Format nix files with nixfmt-tree

This commit is contained in:
Alex David 2025-09-11 07:31:48 -07:00
commit 700189112f
7 changed files with 583 additions and 522 deletions

View file

@ -2,5 +2,6 @@ image: nixos/25.05
environment: environment:
NIX_CONFIG: "experimental-features = nix-command flakes" NIX_CONFIG: "experimental-features = nix-command flakes"
tasks: tasks:
- test-jail-nix: "cd jail.nix/tests && nix run .#runChecks" - test-jail-nix: "cd jail.nix/tests && nix run .#runTests"
- check-format: "cd jail.nix/tests && nix run .#checkFmt"
- build-website: "cd jail.nix/website && nix build -L .#default" - build-website: "cd jail.nix/website && nix build -L .#default"

View file

@ -1,7 +1,9 @@
pkgs: jail: let pkgs: jail:
let
inherit (pkgs) lib; inherit (pkgs) lib;
helpers = import ./helpers.nix pkgs; helpers = import ./helpers.nix pkgs;
in rec { in
rec {
noescape = { noescape = {
sig = "String -> NoEscapedString"; sig = "String -> NoEscapedString";
doc = '' doc = ''
@ -79,9 +81,7 @@ in rec {
} }
``` ```
''; '';
__functor = _: __functor = _: lib.flip lib.pipe;
lib.flip lib.pipe
;
}; };
defer = { defer = {
@ -119,10 +119,9 @@ in rec {
]) ])
``` ```
''; '';
__functor = _: __functor =
combinator: state: _: combinator: state:
state // { deferredPermissions = state.deferredPermissions ++ [ combinator ]; } state // { deferredPermissions = state.deferredPermissions ++ [ combinator ]; };
;
}; };
include-once = { include-once = {
@ -161,12 +160,12 @@ in rec {
]) ])
``` ```
''; '';
__functor = _: __functor =
key: combinator: state: _: key: combinator: state:
if lib.elem key state.includedOnce if lib.elem key state.includedOnce then
then state state
else combinator (state // { includedOnce = state.includedOnce ++ [ key ]; }) else
; combinator (state // { includedOnce = state.includedOnce ++ [ key ]; });
}; };
unsafe-add-raw-args = { unsafe-add-raw-args = {
@ -177,9 +176,9 @@ in rec {
Nothing is escaped, it is the caller's responsibility to ensure Nothing is escaped, it is the caller's responsibility to ensure
everything is properly escaped. everything is properly escaped.
''; '';
__functor = _: __functor =
args: state: state // { cmd = "${state.cmd} ${args}"; } _: args: state:
; state // { cmd = "${state.cmd} ${args}"; };
}; };
add-path = { add-path = {
@ -187,9 +186,9 @@ in rec {
doc = '' doc = ''
Prepends the passed string to `$PATH`. Prepends the passed string to `$PATH`.
''; '';
__functor = _: __functor =
path: state: state // { path = [ path ] ++ state.path; } _: path: state:
; state // { path = [ path ] ++ state.path; };
}; };
set-argv = { set-argv = {
@ -201,9 +200,9 @@ in rec {
arguments are provided to the wrapper script at runtime. Calling this arguments are provided to the wrapper script at runtime. Calling this
will override the current value. will override the current value.
''; '';
__functor = _: __functor =
argv: state: state // { argv = builtins.concatStringsSep " " (builtins.map escape argv); } _: argv: state:
; state // { argv = builtins.concatStringsSep " " (builtins.map escape argv); };
}; };
add-runtime = { add-runtime = {
@ -232,9 +231,9 @@ in rec {
If you create any resources in add-runtime that you want to automatically If you create any resources in add-runtime that you want to automatically
clean up when the jail exits use [add-cleanup](#add-cleanup). clean up when the jail exits use [add-cleanup](#add-cleanup).
''; '';
__functor = _: __functor =
runtime: state: state // { runtime = "${state.runtime}\n${runtime}\n"; } _: runtime: state:
; state // { runtime = "${state.runtime}\n${runtime}\n"; };
}; };
add-cleanup = { add-cleanup = {
@ -266,9 +265,9 @@ in rec {
] ]
``` ```
''; '';
__functor = _: __functor =
cleanup: state: state // { cleanup = state.cleanup ++ [ cleanup ]; } _: cleanup: state:
; state // { cleanup = state.cleanup ++ [ cleanup ]; };
}; };
fake-passwd = { fake-passwd = {
@ -284,7 +283,8 @@ in rec {
you may consider just bind mounting `/etc/passwd` and `/etc/group` inside you may consider just bind mounting `/etc/passwd` and `/etc/group` inside
the jail instead. the jail instead.
''; '';
__functor = _: __functor =
_:
compose [ compose [
(add-runtime '' (add-runtime ''
if [ ! -e ${helpers.dataDirSubPath "passwd"} ] || [ ! -e ${helpers.dataDirSubPath "group"} ]; then if [ ! -e ${helpers.dataDirSubPath "passwd"} ] || [ ! -e ${helpers.dataDirSubPath "group"} ]; then
@ -298,8 +298,7 @@ in rec {
'') '')
(ro-bind (noescape (helpers.dataDirSubPath "passwd")) "/etc/passwd") (ro-bind (noescape (helpers.dataDirSubPath "passwd")) "/etc/passwd")
(ro-bind (noescape (helpers.dataDirSubPath "group")) "/etc/group") (ro-bind (noescape (helpers.dataDirSubPath "group")) "/etc/group")
] ];
;
}; };
wrap-entry = { wrap-entry = {
@ -321,14 +320,17 @@ in rec {
${"''"}) ${"''"})
``` ```
''; '';
__functor = _: __functor =
getWrapper: state: state // { _: getWrapper: state:
entry = lib.getExe (pkgs.writeShellApplication { state
// {
entry = lib.getExe (
pkgs.writeShellApplication {
name = "${state.name}-jail-wrapper"; name = "${state.name}-jail-wrapper";
text = getWrapper state.entry; text = getWrapper state.entry;
});
} }
; );
};
}; };
add-pkg-deps = { add-pkg-deps = {
@ -336,9 +338,7 @@ in rec {
doc = '' doc = ''
Adds the packages' `bin` directory to `$PATH`. Adds the packages' `bin` directory to `$PATH`.
''; '';
__functor = _: __functor = _: pkgs: compose (builtins.map (pkg: add-path "${lib.getBin pkg}/bin") pkgs);
pkgs: compose (builtins.map (pkg: add-path "${lib.getBin pkg}/bin") pkgs)
;
}; };
no-new-session = { no-new-session = {
@ -352,9 +352,7 @@ in rec {
See BWRAP(1) for more information and security implications. See BWRAP(1) for more information and security implications.
''; '';
__functor = _: __functor = _: state: state // { newSession = false; };
state: state // { newSession = false; }
;
}; };
set-env = { set-env = {
@ -364,9 +362,14 @@ in rec {
This will throw if the variable name is not a valid posix variable name. This will throw if the variable name is not a valid posix variable name.
''; '';
__functor = _: __functor =
name: value: state: state // { env = state.env // { ${name} = escape value; }; } _: name: value: state:
; state
// {
env = state.env // {
${name} = escape value;
};
};
}; };
share-ns = { share-ns = {
@ -380,9 +383,14 @@ in rec {
See BWRAP(1) for more information. See BWRAP(1) for more information.
''; '';
__functor = _: __functor =
namespace: state: state // { namespaces = state.namespaces // { ${namespace} = true; }; } _: namespace: state:
; state
// {
namespaces = state.namespaces // {
${namespace} = true;
};
};
}; };
set-hostname = { set-hostname = {
@ -400,9 +408,9 @@ in rec {
] ]
``` ```
''; '';
__functor = _: __functor =
hostname: state: state // { inherit hostname; } _: hostname: state:
; state // { inherit hostname; };
}; };
tmpfs = { tmpfs = {
@ -410,9 +418,7 @@ in rec {
doc = '' doc = ''
Mounts a new tmpfs at the specified location. Mounts a new tmpfs at the specified location.
''; '';
__functor = _: __functor = _: path: unsafe-add-raw-args "--tmpfs ${escape path}";
path: unsafe-add-raw-args "--tmpfs ${escape path}"
;
}; };
camera = { camera = {
@ -420,15 +426,14 @@ in rec {
doc = '' doc = ''
Allows access to webcams and other V4L2 video devices at `/dev/video*`. Allows access to webcams and other V4L2 video devices at `/dev/video*`.
''; '';
__functor = _: __functor =
include-once "camera" _:
(add-runtime '' include-once "camera" (add-runtime ''
for v in /dev/video*; do for v in /dev/video*; do
[ -e "$v" ] || continue [ -e "$v" ] || continue
RUNTIME_ARGS+=(--dev-bind "$v" "$v") RUNTIME_ARGS+=(--dev-bind "$v" "$v")
done done
'') '');
;
}; };
fwd-env = { fwd-env = {
@ -442,9 +447,7 @@ in rec {
If you want to be tolerant of the environment being unset, use If you want to be tolerant of the environment being unset, use
[try-fwd-env](#try-fwd-env) instead. [try-fwd-env](#try-fwd-env) instead.
''; '';
__functor = _: __functor = _: name: set-env name (noescape "\"\$${name}\"");
name: set-env name (noescape "\"\$${name}\"")
;
}; };
try-fwd-env = { try-fwd-env = {
@ -452,9 +455,7 @@ in rec {
doc = '' doc = ''
Forwards the specified environment variable to the underlying process (if set). Forwards the specified environment variable to the underlying process (if set).
''; '';
__functor = _: __functor = _: name: set-env name (noescape "\"\${${name}-}\"");
name: set-env name (noescape "\"\${${name}-}\"")
;
}; };
runtime-deep-ro-bind = { runtime-deep-ro-bind = {
@ -468,9 +469,10 @@ in rec {
use, but a future update may break this combinator. use, but a future update may break this combinator.
''; '';
internal = true; internal = true;
__functor = _: let __functor =
bindRuntimeHelperFunction = include-once "bindRuntimeHelperFunction" ( _:
add-runtime '' let
bindRuntimeHelperFunction = include-once "bindRuntimeHelperFunction" (add-runtime ''
function bindNixStoreClosure { function bindNixStoreClosure {
local NIX_STORE_PATH local NIX_STORE_PATH
NIX_STORE_PATH="$1" NIX_STORE_PATH="$1"
@ -510,25 +512,21 @@ in rec {
;; ;;
esac esac
} }
'' '');
); in
in path: path:
compose [ compose [
bindRuntimeHelperFunction bindRuntimeHelperFunction
(add-runtime "bindRuntime 5 ${escape path}") (add-runtime "bindRuntime 5 ${escape path}")
] ];
;
}; };
readonly = { readonly = {
sig = "String -> Permission"; sig = "String -> Permission";
doc = '' doc = ''
Binds the specified path in the jail as read-only. Binds the specified path in the jail as read-only.
''; '';
__functor = _: __functor = _: path: ro-bind path path;
path: ro-bind path path
;
}; };
readwrite = { readwrite = {
@ -536,9 +534,7 @@ in rec {
doc = '' doc = ''
Binds the specified path in the jail as read-write. Binds the specified path in the jail as read-write.
''; '';
__functor = _: __functor = _: path: rw-bind path path;
path: rw-bind path path
;
}; };
ro-bind = { ro-bind = {
@ -552,9 +548,9 @@ in rec {
ro-bind "/foo" "/bar" ro-bind "/foo" "/bar"
``` ```
''; '';
__functor = _: __functor =
from: to: unsafe-add-raw-args "--ro-bind ${escape from} ${escape to}" _: from: to:
; unsafe-add-raw-args "--ro-bind ${escape from} ${escape to}";
}; };
rw-bind = { rw-bind = {
@ -568,9 +564,9 @@ in rec {
rw-bind "/foo" "/bar" rw-bind "/foo" "/bar"
``` ```
''; '';
__functor = _: __functor =
from: to: unsafe-add-raw-args "--bind ${escape from} ${escape to}" _: from: to:
; unsafe-add-raw-args "--bind ${escape from} ${escape to}";
}; };
readonly-runtime-args = { readonly-runtime-args = {
@ -579,17 +575,16 @@ in rec {
Binds any valid paths passed in as arguments to the jailed program at Binds any valid paths passed in as arguments to the jailed program at
runtime as read-only. runtime as read-only.
''; '';
__functor = _: __functor =
include-once "readonly-runtime-args" _:
(add-runtime '' include-once "readonly-runtime-args" (add-runtime ''
for MAYBE_PATH in "$@"; do for MAYBE_PATH in "$@"; do
if [ -e "$MAYBE_PATH" ]; then if [ -e "$MAYBE_PATH" ]; then
P="$(realpath "$MAYBE_PATH")" P="$(realpath "$MAYBE_PATH")"
RUNTIME_ARGS+=(--ro-bind "$P" "$P") RUNTIME_ARGS+=(--ro-bind "$P" "$P")
fi fi
done done
'') '');
;
}; };
readwrite-runtime-args = { readwrite-runtime-args = {
@ -598,17 +593,16 @@ in rec {
Binds any valid paths passed in as arguments to the jailed program at Binds any valid paths passed in as arguments to the jailed program at
runtime as read-write. runtime as read-write.
''; '';
__functor = _: __functor =
include-once "readwrite-runtime-args" _:
(add-runtime '' include-once "readwrite-runtime-args" (add-runtime ''
for MAYBE_PATH in "$@"; do for MAYBE_PATH in "$@"; do
if [ -e "$MAYBE_PATH" ]; then if [ -e "$MAYBE_PATH" ]; then
P="$(realpath "$MAYBE_PATH")" P="$(realpath "$MAYBE_PATH")"
RUNTIME_ARGS+=(--bind "$P" "$P") RUNTIME_ARGS+=(--bind "$P" "$P")
fi fi
done done
'') '');
;
}; };
readonly-paths-from-var = { readonly-paths-from-var = {
@ -632,19 +626,17 @@ in rec {
] ]
``` ```
''; '';
__functor = _: __functor =
var: separator: _: var: separator:
assert pkgs.lib.isValidPosixName var; assert pkgs.lib.isValidPosixName var;
include-once "readonly-paths-from-var-${var}" include-once "readonly-paths-from-var-${var}" (add-runtime ''
(add-runtime ''
while read -rd${lib.escapeShellArg separator} DIR; do while read -rd${lib.escapeShellArg separator} DIR; do
if [ -e "$DIR" ]; then if [ -e "$DIR" ]; then
P="$(realpath "$DIR")" P="$(realpath "$DIR")"
RUNTIME_ARGS+=(--ro-bind "$P" "$P") RUNTIME_ARGS+=(--ro-bind "$P" "$P")
fi fi
done <<< "''${${var}-}" done <<< "''${${var}-}"
'') '');
;
}; };
mount-cwd = { mount-cwd = {
@ -652,10 +644,7 @@ in rec {
doc = '' doc = ''
Bind mounts the runtime working directory as read-write. Bind mounts the runtime working directory as read-write.
''; '';
__functor = _: __functor = _: include-once "mount-cwd" (unsafe-add-raw-args "--bind \"$PWD\" \"$PWD\"");
include-once "mount-cwd"
(unsafe-add-raw-args "--bind \"$PWD\" \"$PWD\"")
;
}; };
bind-nix-store-runtime-closure = { bind-nix-store-runtime-closure = {
@ -694,8 +683,11 @@ in rec {
``` ```
rather than your entire nix store. rather than your entire nix store.
''; '';
__functor = _: __functor =
include-once "bind-nix-store-runtime-closure" (defer (state: _:
include-once "bind-nix-store-runtime-closure" (
defer (
state:
let let
runtimeClosure = pkgs.writeText "${state.name}-runtime-closure" '' runtimeClosure = pkgs.writeText "${state.name}-runtime-closure" ''
${pkgs.lib.concatStringsSep "\n" state.additionalRuntimeClosures} ${pkgs.lib.concatStringsSep "\n" state.additionalRuntimeClosures}
@ -703,7 +695,8 @@ in rec {
${state.argv} ${state.argv}
${state.entry} ${state.entry}
''; '';
bindArgs = pkgs.runCommand "${state.name}-runtime-closure-bind-args" bindArgs =
pkgs.runCommand "${state.name}-runtime-closure-bind-args"
{ {
__structuredAttrs = true; __structuredAttrs = true;
exportReferencesGraph.runtime = runtimeClosure; exportReferencesGraph.runtime = runtimeClosure;
@ -721,8 +714,8 @@ in rec {
(add-runtime "exec {RUNTIME_CLOSURE_BIND_ARGS_FD}<${bindArgs}") (add-runtime "exec {RUNTIME_CLOSURE_BIND_ARGS_FD}<${bindArgs}")
(unsafe-add-raw-args "--args \"$RUNTIME_CLOSURE_BIND_ARGS_FD\"") (unsafe-add-raw-args "--args \"$RUNTIME_CLOSURE_BIND_ARGS_FD\"")
] state ] state
)) )
; );
}; };
gui = { gui = {
@ -734,7 +727,8 @@ in rec {
[wayland](#wayland), and forwards/binds a few other paths to get fonts [wayland](#wayland), and forwards/binds a few other paths to get fonts
and cursor to render correctly. and cursor to render correctly.
''; '';
__functor = _: __functor =
_:
compose [ compose [
(add-runtime "mkdir -p ~/.config/dconf") (add-runtime "mkdir -p ~/.config/dconf")
pulse pulse
@ -751,8 +745,7 @@ in rec {
(try-fwd-env "XCURSOR_PATH") (try-fwd-env "XCURSOR_PATH")
(try-fwd-env "XCURSOR_SIZE") (try-fwd-env "XCURSOR_SIZE")
(readonly-paths-from-var "XCURSOR_PATH" " ") (readonly-paths-from-var "XCURSOR_PATH" " ")
] ];
;
}; };
wayland = { wayland = {
@ -760,14 +753,14 @@ in rec {
doc = '' doc = ''
Exposes your wayland compositor to the jail. Exposes your wayland compositor to the jail.
''; '';
__functor = _: __functor =
_:
compose [ compose [
(fwd-env "WAYLAND_DISPLAY") (fwd-env "WAYLAND_DISPLAY")
(fwd-env "XDG_RUNTIME_DIR") (fwd-env "XDG_RUNTIME_DIR")
(fwd-env "XDG_SESSION_TYPE") (fwd-env "XDG_SESSION_TYPE")
(readonly (noescape "\"$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY\"")) (readonly (noescape "\"$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY\""))
] ];
;
}; };
xwayland = { xwayland = {
@ -787,17 +780,16 @@ in rec {
run with this combinator will spin up its own personal xwayland-satelite run with this combinator will spin up its own personal xwayland-satelite
server, which will consume more resources than having a global one. server, which will consume more resources than having a global one.
''; '';
__functor = _: __functor =
include-once "xwayland" _:
(compose [ include-once "xwayland" (compose [
wayland wayland
(set-env "DISPLAY" ":42") (set-env "DISPLAY" ":42")
(wrap-entry (entry: '' (wrap-entry (entry: ''
${lib.getExe pkgs.xwayland-satellite} :42 & ${lib.getExe pkgs.xwayland-satellite} :42 &
${entry} ${entry}
'')) ''))
]) ]);
;
}; };
unsafe-x11 = { unsafe-x11 = {
@ -811,12 +803,12 @@ in rec {
For a safer alternative, consider using the [xwayland](#xwayland) For a safer alternative, consider using the [xwayland](#xwayland)
combinator inside of a wayland compositor. combinator inside of a wayland compositor.
''; '';
__functor = _: __functor =
_:
compose [ compose [
(fwd-env "DISPLAY") (fwd-env "DISPLAY")
(readwrite "/tmp/.X11-unix") (readwrite "/tmp/.X11-unix")
] ];
;
}; };
pulse = { pulse = {
@ -824,15 +816,14 @@ in rec {
doc = '' doc = ''
Exposes pulseaudio to the jailed application. Exposes pulseaudio to the jailed application.
''; '';
__functor = _: __functor =
include-once "pulse" _:
(compose [ include-once "pulse" (compose [
(fwd-env "XDG_RUNTIME_DIR") (fwd-env "XDG_RUNTIME_DIR")
(try-fwd-env "PULSE_SERVER") (try-fwd-env "PULSE_SERVER")
(unsafe-add-raw-args "--bind-try /run/pulse /run/pulse") (unsafe-add-raw-args "--bind-try /run/pulse /run/pulse")
(unsafe-add-raw-args "--bind-try \"$XDG_RUNTIME_DIR/pulse\" \"$XDG_RUNTIME_DIR/pulse\"") (unsafe-add-raw-args "--bind-try \"$XDG_RUNTIME_DIR/pulse\" \"$XDG_RUNTIME_DIR/pulse\"")
]) ]);
;
}; };
pipewire = { pipewire = {
@ -840,14 +831,13 @@ in rec {
doc = '' doc = ''
Exposes pipewire to the jailed application. Exposes pipewire to the jailed application.
''; '';
__functor = _: __functor =
include-once "pipewire" _:
(compose [ include-once "pipewire" (compose [
(fwd-env "XDG_RUNTIME_DIR") (fwd-env "XDG_RUNTIME_DIR")
(unsafe-add-raw-args "--bind-try \"$XDG_RUNTIME_DIR/pipewire-0\" \"$XDG_RUNTIME_DIR/pipewire-0\"") (unsafe-add-raw-args "--bind-try \"$XDG_RUNTIME_DIR/pipewire-0\" \"$XDG_RUNTIME_DIR/pipewire-0\"")
(unsafe-add-raw-args "--bind-try /run/pipewire /run/pipewire") (unsafe-add-raw-args "--bind-try /run/pipewire /run/pipewire")
]) ]);
;
}; };
gpu = { gpu = {
@ -855,15 +845,14 @@ in rec {
doc = '' doc = ''
Exposes the gpu to jailed application. Exposes the gpu to jailed application.
''; '';
__functor = _: __functor =
include-once "gpu" _:
(compose [ include-once "gpu" (compose [
(runtime-deep-ro-bind (noescape "/run/opengl-driver")) (runtime-deep-ro-bind (noescape "/run/opengl-driver"))
(runtime-deep-ro-bind (noescape "/run/opengl-driver-32")) (runtime-deep-ro-bind (noescape "/run/opengl-driver-32"))
(readonly (noescape "/sys")) (readonly (noescape "/sys"))
(unsafe-add-raw-args "--dev-bind /dev/dri /dev/dri") (unsafe-add-raw-args "--dev-bind /dev/dri /dev/dri")
]) ]);
;
}; };
time-zone = { time-zone = {
@ -871,10 +860,7 @@ in rec {
doc = '' doc = ''
Exposes your timezone. Exposes your timezone.
''; '';
__functor = _: __functor = _: include-once "time-zone" (runtime-deep-ro-bind "/etc/localtime");
include-once "time-zone"
(runtime-deep-ro-bind "/etc/localtime")
;
}; };
network = { network = {
@ -887,9 +873,11 @@ in rec {
You can set your desired hostname with [set-hostname](#set-hostname). The You can set your desired hostname with [set-hostname](#set-hostname). The
default is `jail`. default is `jail`.
''; '';
__functor = _: __functor =
include-once "network" _:
(state: compose [ include-once "network" (
state:
compose [
time-zone time-zone
(share-ns "net") (share-ns "net")
(runtime-deep-ro-bind "/etc/hosts") (runtime-deep-ro-bind "/etc/hosts")
@ -898,8 +886,8 @@ in rec {
(runtime-deep-ro-bind "/etc/ssl") (runtime-deep-ro-bind "/etc/ssl")
(write-text "/etc/hostname" "${state.hostname}\n") (write-text "/etc/hostname" "${state.hostname}\n")
(unsafe-add-raw-args "--hostname ${escape state.hostname}") (unsafe-add-raw-args "--hostname ${escape state.hostname}")
] state) ] state
; );
}; };
dbus = { dbus = {
@ -926,15 +914,23 @@ in rec {
} }
``` ```
''; '';
__functor = _: __functor =
{ own ? [], talk ? [], see ? [], call ? [], broadcast ? [] }: _:
{
own ? [ ],
talk ? [ ],
see ? [ ],
call ? [ ],
broadcast ? [ ],
}:
let let
proxy = jail "xdg-dbus-proxy" pkgs.xdg-dbus-proxy [ proxy = jail "xdg-dbus-proxy" pkgs.xdg-dbus-proxy [
unsafe-dbus unsafe-dbus
(readwrite (noescape "\"$PROXIED_DBUS_SOCKET_DIR\"")) (readwrite (noescape "\"$PROXIED_DBUS_SOCKET_DIR\""))
]; ];
args = [ "--filter" ] args =
[ "--filter" ]
++ map (id: "--own=${lib.escapeShellArg id}") own ++ map (id: "--own=${lib.escapeShellArg id}") own
++ map (id: "--talk=${lib.escapeShellArg id}") talk ++ map (id: "--talk=${lib.escapeShellArg id}") talk
++ map (id: "--see=${lib.escapeShellArg id}") see ++ map (id: "--see=${lib.escapeShellArg id}") see
@ -965,8 +961,7 @@ in rec {
'') '')
(readwrite (noescape "\"$PROXIED_DBUS_SOCKET_DIR\"")) (readwrite (noescape "\"$PROXIED_DBUS_SOCKET_DIR\""))
(set-env "DBUS_SESSION_BUS_ADDRESS" (noescape "\"unix:path=$PROXIED_DBUS_SOCKET\"")) (set-env "DBUS_SESSION_BUS_ADDRESS" (noescape "\"unix:path=$PROXIED_DBUS_SOCKET\""))
] ];
;
}; };
unsafe-dbus = { unsafe-dbus = {
@ -978,12 +973,12 @@ in rec {
more control over the messages that can be sent/received, consider using more control over the messages that can be sent/received, consider using
the [dbus](#dbus) combinator instead. the [dbus](#dbus) combinator instead.
''; '';
__functor = _: __functor =
_:
compose [ compose [
(readonly (noescape "\"$XDG_RUNTIME_DIR/bus\"")) (readonly (noescape "\"$XDG_RUNTIME_DIR/bus\""))
(set-env "DBUS_SESSION_BUS_ADDRESS" (noescape "\"$DBUS_SESSION_BUS_ADDRESS\"")) (set-env "DBUS_SESSION_BUS_ADDRESS" (noescape "\"$DBUS_SESSION_BUS_ADDRESS\""))
] ];
;
}; };
bind-pkg = { bind-pkg = {
@ -996,12 +991,12 @@ in rec {
bind-pkg "/foo" (pkgs.writeText "foo" "bar") bind-pkg "/foo" (pkgs.writeText "foo" "bar")
``` ```
''; '';
__functor = _: __functor =
path: pkg: compose [ _: path: pkg:
compose [
(ro-bind (toString pkg) path) (ro-bind (toString pkg) path)
(state: state // { additionalRuntimeClosures = state.additionalRuntimeClosures ++ [ pkg ]; }) (state: state // { additionalRuntimeClosures = state.additionalRuntimeClosures ++ [ pkg ]; })
] ];
;
}; };
write-text = { write-text = {
@ -1015,12 +1010,11 @@ in rec {
write-text "/hello.txt" "Hello, world!" write-text "/hello.txt" "Hello, world!"
``` ```
''; '';
__functor = _: __functor =
path: contents: _: path: contents:
bind-pkg bind-pkg path (
path pkgs.writeText "jail-write-text-${lib.strings.sanitizeDerivationName (escape path)}" contents
(pkgs.writeText "jail-write-text-${lib.strings.sanitizeDerivationName (escape path)}" contents) );
;
}; };
persist-home = { persist-home = {
@ -1034,12 +1028,12 @@ in rec {
The home directory is persisted in `~/.local/share/jail.nix/home/<name>`. The home directory is persisted in `~/.local/share/jail.nix/home/<name>`.
''; '';
__functor = _: __functor =
name: compose [ _: name:
compose [
(add-runtime "mkdir -p ${helpers.dataDirSubPath "home/${name}"}") (add-runtime "mkdir -p ${helpers.dataDirSubPath "home/${name}"}")
(rw-bind (noescape (helpers.dataDirSubPath "home/${name}")) (noescape "~")) (rw-bind (noescape (helpers.dataDirSubPath "home/${name}")) (noescape "~"))
] ];
;
}; };
jail-to-host-channel = { jail-to-host-channel = {
@ -1079,12 +1073,13 @@ in rec {
that returns the size of the file passed in without needing to that returns the size of the file passed in without needing to
give the jail read access to any files. give the jail read access to any files.
''; '';
__functor = _: __functor =
jailTxName: hostRxHandler: _: jailTxName: hostRxHandler:
assert pkgs.lib.isValidPosixName jailTxName; assert pkgs.lib.isValidPosixName jailTxName;
let varPrefix = "J2H_CHAN_${pkgs.lib.toUpper jailTxName}"; in let
include-once "jail-to-host-channel-${jailTxName}" varPrefix = "J2H_CHAN_${pkgs.lib.toUpper jailTxName}";
(compose [ in
include-once "jail-to-host-channel-${jailTxName}" (compose [
(add-runtime '' (add-runtime ''
# Set up jail-to-host channel "${jailTxName}" # Set up jail-to-host channel "${jailTxName}"
${varPrefix}_TMP=$(mktemp -d) ${varPrefix}_TMP=$(mktemp -d)
@ -1092,10 +1087,14 @@ in rec {
( (
while true; do while true; do
MSG=$(<"''$${varPrefix}_TMP/fifo") MSG=$(<"''$${varPrefix}_TMP/fifo")
${pkgs.lib.getExe (pkgs.writeShellApplication { ${
pkgs.lib.getExe (
pkgs.writeShellApplication {
name = "${jailTxName}-host-rx-handler"; name = "${jailTxName}-host-rx-handler";
text = hostRxHandler; text = hostRxHandler;
})} "$MSG" > "''$${varPrefix}_TMP/fifo" || break }
)
} "$MSG" > "''$${varPrefix}_TMP/fifo" || break
done done
) & ) &
${varPrefix}_RX_PID=$! ${varPrefix}_RX_PID=$!
@ -1105,21 +1104,26 @@ in rec {
rm -rf "''$${varPrefix}_TMP" rm -rf "''$${varPrefix}_TMP"
'') '')
(ro-bind (noescape "\"\$${varPrefix}_TMP/fifo\"") "/run/j2hc-${jailTxName}") (ro-bind (noescape "\"\$${varPrefix}_TMP/fifo\"") "/run/j2hc-${jailTxName}")
(add-pkg-deps [(pkgs.writeShellApplication { (add-pkg-deps [
(pkgs.writeShellApplication {
name = jailTxName; name = jailTxName;
runtimeInputs = [ pkgs.util-linux ]; runtimeInputs = [ pkgs.util-linux ];
text = '' text = ''
flock /run/j2hc.lock ${pkgs.lib.getExe (pkgs.writeShellApplication { flock /run/j2hc.lock ${
pkgs.lib.getExe (
pkgs.writeShellApplication {
name = "${jailTxName}-locked"; name = "${jailTxName}-locked";
text = '' text = ''
echo "$1" > /run/j2hc-${jailTxName} echo "$1" > /run/j2hc-${jailTxName}
echo "$(< /run/j2hc-${jailTxName})" echo "$(< /run/j2hc-${jailTxName})"
''; '';
})} "$1" }
)
} "$1"
''; '';
})]) })
]) ])
; ]);
}; };
open-urls-in-browser = { open-urls-in-browser = {
@ -1132,12 +1136,12 @@ in rec {
program can launch your browser, even if it has a subset of the program can launch your browser, even if it has a subset of the
permissions your browser has. permissions your browser has.
''; '';
__functor = _: __functor =
_:
compose [ compose [
(jail-to-host-channel "browserchannel" ''"$BROWSER" "$1"'') (jail-to-host-channel "browserchannel" ''"$BROWSER" "$1"'')
(set-env "BROWSER" "browserchannel") (set-env "BROWSER" "browserchannel")
] ];
;
}; };
############################################ ############################################
@ -1146,22 +1150,20 @@ in rec {
deprecated = true; deprecated = true;
sig = "Permission"; sig = "Permission";
doc = "This was reworked to store data under `~/.local/share/jail.nix` and renamed to [persist-home](#persist-home)."; doc = "This was reworked to store data under `~/.local/share/jail.nix` and renamed to [persist-home](#persist-home).";
__functor = _: __functor =
name: _: name:
lib.warn "persisthome is deprecated, use persist-home instead. When doing so, rename ~/.local/share/jails/${name} to ${helpers.dataDirSubPath "home/${name}"}" lib.warn
"persisthome is deprecated, use persist-home instead. When doing so, rename ~/.local/share/jails/${name} to ${helpers.dataDirSubPath "home/${name}"}"
(compose [ (compose [
(add-runtime "mkdir -p ~/.local/share/jails/${lib.escapeShellArg name}") (add-runtime "mkdir -p ~/.local/share/jails/${lib.escapeShellArg name}")
(rw-bind (noescape "~/.local/share/jails/${lib.escapeShellArg name}") (noescape "~")) (rw-bind (noescape "~/.local/share/jails/${lib.escapeShellArg name}") (noescape "~"))
]) ]);
;
}; };
dbus-unsafe = { dbus-unsafe = {
deprecated = true; deprecated = true;
sig = "Permission"; sig = "Permission";
doc = "This was renamed to [unsafe-dbus](#unsafe-dbus)."; doc = "This was renamed to [unsafe-dbus](#unsafe-dbus).";
__functor = _: __functor = _: lib.warn "dbus-unsafe is deprecated, use unsafe-dbus instead" unsafe-dbus;
lib.warn "dbus-unsafe is deprecated, use unsafe-dbus instead"
unsafe-dbus;
}; };
} }

View file

@ -1,27 +1,34 @@
let let
jailNix = import ./jail.nix; jailNix = import ./jail.nix;
in { in
{
init = pkgs: jailNix { inherit pkgs; }; init = pkgs: jailNix { inherit pkgs; };
extend = jailNix; extend = jailNix;
mkOverlay = opts@{ mkOverlay =
opts@{
final, final,
prev, prev,
packages ? _: { }, packages ? _: { },
... ...
}: let }:
let
fwdOptsKey = key: if opts ? ${key} then { ${key} = opts.${key}; } else { }; fwdOptsKey = key: if opts ? ${key} then { ${key} = opts.${key}; } else { };
jail = jailNix ( jail = jailNix (
{ pkgs = prev; } {
pkgs = prev;
}
// fwdOptsKey "additionalCombinators" // fwdOptsKey "additionalCombinators"
// fwdOptsKey "basePermissions" // fwdOptsKey "basePermissions"
// fwdOptsKey "bubblewrapPackage" // fwdOptsKey "bubblewrapPackage"
); );
wrap = prev.lib.mapAttrs (name: opts: wrap = prev.lib.mapAttrs (
name: opts:
let let
unjailed = prev.${name}; unjailed = prev.${name};
jailed = jail name unjailed opts; jailed = jail name unjailed opts;
in jailed // { inherit jailed unjailed; } in
jailed // { inherit jailed unjailed; }
); );
in in
wrap (packages jail.combinators); wrap (packages jail.combinators);

View file

@ -5,8 +5,10 @@ pkgs: rec {
noescape = value: { _noescape = value; }; noescape = value: { _noescape = value; };
escape = rawOrStr: escape =
if builtins.typeOf rawOrStr == "set" && rawOrStr ? _noescape rawOrStr:
then rawOrStr._noescape if builtins.typeOf rawOrStr == "set" && rawOrStr ? _noescape then
else pkgs.lib.strings.escapeShellArg rawOrStr; rawOrStr._noescape
else
pkgs.lib.strings.escapeShellArg rawOrStr;
} }

View file

@ -1,22 +1,33 @@
{ pkgs {
, additionalCombinators ? _: {} pkgs,
, basePermissions ? import ./base-permissions.nix pkgs additionalCombinators ? _: { },
, bubblewrapPackage ? pkgs.bubblewrap basePermissions ? import ./base-permissions.nix pkgs,
}: let bubblewrapPackage ? pkgs.bubblewrap,
}:
let
inherit (pkgs) lib; inherit (pkgs) lib;
builtinCombinators = import ./combinators.nix pkgs jail; builtinCombinators = import ./combinators.nix pkgs jail;
allCombinators = builtinCombinators // additionalCombinators builtinCombinators; allCombinators = builtinCombinators // additionalCombinators builtinCombinators;
normalizePermissionsToList = combinators: normalizePermissionsToList =
let t = builtins.typeOf combinators; in combinators:
if t == "lambda" then combinators allCombinators else let
if t == "list" then combinators else t = builtins.typeOf combinators;
if t == "null" then [] in
else throw "Unknown combinator type ${t}. Must be a function, list, or null"; if t == "lambda" then
combinators allCombinators
else if t == "list" then
combinators
else if t == "null" then
[ ]
else
throw "Unknown combinator type ${t}. Must be a function, list, or null";
jail = name: exe: permissions: let jail =
name: exe: permissions:
let
initialState = { initialState = {
name = name; name = name;
cmd = lib.getExe bubblewrapPackage; cmd = lib.getExe bubblewrapPackage;
@ -33,7 +44,8 @@
deferredPermissions = [ ]; # See defer combinator deferredPermissions = [ ]; # See defer combinator
additionalRuntimeClosures = [ ]; # See bind-nix-store-runtime-closure additionalRuntimeClosures = [ ]; # See bind-nix-store-runtime-closure
}; };
in lib.pipe initialState ( in
lib.pipe initialState (
# Permissions shared by all invocations of jail # Permissions shared by all invocations of jail
(normalizePermissionsToList basePermissions) (normalizePermissionsToList basePermissions)
@ -45,35 +57,50 @@
# Finalize everything remaining in state into bwrap args # Finalize everything remaining in state into bwrap args
++ (with builtinCombinators; [ ++ (with builtinCombinators; [
(s: (
s:
# See `--unshare-*` in BWRAP(1) # See `--unshare-*` in BWRAP(1)
lib.pipe ["user" "ipc" "pid" "net" "uts" "cgroup"] [ lib.pipe
[ "user" "ipc" "pid" "net" "uts" "cgroup" ]
[
(lib.filter (ns: !(s.namespaces.${ns} or false))) (lib.filter (ns: !(s.namespaces.${ns} or false)))
(map (ns: "--unshare-${ns}")) (map (ns: "--unshare-${ns}"))
(builtins.concatStringsSep " ") (builtins.concatStringsSep " ")
unsafe-add-raw-args unsafe-add-raw-args
] s ]
s
) )
(s: if builtins.length s.path > 0 then set-env "PATH" (lib.concatStringsSep ":" s.path) s else s) (s: if builtins.length s.path > 0 then set-env "PATH" (lib.concatStringsSep ":" s.path) s else s)
(s: if s.newSession then unsafe-add-raw-args "--new-session" s else s) (s: if s.newSession then unsafe-add-raw-args "--new-session" s else s)
(s: lib.foldr (envVar: (
s:
lib.foldr (
envVar:
assert pkgs.lib.isValidPosixName envVar; assert pkgs.lib.isValidPosixName envVar;
unsafe-add-raw-args "--setenv ${envVar} ${s.env.${envVar}}" unsafe-add-raw-args "--setenv ${envVar} ${s.env.${envVar}}"
) s (builtins.attrNames s.env)) ) s (builtins.attrNames s.env)
)
]) ])
# Build jailed app from state # Build jailed app from state
++ [ ++ [
(state: '' (state: ''
RUNTIME_ARGS=() RUNTIME_ARGS=()
${if builtins.length state.cleanup > 0 then '' ${
if builtins.length state.cleanup > 0 then
''
function cleanup { function cleanup {
${lib.concatStringsSep "\n" state.cleanup} ${lib.concatStringsSep "\n" state.cleanup}
} }
trap cleanup EXIT trap cleanup EXIT
'' else ""} ''
else
""
}
${state.runtime} ${state.runtime}
${if builtins.length state.cleanup > 0 then "" else "exec "}${state.cmd} "''${RUNTIME_ARGS[@]}" -- ${state.entry} ${state.argv} ${
if builtins.length state.cleanup > 0 then "" else "exec "
}${state.cmd} "''${RUNTIME_ARGS[@]}" -- ${state.entry} ${state.argv}
'') '')
(text: pkgs.writeShellApplication { inherit name text; }) (text: pkgs.writeShellApplication { inherit name text; })
@ -82,7 +109,8 @@
] ]
); );
in { in
{
combinators = allCombinators; combinators = allCombinators;
__functor = _: jail; __functor = _: jail;
} }

View file

@ -2,7 +2,9 @@
# This is a separate flake file from the one at the root because we don't # This is a separate flake file from the one at the root because we don't
# want to depend on nixpkgs # want to depend on nixpkgs
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05"; inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05";
outputs = { nixpkgs, ... }: let outputs =
{ nixpkgs, ... }:
let
pkgs = import nixpkgs { system = "x86_64-linux"; }; pkgs = import nixpkgs { system = "x86_64-linux"; };
lib = pkgs.lib; lib = pkgs.lib;
haskellPackages = pkgs.haskellPackages.callCabal2nix "jail-nix-tests" ./. { }; haskellPackages = pkgs.haskellPackages.callCabal2nix "jail-nix-tests" ./. { };
@ -10,24 +12,35 @@
(pkgs.haskellPackages.ghc.withPackages (p: haskellPackages.buildInputs)) (pkgs.haskellPackages.ghc.withPackages (p: haskellPackages.buildInputs))
pkgs.cabal-install pkgs.cabal-install
]; ];
in { mkApp = name: runtimeInputs: script: {
apps.x86_64-linux.runChecks = {
type = "app"; type = "app";
program = lib.getExe (pkgs.writeShellApplication { program = lib.getExe (
name = "run-all-jail-nix-tests"; pkgs.writeShellApplication {
runtimeInputs = testDependencies; inherit name runtimeInputs;
text = '' text = script;
${lib.pipe { }
);
};
in
{
apps.x86_64-linux.runTests = mkApp "run-all-jail-nix-tests" testDependencies ''
${
lib.pipe
{
jail-nix = ../.; jail-nix = ../.;
nixpkgs = nixpkgs; nixpkgs = nixpkgs;
} [ }
[
(lib.mapAttrsToList (name: path: "${name}=${path}")) (lib.mapAttrsToList (name: path: "${name}=${path}"))
(lib.concatStringsSep " ") (lib.concatStringsSep " ")
(lib.toShellVar "NIX_PATH") (lib.toShellVar "NIX_PATH")
]} cabal test ]
} cabal test
''; '';
});
}; apps.x86_64-linux.checkFmt = mkApp "check-fmt" [ pkgs.nixfmt-tree ] "treefmt --ci";
apps.x86_64-linux.fmt = mkApp "fmt" [ pkgs.nixfmt-tree ] "treefmt";
devShells.x86_64-linux.default = pkgs.mkShell { devShells.x86_64-linux.default = pkgs.mkShell {
buildInputs = testDependencies ++ [ buildInputs = testDependencies ++ [

View file

@ -3,7 +3,9 @@
# want to depend on nixpkgs # want to depend on nixpkgs
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05"; inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05";
outputs = { self, nixpkgs, ... }: let outputs =
{ self, nixpkgs, ... }:
let
pkgs = import nixpkgs { system = "x86_64-linux"; }; pkgs = import nixpkgs { system = "x86_64-linux"; };
lib = pkgs.lib; lib = pkgs.lib;
@ -17,10 +19,13 @@
}; };
}; };
formatCombinatorDoc = name: combinatorObj: let formatCombinatorDoc =
name: combinatorObj:
let
attrPos = builtins.unsafeGetAttrPos "__functor" combinatorObj; attrPos = builtins.unsafeGetAttrPos "__functor" combinatorObj;
file = lib.removePrefix (toString ./..) attrPos.file; file = lib.removePrefix (toString ./..) attrPos.file;
in '' in
''
### ${name} ### ${name}
**${name} :: ${combinatorObj.sig}** **${name} :: ${combinatorObj.sig}**
@ -29,13 +34,14 @@
${combinatorObj.doc} ${combinatorObj.doc}
''; '';
combinatorDocs = let combinatorDocs =
allCombinators = import ../lib/combinators.nix let
(throw "Docs must not depend on args") allCombinators = import ../lib/combinators.nix (throw "Docs must not depend on args") (
(throw "Docs must not depend on args") throw "Docs must not depend on args"
; );
formatSection = filter: formatSection =
filter:
lib.pipe allCombinators [ lib.pipe allCombinators [
(lib.filterAttrs (_: filter)) (lib.filterAttrs (_: filter))
(lib.mapAttrsToList formatCombinatorDoc) (lib.mapAttrsToList formatCombinatorDoc)
@ -45,7 +51,8 @@
hr = ''<hr style="border: 2px solid #272525">''; hr = ''<hr style="border: 2px solid #272525">'';
is = flag: combinator: combinator ? ${flag} && combinator.${flag}; is = flag: combinator: combinator ? ${flag} && combinator.${flag};
in '' in
''
# Combinators # Combinators
jail.nix combinators are the building blocks to create `Permission`s, jail.nix combinators are the building blocks to create `Permission`s,
@ -105,7 +112,8 @@
'' ''
]; ];
}; };
in { in
{
packages.x86_64-linux.default = pkgs.runCommand "website" { buildInputs = [ pkgs.mkdocs ]; } '' packages.x86_64-linux.default = pkgs.runCommand "website" { buildInputs = [ pkgs.mkdocs ]; } ''
cp -r ${./static-docs} docs cp -r ${./static-docs} docs
chmod -R +w docs chmod -R +w docs