diff --git a/Cargo.lock b/Cargo.lock index 3ad5ea42c..191566d6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3539,7 +3539,7 @@ dependencies = [ [[package]] name = "omg" -version = "0.2.0" +version = "0.2.1" dependencies = [ "ahash", "alpm", @@ -3934,9 +3934,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.16" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pin-utils" diff --git a/Cargo.toml b/Cargo.toml index 2364f89f0..be0ca7265 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "omg" -version = "0.2.0" +version = "0.2.1" edition = "2024" rust-version = "1.95.0" description = "The Fastest Unified Package Manager for Arch Linux + All Language Runtimes" diff --git a/docs/cli.md b/docs/cli.md index 0e524d129..c928e7506 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1174,6 +1174,9 @@ omg tool install ripgrep # Install jq omg tool install jq +# Install an exact published RubyGems version using the selected OMG Ruby or system Ruby +omg tool install gem:rake@13.3.1 + # List installed tools omg tool list @@ -1224,6 +1227,8 @@ lifecycle scripts are disabled and registry signatures/provenance are audited; pip accepts wheels only; Cargo requires the published lockfile; and Go uses the public module proxy and checksum database. +Pinned RubyGems installs require an explicit clean decision from the live OMG API for the requested version and all resolved dependencies. OMG verifies each archive against the SHA-256 published by RubyGems and installs the reviewed files into a private gem home. Gems with native build extensions or RubyGems plugins are currently rejected. + Registry-backed managers accept registry package names only. npm GitHub shorthands, Git URLs, tarball URLs, and local package paths are rejected so a package name cannot silently select a less verified source. Go module paths are diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index e69a6ede5..6e6a62353 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -2565,7 +2565,7 @@ dependencies = [ [[package]] name = "omg" -version = "0.2.0" +version = "0.2.1" dependencies = [ "ahash", "anyhow", diff --git a/scripts/check-qemu-controller.sh b/scripts/check-qemu-controller.sh index 4d6172c75..1d1b6d87c 100644 --- a/scripts/check-qemu-controller.sh +++ b/scripts/check-qemu-controller.sh @@ -20,8 +20,8 @@ done # https://security-tracker.debian.org/tracker/source-package/libslirp version=$(dpkg-query -W -f='${Version}' libslirp0) [[ -n "$version" && "$version" != *$'\n'* ]] || exit 3 -printf 'libslirp0=%s minimum=4.9.5-1\n' "$version" -if ! dpkg --compare-versions "$version" ge '4.9.5-1'; then +printf 'libslirp0=%s minimum=4.9.7-1\n' "$version" +if ! dpkg --compare-versions "$version" ge '4.9.7-1'; then printf 'error: libslirp0 is below the patched controller floor\n' >&2 exit 3 fi diff --git a/scripts/install-qemu-libslirp.py b/scripts/install-qemu-libslirp.py index b2246b05a..3aaa18c83 100644 --- a/scripts/install-qemu-libslirp.py +++ b/scripts/install-qemu-libslirp.py @@ -9,13 +9,21 @@ import subprocess import tempfile -# Debian's signed sid Packages indexes and matching downloads, 2026-10-03. -# https://security-tracker.debian.org/tracker/CVE-2026-95507 -# https://security-tracker.debian.org/tracker/CVE-2026-95508 -VERSION = "4.9.5-1" +# Debian's signed sid Packages indexes and matching downloads, 2026-12-04. +# https://security-tracker.debian.org/tracker/source-package/libslirp +# Snapshot file IDs locate the archived bytes. The signed index supplies the SHA-256. +VERSION = "4.9.7-1" PINS = { - "amd64": {"size": 71872, "sha256": "3fad48bcc3830a8d236678042e246121cfac26931311874d0a69f862dd82e5d3"}, - "arm64": {"size": 62600, "sha256": "ae1f711bc86fc0336773f67a1df9f5372c9596016181b4130c6fdf36efe159bb"}, + "amd64": { + "size": 73912, + "sha256": "0f681317e59fb84aa69bc0246a5b4e5cd4c83ef685657c7a0ce93dc850cfb79e", + "snapshot": "2bced765b5df987cd3cbc3e6f57b77fc9ac85657" + }, + "arm64": { + "size": 64904, + "sha256": "bad25e3be87ccd920859bc8485726109db9385868e861c7af54ebb83675f4066", + "snapshot": "5518ed511caafc7dadd0b88852f39d75b34cede6" + } } @@ -45,7 +53,7 @@ def install(qemu_package): raise ValueError("Unsupported controller architecture") pin = PINS[architecture] filename = f"libslirp0_{VERSION}_{architecture}.deb" - url = "https://deb.debian.org/debian/pool/main/libs/libslirp/" + filename + url = "https://snapshot.debian.org/file/" + pin["snapshot"] with tempfile.TemporaryDirectory(prefix="omg-libslirp-") as directory: path = Path(directory) / filename subprocess.run(["curl", "--fail", "--show-error", "--silent", "--location", @@ -69,7 +77,7 @@ def install(qemu_package): library = ctypes.CDLL(matches[0]) library.slirp_version_string.restype = ctypes.c_char_p runtime = library.slirp_version_string().decode("ascii") - if runtime != "4.9.5": + if runtime != VERSION.split("-", 1)[0]: raise ValueError("Loaded libslirp version mismatch") print(json.dumps({"url": url, "sha256": pin["sha256"], "size": pin["size"], "package": fields, "installed": installed, "library": matches[0], diff --git a/scripts/test_qemu_controller_floor.py b/scripts/test_qemu_controller_floor.py index d5a259aa6..a380b51bf 100644 --- a/scripts/test_qemu_controller_floor.py +++ b/scripts/test_qemu_controller_floor.py @@ -10,10 +10,10 @@ class QemuControllerFloorTests(unittest.TestCase): - def run_gate(self, query_status=0, comparator_status=0, version='1:10.0.13+ds-0+deb13u1', package='qemu-system-x86', slirp_version='4.9.5-1'): + def run_gate(self, query_status=0, comparator_status=0, version='1:10.0.13+ds-0+deb13u1', package='qemu-system-x86', slirp_version='4.9.7-1'): gate = (ROOT / 'scripts/check-qemu-controller.sh').read_text(encoding='utf-8') prefix = '''dpkg-query() { if [[ "$3" == libslirp0 ]]; then printf '%s' "$SLIRP_VERSION"; else printf '%s' "$FIXTURE_VERSION"; fi; return "$QUERY_STATUS"; } -dpkg() { [[ "$1" == --compare-versions && "$3" == ge && ( "$4" == '1:10.0.13+ds-0+deb13u1' || "$4" == '4.9.5-1' ) ]] || return 99; return "$COMPARATOR_STATUS"; } +dpkg() { [[ "$1" == --compare-versions && "$3" == ge && ( "$4" == '1:10.0.13+ds-0+deb13u1' || "$4" == '4.9.7-1' ) ]] || return 99; return "$COMPARATOR_STATUS"; } ''' return subprocess.run([BASH, '-c', prefix + gate, '_', package], env=dict(os.environ, FIXTURE_VERSION=version, QUERY_STATUS=str(query_status), @@ -22,8 +22,8 @@ def run_gate(self, query_status=0, comparator_status=0, version='1:10.0.13+ds-0+ def test_rejects_affected_libslirp_with_real_debian_version_comparison(self): gate = (ROOT / 'scripts/check-qemu-controller.sh').read_text(encoding='utf-8') prefix = 'dpkg-query() { if [[ "$3" == libslirp0 ]]; then printf "%s" "$SLIRP_VERSION"; else printf "1:10.0.13+ds-0+deb13u1"; fi; }\n' - for version, accepted in [('4.8.0-1+deb13u1', False), ('4.9.4-1', False), - ('4.9.5-1', True), ('4.9.5-2', True)]: + for version, accepted in [('4.8.0-1+deb13u1', False), ('4.9.5-1', False), ('4.9.6-1', False), + ('4.9.7-1', True), ('4.9.7-2', True)]: with self.subTest(version=version): result = subprocess.run([BASH, '-c', prefix + gate, '_', 'qemu-system-x86'], env=dict(os.environ, SLIRP_VERSION=version), capture_output=True, text=True, timeout=10) @@ -46,7 +46,7 @@ def test_rejects_missing_old_or_invalid_package_evidence(self): def test_real_debian_version_ordering(self): gate = (ROOT / 'scripts/check-qemu-controller.sh').read_text(encoding='utf-8') prefix = '''dpkg-query() { - if [[ "$3" == libslirp0 ]]; then printf "4.9.5-1"; + if [[ "$3" == libslirp0 ]]; then printf "4.9.7-1"; elif [[ "$3" == "$FIXTURE_PACKAGE" ]]; then printf "%s" "$FIXTURE_VERSION"; else printf "1:10.0.13+ds-0+deb13u1"; fi; } diff --git a/scripts/test_qemu_libslirp.py b/scripts/test_qemu_libslirp.py index 6a9568f02..03a24f590 100644 --- a/scripts/test_qemu_libslirp.py +++ b/scripts/test_qemu_libslirp.py @@ -15,7 +15,7 @@ class LibslirpPackageTests(unittest.TestCase): def archive(self, directory, **changes): - fields = {"Package": "libslirp0", "Source": "libslirp", "Version": "4.9.5-1", + fields = {"Package": "libslirp0", "Source": "libslirp", "Version": "4.9.7-1", "Architecture": "amd64", "Maintainer": "Fixture ", "Description": "Synthetic package identity fixture"} fields.update(changes) @@ -34,7 +34,7 @@ def test_accepts_actual_debian_archive_identity(self): archive, pin = self.archive(directory) fields = installer.verify_package(archive, "amd64", pin) self.assertEqual(fields, {"Package": "libslirp0", "Source": "libslirp", - "Version": "4.9.5-1", "Architecture": "amd64"}) + "Version": "4.9.7-1", "Architecture": "amd64"}) def test_rejects_coherent_wrong_package_source_version_or_architecture(self): for changes in ({"Package": "another-package"}, {"Source": "another-source"}, diff --git a/src/cli/args.rs b/src/cli/args.rs index cec9b42f9..10ea18593 100644 --- a/src/cli/args.rs +++ b/src/cli/args.rs @@ -858,9 +858,9 @@ pub enum EnvCommands { #[derive(Subcommand, Debug)] pub enum ToolCommands { - /// Install a dev tool from any source (Pacman, Cargo, NPM, Pip, Go) + /// Install a dev tool from any source (Pacman, Cargo, NPM, Pip, Go, RubyGems) Install { - /// Tool name (e.g. ripgrep, jq, tldr) + /// Tool name or pinned RubyGem (e.g. ripgrep, gem:rake@13.3.1) name: String, }, /// List installed tools diff --git a/src/cli/tool.rs b/src/cli/tool.rs index e7a416e38..afb566acf 100644 --- a/src/cli/tool.rs +++ b/src/cli/tool.rs @@ -1,3 +1,5 @@ +mod gem; + use crate::cli::{CliContext, LocalCommandRunner, ToolCommands}; use anyhow::{Context, Result}; use console::user_attended; @@ -81,6 +83,7 @@ fn validate_managed_package(manager: &str, package: &str) -> Result<()> { }; let valid = match manager { "npm" => crate::core::security::npm::NpmSpec::parse(package).is_ok(), + "gem" => gem::parse_request(package).is_ok(), "cargo" => crate::runtimes::cargo_tool::validate_request(package).is_ok(), "pip" => crate::runtimes::pip_tool::validate_request(package).is_ok(), "pacman" => !package.contains('/') && !package.contains('@') && registry_name(package), @@ -757,7 +760,7 @@ fn installed_tool_names_in(tools_dir: &Path) -> Result> { } } - for manager in ["cargo", "npm", "pip", "go"] { + for manager in ["cargo", "npm", "pip", "go", "gem"] { let manager_dir = tools_dir.join(manager); let entries = match fs::read_dir(&manager_dir) { Ok(entries) => entries, @@ -844,6 +847,16 @@ pub async fn install(name: &str) -> Result<()> { Go, } + if let Some(request) = name.strip_prefix("gem:") { + return gem::install_request( + request, + get_dirs(), + std::sync::Arc::new(crate::core::security::vulnerability::VulnerabilityScanner::new()), + crate::runtimes::security::RuntimeSecurity::default(), + ) + .await; + } + // SECURITY: Validate tool name crate::core::security::validate_package_name(name)?; @@ -1047,6 +1060,15 @@ fn install_managed_blocking( runtime_security, )?); } + "gem" => { + tool_admission = Some(gem::install( + pkg, + &staging_dir, + tools_dir, + runtime_security, + advisories.as_ref(), + )?); + } "cargo" | "go" | "pip" => { let install = match manager { "cargo" => crate::runtimes::cargo_tool::install_reviewed, @@ -1063,7 +1085,7 @@ fn install_managed_blocking( )?); } _ => anyhow::bail!( - "Unknown package manager '{manager}'. Supported: npm, cargo, pip, go, pacman" + "Unknown package manager '{manager}'. Supported: npm, cargo, pip, go, gem, pacman" ), } if let Some(admission) = &npm_admission { @@ -1360,7 +1382,7 @@ pub async fn remove(name: &str) -> Result<()> { } } else { candidates.extend( - ["cargo", "npm", "pip", "go"] + ["cargo", "npm", "pip", "go", "gem"] .into_iter() .map(|manager| (manager, tools_dir.join(manager).join(name))), ); @@ -1924,7 +1946,11 @@ with zipfile.ZipFile(sys.argv[1], 'w') as archive: } #[cfg(unix)] - fn prepare_managed_registry_fixture(tools: &Path, runtime: &str, programs: &[(&str, &Path)]) { + pub(super) fn prepare_managed_registry_fixture( + tools: &Path, + runtime: &str, + programs: &[(&str, &Path)], + ) { use std::os::unix::fs::PermissionsExt as _; let versions = tools.parent().unwrap().join("versions").join(runtime); let version = versions.join("1.78.0"); @@ -1986,6 +2012,17 @@ with zipfile.ZipFile(sys.argv[1], 'w') as archive: .unwrap(); } + #[tokio::test] + async fn sources_without_gem_coverage_cannot_authorize_gems() { + use crate::core::security::vulnerability::VulnerabilitySource as _; + assert!( + TestNpmAdvisories::default() + .require_clean_gems(&[("fixture".into(), "1".into())]) + .await + .is_err() + ); + } + #[derive(Default)] struct TestNpmAdvisories { findings: Vec, diff --git a/src/cli/tool/gem.rs b/src/cli/tool/gem.rs new file mode 100644 index 000000000..30103acb6 --- /dev/null +++ b/src/cli/tool/gem.rs @@ -0,0 +1,199 @@ +//! Exact RubyGems installs with a fresh OMG decision before artifact download. +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeSet, path::Path}; + +use crate::core::security::vulnerability::VulnerabilitySource; +use crate::runtimes::{ + package_manager::{ManagedRuntime, ReviewedTool}, + security::RuntimeSecurity, + tool_artifacts, +}; + +pub(super) fn parse_request(request: &str) -> Result<(&str, &str)> { + let (name, version) = request + .split_once('@') + .context("Use gem:NAME@EXACT_VERSION")?; + crate::core::security::validate_package_name(name)?; + ensure!( + name.starts_with(|c: char| c.is_ascii_alphanumeric()) + && name.bytes().any(|b| b.is_ascii_alphabetic()) + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)), + "Invalid RubyGems name" + ); + ensure!( + version.len() <= 128 + && version.starts_with(|c: char| c.is_ascii_digit()) + && version + .split('.') + .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric())), + "Expected an exact canonical RubyGems version" + ); + Ok((name, version)) +} + +#[derive(Deserialize, Serialize)] +struct ResolvedGem { + name: String, + version: String, + platform: String, +} + +struct GemReview { + digest: String, + runtime: Option, +} + +impl ReviewedTool for GemReview { + fn verify(&self, prefix: &Path) -> Result<()> { + if let Some(runtime) = &self.runtime { + runtime.verify()?; + } + ensure!( + tool_artifacts::tree(prefix)? == self.digest, + "Reviewed RubyGems install changed before activation" + ); + Ok(()) + } +} + +pub(super) async fn install_request( + request: &str, + (tools, bin): (std::path::PathBuf, std::path::PathBuf), + source: std::sync::Arc, + security: RuntimeSecurity, +) -> Result<()> { + let (name, _) = parse_request(request)?; + crate::core::paths::create_private_data_directory(&tools)?; + crate::core::paths::create_private_data_directory(&bin)?; + super::install_managed_with_advisories("gem", request, name, &tools, &bin, source, security) + .await +} + +fn ruby_command(runtime: Option<&ManagedRuntime>) -> Result { + match runtime { + Some(runtime) => runtime.command_path("ruby"), + None => crate::core::privilege::root_controlled_program_path("ruby") + .context("Select an OMG Ruby or install a system Ruby with RubyGems"), + } +} + +fn selected_runtime( + tools_dir: &Path, + security: &RuntimeSecurity, +) -> Result> { + let selected = tools_dir + .parent() + .context("Missing OMG data root")? + .join("versions/ruby/current"); + let runtime = match std::fs::symlink_metadata(selected) { + Ok(_) => Some(ManagedRuntime::open("ruby", tools_dir, security)?), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(error.into()), + }; + Ok(runtime) +} + +pub(super) fn install( + request: &str, + prefix: &Path, + tools_dir: &Path, + security: &RuntimeSecurity, + source: &dyn VulnerabilitySource, +) -> Result> { + let (name, version) = parse_request(request)?; + let admit = |packages: &[(String, String)]| { + tool_artifacts::scoped_future(source.require_clean_gems(packages)) + }; + admit(&[(name.to_owned(), version.to_owned())])?; + let runtime = selected_runtime(tools_dir, security)?; + let scratch = tempfile::Builder::new() + .prefix(".gem-artifacts-") + .tempdir_in(prefix.parent().context("Missing gem tools directory")?)?; + let command = |action: &str| -> Result { + let ruby = ruby_command(runtime.as_ref())?; + let mut cmd = super::restricted_manager_command(ruby, scratch.path())?; + cmd.env_clear() + .env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin") + .env("HOME", scratch.path()) + .env("GEM_HOME", scratch.path().join("gem-home")) + .env("GEM_PATH", scratch.path().join("gem-home")) + .arg("--disable-gems") + .arg("-e") + .arg(include_str!("gem_install.rb")) + .arg("--") + .arg(action); + Ok(cmd) + }; + let mut resolve = command("resolve")?; + resolve.arg(name).arg(version); + let metadata = tool_artifacts::run(resolve, "RubyGems metadata resolution", false)?; + let graph: Vec = + serde_json::from_slice(&metadata).context("Invalid RubyGems resolution metadata")?; + ensure!( + !graph.is_empty() && graph.len() <= 256, + "Invalid RubyGems dependency graph size" + ); + let mut names = BTreeSet::new(); + let mut coordinates = Vec::with_capacity(graph.len()); + for gem in &graph { + parse_request(&format!("{}@{}", gem.name, gem.version))?; + ensure!( + names.insert(&gem.name) + && !gem.platform.is_empty() + && gem.platform.len() <= 128 + && gem + .platform + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)), + "Invalid or duplicate RubyGems dependency" + ); + coordinates.push((gem.name.clone(), gem.version.clone())); + } + ensure!( + coordinates.iter().any(|(n, v)| n == name && v == version), + "RubyGems resolver omitted the requested version" + ); + admit(&coordinates)?; + let mut install = command("install")?; + install + .arg(name) + .arg(prefix.canonicalize()?) + .arg(serde_json::to_string(&graph)?); + tool_artifacts::run(install, "RubyGems verified installation", false)?; + admit(&coordinates)?; + super::write_security_receipt(prefix, "gem", request)?; + Ok(Box::new(GemReview { + digest: tool_artifacts::tree(prefix)?, + runtime, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exact_gem_coordinates_only() { + for request in [ + "rake", + "../rake@1", + "rake@>=1", + "rake@1@git", + "rake@1..2", + "x/y@1", + ] { + assert!(parse_request(request).is_err(), "{request}"); + } + assert_eq!( + parse_request("uznex-api-doc@99.0.1").unwrap(), + ("uznex-api-doc", "99.0.1") + ); + } +} + +#[cfg(all(test, unix))] +#[path = "gem_install_tests.rs"] +mod install_tests; diff --git a/src/cli/tool/gem_install.rb b/src/cli/tool/gem_install.rb new file mode 100644 index 000000000..87cbd7818 --- /dev/null +++ b/src/cli/tool/gem_install.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true + +require "rubygems" +require "json" + +action, name, target, encoded = ARGV +if action == "resolve" + require "rubygems/resolver" + require "rubygems/remote_fetcher" + requirement = Gem::Dependency.new(name, "= #{target}") + set = Gem::Resolver::APISet.new("https://index.rubygems.org/info/") + requests = Gem::Resolver.new([requirement], set).resolve + puts JSON.generate(requests.map { |r| {name: r.name, version: r.version.to_s, platform: r.spec.platform.to_s} }) + exit +end + +abort "Unknown gem installation action" unless action == "install" +require "digest" +require "net/http" +require "rubygems/installer" +require "rubygems/package" + +# The caller has admitted every coordinate in this graph. All network paths +# are derived from validated components under the same TLS registry origin. +def registry_get(path, limit) + uri = URI("https://rubygems.org#{path}") + body = +"".b + Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 15, read_timeout: 30) do |http| + http.request(Net::HTTP::Get.new(uri)) do |response| + abort "RubyGems returned HTTP #{response.code} for #{path}" unless response.is_a?(Net::HTTPOK) + response.read_body do |chunk| + abort "RubyGems response exceeds limit" if body.bytesize + chunk.bytesize > limit + body << chunk + end + end + end + body +end + +graph = JSON.parse(encoded) +versions = graph.to_h { |g| [g.fetch("name"), Gem::Version.new(g.fetch("version"))] } +receipts = [] +archive_bytes = 0 +archives = graph.map do |g| + n, v, p = g.values_at("name", "version", "platform") + meta = JSON.parse(registry_get("/api/v2/rubygems/#{n}/versions/#{v}.json?platform=#{p}", 2 << 20)) + abort "Registry coordinate mismatch" unless meta.values_at("name", "version", "platform") == [n, v, p] + filename = "#{n}-#{v}#{p == "ruby" ? "" : "-#{p}"}.gem" + bytes = registry_get("/downloads/#{filename}", 64 << 20) + archive_bytes += bytes.bytesize + abort "RubyGems dependency graph exceeds archive budget" if archive_bytes > (512 << 20) + sha = Digest::SHA256.hexdigest(bytes) + abort "Gem digest mismatch for #{filename}" unless sha == meta.fetch("sha") + File.binwrite(filename, bytes) + package = Gem::Package.new(filename) + package.verify + spec = package.spec + abort "Gem identity mismatch" unless [spec.name, spec.version.to_s, spec.platform.to_s] == [n, v, p] + abort "Incompatible Ruby or RubyGems" unless spec.required_ruby_version.satisfied_by?(Gem.ruby_version) && + spec.required_rubygems_version.satisfied_by?(Gem.rubygems_version) + spec.runtime_dependencies.each do |dep| + abort "Unreviewed dependency of #{n}: #{dep}" unless versions.key?(dep.name) && dep.match?(dep.name, versions.fetch(dep.name)) + end + abort "Gem has installation hooks or native extensions" unless spec.extensions.empty? && + spec.files.none? { |file| File.basename(file).match?(/\Arubygems_plugin\./) } + abort "Invalid gem executable directory" unless spec.bindir.to_s.split("/", -1).all? { |part| /\A[[:alnum:]_-][[:alnum:]_.-]*\z/.match?(part) } || spec.executables.empty? + abort "Invalid gem executable path" unless spec.executables.all? { |exe| /\A[a-zA-Z0-9_+.-]+\z/.match?(exe) && !exe.start_with?(".") } + receipts << g.merge("sha256" => sha) + [filename, spec] +end + +# Install only the files verified above. No remote resolution or installer +# hooks from the user's gem home participate in this phase. +Gem.use_paths(target, [target]) +wrappers = File.join(Dir.pwd, "wrappers") +Dir.mkdir(wrappers) +archives.each do |filename, _spec| + Gem::Installer.at(filename, install_dir: target, bin_dir: wrappers, ignore_dependencies: true, + wrappers: true, document: []).install +end +root = archives.map(&:last).find { |spec| spec.name == name } +bin = File.join(target, "bin") +Dir.mkdir(bin) unless File.directory?(bin) +root.executables.each do |exe| + path = File.join(bin, exe) + File.open(path, "wx", 0o755) do |f| + f.puts "#!#{Gem.ruby}", 'require "rubygems"', + 'prefix = File.expand_path("..", File.dirname(File.realpath(__FILE__)))', + 'Gem.use_paths(prefix, [prefix])', + "load Gem.activate_bin_path(#{name.dump}, #{exe.dump}, #{("= " + root.version.to_s).dump})" + end +end +File.write(File.join(target, ".omg-package-advisory-review.json"), JSON.pretty_generate(receipts)) diff --git a/src/cli/tool/gem_install_tests.rs b/src/cli/tool/gem_install_tests.rs new file mode 100644 index 000000000..ad0f9d3cb --- /dev/null +++ b/src/cli/tool/gem_install_tests.rs @@ -0,0 +1,124 @@ +use super::*; +use crate::core::security::vulnerability::{VulnerabilityScanner, gem_admission_fixture}; +use std::{fs, sync::Arc}; + +fn verdict(name: &str, rejected: bool) -> serde_json::Value { + let mut result = serde_json::json!({ + "package":{"ecosystem":"RubyGems","name":name,"version":"1.0"}, + "status":"no_match","policy_verdict":"allow","findings":[],"gaps":[] + }); + if rejected { + result["status"] = "matched".into(); + result["policy_verdict"] = "reject_malware".into(); + result["findings"] = serde_json::json!([{"id":"MAL-fixture","kind":"malware"}]); + } + result +} + +fn response(rows: &[serde_json::Value]) -> String { + serde_json::json!({"schema_version":2, "results":rows}).to_string() +} + +#[tokio::test] +async fn gem_root_and_dependency_admission_precede_publication() -> Result<()> { + let owner = tempfile::tempdir()?; + let tools = owner.path().join("tools"); + let bin = owner.path().join("bin"); + let security = RuntimeSecurity::fixture(); + assert!(super::super::install("../invalid").await.is_err()); + assert!(super::super::install("gem:invalid").await.is_err()); + assert!(selected_runtime(&tools, &security)?.is_none()); + assert_eq!( + ruby_command(None).ok(), + crate::core::privilege::root_controlled_program_path("ruby").ok() + ); + fs::write(owner.path().join("versions"), b"non-directory")?; + assert!(selected_runtime(&tools, &security).is_err()); + fs::remove_file(owner.path().join("versions"))?; + let mock_ruby = owner.path().join("reviewed-ruby"); + fs::write( + &mock_ruby, + r#"#!/bin/sh +set -eu +case "$5" in +resolve) + if [ "$6" = malformed ]; then printf garbage; exit 0; fi + printf '[{"name":"%s","version":"1.0","platform":"x86_64-linux"},{"name":"dep","version":"1.0","platform":"ruby"}]' "$6" ;; +install) + mkdir "$7/bin"; printf '#!/bin/sh\necho reviewed\n' > "$7/bin/fixture"; chmod 755 "$7/bin/fixture" ;; +*) exit 21 ;; +esac +"#, + ).expect("write controlled Ruby driver"); + super::super::tests::prepare_managed_registry_fixture(&tools, "ruby", &[("ruby", &mock_ruby)]); + let (malformed, replies) = + gem_admission_fixture(vec![response(&[verdict("malformed", false)])]).await?; + let error = install_request( + "malformed@1.0", + (tools.clone(), bin.clone()), + Arc::new(malformed), + RuntimeSecurity::fixture(), + ) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("Invalid RubyGems resolution metadata") + ); + replies.await??; + let root = verdict("fixture", false); + let clean = response(&[root.clone(), verdict("dep", false)]); + let (scanner, server) = gem_admission_fixture(vec![ + response(&[verdict("fixture", true)]), + response(std::slice::from_ref(&root)), + response(&[root.clone(), verdict("dep", true)]), + response(std::slice::from_ref(&root)), + clean.clone(), + clean, + ]) + .await?; + let source = Arc::new(scanner); + let run = || { + install_request( + "fixture@1.0", + (tools.clone(), bin.clone()), + source.clone(), + RuntimeSecurity::fixture(), + ) + }; + for package in ["fixture", "dep"] { + let error = run().await.unwrap_err().to_string(); + assert!( + error.contains(&format!("{package}@1.0")) && error.contains("MAL-fixture"), + "{error}" + ); + assert!(!bin.join("fixture").exists() && !tools.join("gem/fixture").exists()); + } + run().await?; + server.await??; + assert!(super::super::installed_tool_names_in(&tools)?.contains(&"fixture".to_string())); + assert_eq!( + std::process::Command::new(bin.join("fixture")) + .output()? + .stdout, + b"reviewed\n" + ); + let prefix = tools.join("gem/fixture"); + let review = GemReview { + digest: tool_artifacts::tree(&prefix)?, + runtime: None, + }; + review.verify(&prefix)?; + fs::write(prefix.join("bin/fixture"), b"changed")?; + assert!(review.verify(&prefix).is_err()); + let missing = + VulnerabilityScanner::with_osv_endpoint("http://127.0.0.1".into(), "RubyGems".into()); + assert!( + missing + .require_clean_gems(&[("fixture".into(), "1.0".into())]) + .await + .is_err() + ); + Ok(()) +} diff --git a/src/core/security/vulnerability.rs b/src/core/security/vulnerability.rs index 75a27b1fc..dec733180 100644 --- a/src/core/security/vulnerability.rs +++ b/src/core/security/vulnerability.rs @@ -228,6 +228,14 @@ pub fn validate_assessment_inventory( /// Coverage-aware batch evidence. Implementations may not omit unmatched inputs. pub trait VulnerabilitySource: Send + Sync { + /// A source without exact RubyGems verdicts cannot authorize a gem download. + fn require_clean_gems<'a>( + &'a self, + _packages: &'a [(String, String)], + ) -> Pin> + Send + 'a>> { + Box::pin(async { anyhow::bail!("Advisory source cannot admit RubyGems packages") }) + } + fn assess_packages<'a>( &'a self, packages: &'a [SecurityPackage], @@ -775,6 +783,33 @@ impl VulnerabilityScanner { Ok(reports) } + pub(crate) async fn require_clean_gems( + &self, + packages: &[(String, String)], + ) -> anyhow::Result<()> { + let endpoint = self + .local_assess_url + .as_deref() + .ok_or_else(|| anyhow::anyhow!("Missing OMG assessment endpoint"))?; + for ((name, version), outcome) in self + .assess_local_coordinates(endpoint, "RubyGems", packages, AssessmentUse::Admission) + .await? + { + anyhow::ensure!( + outcome.clean, + "Blocked RubyGems {name}@{version}: {:?} ({})", + outcome.verdict, + outcome + .findings + .iter() + .map(|f| f.id.as_str()) + .collect::>() + .join(", ") + ); + } + Ok(()) + } + async fn assess_local_coordinates( &self, endpoint: &str, @@ -880,6 +915,7 @@ struct LocalAssessResponse { #[derive(Debug, Deserialize)] struct LocalAssessPackage { + ecosystem: Option, name: String, version: String, } @@ -916,8 +952,15 @@ struct LocalAssessResult { package: LocalAssessPackage, status: String, policy_verdict: LocalPolicyVerdict, - #[serde(default)] - findings: Vec, + gaps: Option>, + #[serde(default, deserialize_with = "present_findings")] + findings: Option>, +} + +fn present_findings<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result>, D::Error> { + Vec::deserialize(deserializer).map(Some) } #[derive(Debug, Clone)] @@ -930,6 +973,8 @@ struct LocalFindingReport { #[derive(Debug, Clone)] struct LocalCoordinateOutcome { + clean: bool, + verdict: LocalPolicyVerdict, is_partial: bool, findings: Vec, } @@ -996,12 +1041,18 @@ fn parse_local_advisory_severity(raw: Option<&str>) -> (Option, Option LocalCoordinateOutcome { + let clean = result.package.ecosystem.as_deref() == Some("RubyGems") + && result.status == "no_match" + && result.policy_verdict == LocalPolicyVerdict::Allow + && result.findings.as_ref().is_some_and(Vec::is_empty) + && result.gaps.is_some_and(|gaps| gaps.is_empty()); let verdict_is_reject = matches!( result.policy_verdict, LocalPolicyVerdict::RejectMalware | LocalPolicyVerdict::RejectExploited ); - let mut findings = Vec::with_capacity(result.findings.len()); - for finding in result.findings { + let raw_findings = result.findings.unwrap_or_default(); + let mut findings = Vec::with_capacity(raw_findings.len()); + for finding in raw_findings { let is_malware = finding.kind == "malware" || finding.id.starts_with("MAL-"); let is_exploited = finding.in_zero_day || finding.in_kev; let (score, mut advisory_severity) = @@ -1050,12 +1101,21 @@ fn map_local_assessment_result(result: LocalAssessResult) -> LocalCoordinateOutc || result.status == "partial" || (verdict_is_reject && findings.is_empty()); LocalCoordinateOutcome { + clean, + verdict: result.policy_verdict, is_partial, findings, } } impl VulnerabilitySource for VulnerabilityScanner { + fn require_clean_gems<'a>( + &'a self, + packages: &'a [(String, String)], + ) -> Pin> + Send + 'a>> { + Box::pin(VulnerabilityScanner::require_clean_gems(self, packages)) + } + fn assess_packages<'a>( &'a self, packages: &'a [SecurityPackage], @@ -1404,10 +1464,38 @@ impl VulnerabilityScanner { } } +#[cfg(test)] +pub(crate) use tests::gem_admission_fixture; + #[cfg(test)] mod tests { use super::*; + #[test] + fn ruby_gem_admission_requires_an_explicit_complete_allow() { + let allow = serde_json::json!({ + "package":{"ecosystem":"RubyGems","name":"rake","version":"13.3.1"}, + "status":"no_match","policy_verdict":"allow","findings":[],"gaps":[] + }); + let clean = + |reply| map_local_assessment_result(serde_json::from_value(reply).unwrap()).clean; + assert!(clean(allow.clone())); + let mut missing = allow.clone(); + missing.as_object_mut().unwrap().remove("findings"); + assert!(!clean(missing)); + for (pointer, value) in [ + ("/status", serde_json::json!("partial")), + ("/policy_verdict", serde_json::json!("reject_malware")), + ("/package/ecosystem", serde_json::json!("npm")), + ("/gaps", serde_json::json!(["unavailable"])), + ("/gaps", serde_json::json!(null)), + ] { + let mut reply = allow.clone(); + *reply.pointer_mut(pointer).unwrap() = value; + assert!(!clean(reply), "{pointer}"); + } + } + #[cfg(feature = "arch")] fn arch_snapshot_fixture(payload: &str) -> Vec { use sha2::{Digest, Sha256}; @@ -2332,6 +2420,18 @@ mod tests { Ok(()) } + pub(crate) async fn gem_admission_fixture( + responses: Vec, + ) -> anyhow::Result<( + VulnerabilityScanner, + tokio::task::JoinHandle>, + )> { + let (mut scanner, server) = + serve_osv_responses(responses.into_iter().map(|body| (body, false)).collect()).await?; + scanner.local_assess_url = Some(scanner.osv_api_url.clone()); + Ok((scanner, server)) + } + async fn serve_osv_responses( responses: Vec<(String, bool)>, ) -> anyhow::Result<( diff --git a/src/runtimes/package_manager.rs b/src/runtimes/package_manager.rs index 4bf82e146..44e8add7a 100644 --- a/src/runtimes/package_manager.rs +++ b/src/runtimes/package_manager.rs @@ -27,7 +27,7 @@ impl ManagedRuntime { security: &RuntimeSecurity, ) -> Result { ensure!( - matches!(runtime, "rust" | "go" | "python"), + matches!(runtime, "rust" | "go" | "python" | "ruby"), "Unsupported package-manager runtime: {runtime}" ); let data_root = tools_dir