class MXC::Sandbox
A sandbox policy: what a command may read, write and reach, and how long it may run.
Setters return the sandbox, so they chain, and nil resets a setting to its default:
sandbox = MXC.sandbox .with_readable("app/skills") .with_writable(Rails.root.join("tmp")) .with_network(allow: ["pypi.org", "*.pythonhosted.org"]) .with_timeout(30) sandbox.run("python3 app/skills/build.py") sandbox.run("python3", "app/skills/convert.py", params[:filename])
Subclasses declare the same settings with class macros:
class SkillSandbox < MXC::Sandbox readable "app/skills" writable "tmp/skills" network false timeout 30 limits cpu_time: 60, memory: 2 * 1024**3 priority :low end SkillSandbox.new.run("python3 app/skills/build.py")
Public Class Methods
Source
# File lib/mxc/sandbox.rb, line 78 def backend(name) = configure { |sandbox| sandbox.with_backend(name) }
Sets every instance’s backend.
Source
# File lib/mxc/sandbox.rb, line 56 def denied(*paths) = configure { |sandbox| sandbox.with_denied(*paths) }
Adds paths every instance hides, even inside readable or writable paths.
Source
# File lib/mxc/sandbox.rb, line 72 def directory(path) = configure { |sandbox| sandbox.with_directory(path) }
Sets every instance’s working directory.
Source
# File lib/mxc/sandbox.rb, line 69 def env(variables) = configure { |sandbox| sandbox.with_env(variables) }
Adds environment variables for every instance.
Source
# File lib/mxc/sandbox.rb, line 63 def libraries(enabled) = configure { |sandbox| sandbox.with_libraries(enabled) }
Sets whether every instance can read the libraries its programs load. See with_libraries.
Source
# File lib/mxc/sandbox.rb, line 60 def libraries_of(*paths) = configure { |sandbox| sandbox.with_libraries_of(*paths) }
Adds programs and libraries whose shared libraries every instance can load. Takes the same arguments as with_libraries_of.
Source
# File lib/mxc/sandbox.rb, line 81 def limits(...) = configure { |sandbox| sandbox.with_limits(...) }
Sets every instance’s resource limits. Takes the same arguments as with_limits.
Source
# File lib/mxc/sandbox.rb, line 66 def network(...) = configure { |sandbox| sandbox.with_network(...) }
Sets every instance’s network access. Takes the same arguments as with_network.
Source
# File lib/mxc/sandbox.rb, line 124 def initialize(**options) unknown = options.keys - OPTIONS raise ArgumentError, "unknown option#{'s' if unknown.size > 1}: #{unknown.join(', ')}" if unknown.any? inherit(self.class.defaults) options.each { |name, value| apply(name, value) } end
Returns a new sandbox with the class’s defaults, then applies options through the matching setters: readable:, writable:, denied:, network:, env:, directory:, timeout:, backend:, limits: and priority:.
MXC::Sandbox.new(readable: "app/skills", network: { allow: ["pypi.org"] }, timeout: 30) MXC::Sandbox.new(limits: { cpu_time: 60, memory: 2 * 1024**3 }, priority: :low)
Source
# File lib/mxc/sandbox.rb, line 84 def priority(level) = configure { |sandbox| sandbox.with_priority(level) }
Sets every instance’s scheduling priority: :normal, :low, or :lowest.
Source
# File lib/mxc/sandbox.rb, line 50 def readable(*paths) = configure { |sandbox| sandbox.with_readable(*paths) }
Adds paths every instance can read.
Source
# File lib/mxc/sandbox.rb, line 75 def timeout(seconds) = configure { |sandbox| sandbox.with_timeout(seconds) }
Sets every instance’s timeout in seconds.
Source
# File lib/mxc/sandbox.rb, line 53 def writable(*paths) = configure { |sandbox| sandbox.with_writable(*paths) }
Adds paths every instance can read and write.
Public Instance Methods
Source
# File lib/mxc/sandbox.rb, line 355 def availability problem = Preflight.problem(network:, denied:, resources:, backend:) host = MXC.availability(backend:) unless problem problem ||= Preflight.problem(network:, backend: :landlock) if host&.runs_on == :landlock return host unless problem Availability.new(backend:, supported: false, reason: problem.message, remediation: problem.remediation) end
Returns the Availability of this sandbox on this host, with the reason and remediation when it cannot run.
Source
# File lib/mxc/sandbox.rb, line 165 def backend = @settings[:backend] || MXC.config.backend
Returns the backend, falling back to MXC.config.backend.
Source
# File lib/mxc/sandbox.rb, line 144 def denied = @settings[:denied].dup.freeze
Returns the paths hidden from the command, as given.
Source
# File lib/mxc/sandbox.rb, line 159 def directory = @settings[:directory]
Returns the working directory, or nil for the default.
Source
# File lib/mxc/sandbox.rb, line 153 def env = @settings[:env].dup.freeze
Returns the environment variables set for the command.
Source
# File lib/mxc/sandbox.rb, line 150 def libraries = @settings[:libraries]
Returns true when the command can read the libraries its program loads, the default.
Source
# File lib/mxc/sandbox.rb, line 147 def libraries_of = @settings[:libraries_of].dup.freeze
Returns the programs and libraries whose shared libraries the command can load, as given.
Source
# File lib/mxc/sandbox.rb, line 169 def limits = @settings[:limits].dup.freeze
Returns the resource limits, such as { cpu_time: 60, memory: 2147483648 }. A limit that is not set is absent.
Source
# File lib/mxc/sandbox.rb, line 156 def network = @settings[:network]
Returns the network access: false, true, or { allow: [...] } for an allow-list.
Source
# File lib/mxc/sandbox.rb, line 172 def priority = @settings[:priority] || :normal
Returns the scheduling priority: :normal, :low, or :lowest.
Source
# File lib/mxc/sandbox.rb, line 138 def readable = @settings[:readable].dup.freeze
Returns the paths the command can read, as given.
Source
# File lib/mxc/sandbox.rb, line 330 def run(*command, &) return stream(*command, &) if block_given? arguments = command_arguments(command) outcome = StartupFailure.check!(Native.run(command_line(arguments), request(arguments))) Result.new(**outcome, backend: resolved_backend(outcome[:warnings])) end
Runs command and returns its Result once it finishes. Like Kernel#system, one String runs through the platform shell: sh -c, or cmd.exe /d /s /c on Windows. Two or more Strings are a program and its arguments, and each argument reaches the program unchanged, without a shell.
With a block, yields each Chunk of output as it arrives.
On macOS, the command can read the shared library files its program links outside the system’s own, such as Homebrew’s, so programs built against them start. The program is the first argument, or the first word of a command for the shell, found on the PATH of env. See with_libraries_of for libraries the program opens later, and with_libraries to turn this off.
sandbox.run("python3 build.py && ls dist") sandbox.run("python3", "convert.py", params[:filename]) sandbox.run("python3", "build.py") { |chunk| print chunk.content }
Raises ArgumentError without a command or when given an Array. On Windows, it also raises ArgumentError for a program and arguments that start a .bat or .cmd file, because Windows runs those through cmd.exe, which splits the arguments again.
Source
# File lib/mxc/sandbox.rb, line 342 def spawn(*command) arguments = command_arguments(command) native = Native.spawn(command_line(arguments), request(arguments)) Process.new(native, backend: resolved_backend(native.warnings)) end
Source
# File lib/mxc/sandbox.rb, line 349 def supported? availability.supported? end
Returns true when this host can run this sandbox, including its network policy.
Source
# File lib/mxc/sandbox.rb, line 162 def timeout = @settings[:timeout] || MXC.config.timeout
Returns the timeout in seconds, falling back to MXC.config.timeout.
Source
# File lib/mxc/sandbox.rb, line 269 def with_backend(name) @settings[:backend] = name && self.class.backend_name(name) self end
Sets the backend: :auto (Bubblewrap on Linux, Seatbelt on macOS, ProcessContainer on Windows), :bubblewrap, :landlock, :seatbelt, or :process_container.
On Linux, :auto runs on Landlock when Bubblewrap cannot create its namespaces, and says so in Result#warnings. :bubblewrap never does. :landlock needs Linux 6.2 or newer and runs without network access.
Source
# File lib/mxc/sandbox.rb, line 187 def with_denied(*paths) add_paths(:denied, paths) end
Adds paths hidden from the command, even inside readable or writable paths.
Source
# File lib/mxc/sandbox.rb, line 250 def with_directory(path) @settings[:directory] = path && File.path(path) self end
Sets the directory the command starts in. The sandbox must be able to read it. Without one, the command starts in /, or %SystemRoot% on Windows.
Source
# File lib/mxc/sandbox.rb, line 242 def with_env(variables) env = @settings[:env] variables.nil? ? env.clear : variables.each { |name, value| env[name.to_s] = value.to_s } self end
Adds environment variables for the command. The sandbox starts from a minimal environment, not the parent’s. On Windows, that environment keeps the system variables programs need to start, such as SYSTEMROOT and PATH.
sandbox.with_env("LANG" => "C.UTF-8")
Source
# File lib/mxc/sandbox.rb, line 208 def with_libraries(enabled) unless [true, false, nil].include?(enabled) raise ArgumentError, "libraries must be true, false or nil, got #{enabled.inspect}" end @settings[:libraries] = enabled != false self end
Sets whether the command can read the shared libraries its program and libraries_of load, on macOS. true is the default; false grants no library, so the command reads only the system’s and those under readable. nil resets it to true.
sandbox.with_libraries(false)
Source
# File lib/mxc/sandbox.rb, line 199 def with_libraries_of(*paths) add_paths(:libraries_of, paths) end
Adds programs and libraries whose shared libraries the command loads, such as the extensions an interpreter opens. On macOS, the command can read those library files, and the libraries they load in turn, when they are not the system’s own. The program the command runs needs no entry: run grants its libraries already. Elsewhere, on a Mac without the Command Line Tools, and with with_libraries(false), this grants nothing.
sandbox.with_libraries_of(*Dir[File.join(RbConfig::CONFIG["archdir"], "**", "*.bundle")])
# File lib/mxc/sandbox.rb, line 292 def with_limits(reset = (keep = true), **limits) unless keep raise ArgumentError, "pass limits as keywords, or nil to remove them, got #{reset.inspect}" unless reset.nil? @settings[:limits].clear end limits.each { |name, value| set_limit(name, value) } self end
Sets resource limits. Each process the command starts gets its own CPU time and memory.
cpu_time: is the CPU time each process may use, in seconds. It accepts anything that responds to to_f, such as 90 or 2.minutes, and is rounded up to whole seconds on Linux and macOS. A process that uses it up is stopped.
memory: is the memory each process may allocate, in bytes. It accepts anything that responds to to_i, such as 2 * 1024**3 or 2.gigabytes, and is rounded up to whole megabytes. Allocations beyond it fail. Not available on macOS.
processes: is how many processes the command may run at the same time. Windows only.
A limit given as nil is removed, and with_limits(nil) removes them all. Raises ArgumentError for an unknown limit or a value that is not positive.
sandbox.with_limits(cpu_time: 2.minutes, memory: 2.gigabytes)
# File lib/mxc/sandbox.rb, line 223 def with_network(enabled = true, allow: nil) if allow raise ArgumentError, 'pass allow: or true/false, not both' unless enabled == true @settings[:network] = { allow: Array(allow).map(&:to_s).freeze }.freeze else raise ArgumentError, "network must be true, false or nil, got #{enabled.inspect}" unless [true, false, nil].include?(enabled) @settings[:network] = enabled || false end self end
Sets network access. The default, false, gives the command no network at all. true allows any destination. allow: takes a list of hosts the command may reach over HTTP and HTTPS: "pypi.org", "*.pythonhosted.org" (subdomains only), or "example.com:8443" for another port.
sandbox.with_network(allow: ["pypi.org", "*.pythonhosted.org"])
Source
# File lib/mxc/sandbox.rb, line 305 def with_priority(level) @settings[:priority] = level && priority_name(level) self end
Sets the scheduling priority of every process the command starts: :normal (the default), :low (nice 10 on Linux and macOS, below normal on Windows), or :lowest (nice 19, or idle on Windows).
Source
# File lib/mxc/sandbox.rb, line 176 def with_readable(*paths) add_paths(:readable, paths) end
Adds paths the command can read. Accepts Strings and Pathnames; relative paths are expanded from the current directory when the command runs.
Source
# File lib/mxc/sandbox.rb, line 257 def with_timeout(seconds) @settings[:timeout] = self.class.duration(seconds) self end
Sets the timeout in seconds. Accepts anything that responds to to_f, such as 30, 2.5 or 1.minute.
Source
# File lib/mxc/sandbox.rb, line 182 def with_writable(*paths) add_paths(:writable, paths) end
Adds paths the command can read and write. A path that is also readable is writable, whichever was added first. A readable path inside a writable one stays read-only.
Source
# File lib/mxc/sandbox.rb, line 141 def writable = @settings[:writable].dup.freeze
Returns the paths the command can read and write, as given.
Protected Instance Methods
Source
# File lib/mxc/sandbox.rb, line 493 def resources limits = @settings[:limits] return if limits.empty? && priority == :normal { cpu_time_ms: limits[:cpu_time] && (limits[:cpu_time].to_f * 1000).ceil, memory_mb: limits[:memory] && -(-limits[:memory].to_i / MEGABYTE), max_processes: limits[:processes], priority: PRIORITIES.fetch(priority) }.compact end
The resource limits as MXC takes them, or nil when there are none.