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,12 +186,12 @@ 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 = {
sig = "[String] -> Permission"; sig = "[String] -> Permission";
doc = '' doc = ''
Overrides the current argv that is passed to the jailed executable. Overrides the current argv that is passed to the jailed executable.
@ -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 = {
@ -277,14 +276,15 @@ in rec {
doc = '' doc = ''
Generates and mounts fake `/etc/passwd` and `/etc/group` files in the jail. Generates and mounts fake `/etc/passwd` and `/etc/group` files in the jail.
The fake `/etc/passwd` and `/etc/group` files contains a root user, and The fake `/etc/passwd` and `/etc/group` files contains a root user, and
forward the calling user's user id, username, group id and group name. forward the calling user's user id, username, group id and group name.
If you do not want to hide the users and groups that exist on your system, If you do not want to hide the users and groups that exist on your system,
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
name = "${state.name}-jail-wrapper"; // {
text = getWrapper state.entry; entry = lib.getExe (
}); pkgs.writeShellApplication {
} name = "${state.name}-jail-wrapper";
; 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,22 +593,21 @@ 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 = {
sig = "String -> String -> Permission"; sig = "String -> String -> Permission";
doc = '' doc = ''
This binds multiple paths as read-only specified by a single runtime This binds multiple paths as read-only specified by a single runtime
environment variable. environment variable.
@ -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,35 +683,39 @@ 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: _:
let include-once "bind-nix-store-runtime-closure" (
runtimeClosure = pkgs.writeText "${state.name}-runtime-closure" '' defer (
${pkgs.lib.concatStringsSep "\n" state.additionalRuntimeClosures} state:
${pkgs.lib.concatStringsSep "\n" state.path} let
${state.argv} runtimeClosure = pkgs.writeText "${state.name}-runtime-closure" ''
${state.entry} ${pkgs.lib.concatStringsSep "\n" state.additionalRuntimeClosures}
''; ${pkgs.lib.concatStringsSep "\n" state.path}
bindArgs = pkgs.runCommand "${state.name}-runtime-closure-bind-args" ${state.argv}
{ ${state.entry}
__structuredAttrs = true;
exportReferencesGraph.runtime = runtimeClosure;
nativeBuildInputs = [ pkgs.jq ];
}
''
while read -r DEP; do
printf '%s\0' --ro-bind "$DEP" "$DEP" >> $out
done <<< "$(jq -r '.runtime | map(.path) | sort | .[]' "$NIX_ATTRS_JSON_FILE")"
''; '';
in bindArgs =
pkgs.runCommand "${state.name}-runtime-closure-bind-args"
{
__structuredAttrs = true;
exportReferencesGraph.runtime = runtimeClosure;
nativeBuildInputs = [ pkgs.jq ];
}
''
while read -r DEP; do
printf '%s\0' --ro-bind "$DEP" "$DEP" >> $out
done <<< "$(jq -r '.runtime | map(.path) | sort | .[]' "$NIX_ATTRS_JSON_FILE")"
'';
in
compose [ compose [
# Use `--args` and a file descriptor here in case the runtime # Use `--args` and a file descriptor here in case the runtime
# closure is huge, to avoid running into argv size limitations # closure is huge, to avoid running into argv size limitations
(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,19 +873,21 @@ 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" (
time-zone state:
(share-ns "net") compose [
(runtime-deep-ro-bind "/etc/hosts") time-zone
(runtime-deep-ro-bind "/etc/nsswitch.conf") (share-ns "net")
(runtime-deep-ro-bind "/etc/resolv.conf") (runtime-deep-ro-bind "/etc/hosts")
(runtime-deep-ro-bind "/etc/ssl") (runtime-deep-ro-bind "/etc/nsswitch.conf")
(write-text "/etc/hostname" "${state.hostname}\n") (runtime-deep-ro-bind "/etc/resolv.conf")
(unsafe-add-raw-args "--hostname ${escape state.hostname}") (runtime-deep-ro-bind "/etc/ssl")
] state) (write-text "/etc/hostname" "${state.hostname}\n")
; (unsafe-add-raw-args "--hostname ${escape state.hostname}")
] state
);
}; };
dbus = { dbus = {
@ -926,47 +914,54 @@ in rec {
} }
``` ```
''; '';
__functor = _: __functor =
{ own ? [], talk ? [], see ? [], call ? [], broadcast ? [] }: _:
let {
proxy = jail "xdg-dbus-proxy" pkgs.xdg-dbus-proxy [ own ? [ ],
unsafe-dbus talk ? [ ],
(readwrite (noescape "\"$PROXIED_DBUS_SOCKET_DIR\"")) see ? [ ],
]; call ? [ ],
broadcast ? [ ],
}:
let
proxy = jail "xdg-dbus-proxy" pkgs.xdg-dbus-proxy [
unsafe-dbus
(readwrite (noescape "\"$PROXIED_DBUS_SOCKET_DIR\""))
];
args = [ "--filter" ] args =
++ map (id: "--own=${lib.escapeShellArg id}") own [ "--filter" ]
++ map (id: "--talk=${lib.escapeShellArg id}") talk ++ map (id: "--own=${lib.escapeShellArg id}") own
++ map (id: "--see=${lib.escapeShellArg id}") see ++ map (id: "--talk=${lib.escapeShellArg id}") talk
++ map (id: "--call=${lib.escapeShellArg id}") call ++ map (id: "--see=${lib.escapeShellArg id}") see
++ map (id: "--broadcast=${lib.escapeShellArg id}") broadcast; ++ map (id: "--call=${lib.escapeShellArg id}") call
in ++ map (id: "--broadcast=${lib.escapeShellArg id}") broadcast;
compose [ in
(add-runtime '' compose [
PROXIED_DBUS_SOCKET_DIR=$(mktemp -d) (add-runtime ''
export PROXIED_DBUS_SOCKET_DIR PROXIED_DBUS_SOCKET_DIR=$(mktemp -d)
PROXIED_DBUS_SOCKET="$PROXIED_DBUS_SOCKET_DIR/socket" export PROXIED_DBUS_SOCKET_DIR
mkfifo "$PROXIED_DBUS_SOCKET_DIR/ready" PROXIED_DBUS_SOCKET="$PROXIED_DBUS_SOCKET_DIR/socket"
exec {XDG_DBUS_PROXY_READY_FD}<>"$PROXIED_DBUS_SOCKET_DIR/ready" mkfifo "$PROXIED_DBUS_SOCKET_DIR/ready"
${lib.getExe proxy} \ exec {XDG_DBUS_PROXY_READY_FD}<>"$PROXIED_DBUS_SOCKET_DIR/ready"
"$DBUS_SESSION_BUS_ADDRESS" \ ${lib.getExe proxy} \
"$PROXIED_DBUS_SOCKET" \ "$DBUS_SESSION_BUS_ADDRESS" \
--fd="$XDG_DBUS_PROXY_READY_FD" \ "$PROXIED_DBUS_SOCKET" \
${lib.concatStringsSep " " args} \ --fd="$XDG_DBUS_PROXY_READY_FD" \
& ${lib.concatStringsSep " " args} \
PROXY_PID=$! &
IFS= read -rn1 -u "$XDG_DBUS_PROXY_READY_FD" PROXY_PID=$!
'') IFS= read -rn1 -u "$XDG_DBUS_PROXY_READY_FD"
(add-cleanup '' '')
kill "$PROXY_PID" (add-cleanup ''
if [ -e "''${PROXIED_DBUS_SOCKET_DIR-}" ]; then kill "$PROXY_PID"
rm -rf "$PROXIED_DBUS_SOCKET_DIR" if [ -e "''${PROXIED_DBUS_SOCKET_DIR-}" ]; then
fi rm -rf "$PROXIED_DBUS_SOCKET_DIR"
'') fi
(readwrite (noescape "\"$PROXIED_DBUS_SOCKET_DIR\"")) '')
(set-env "DBUS_SESSION_BUS_ADDRESS" (noescape "\"unix:path=$PROXIED_DBUS_SOCKET\"")) (readwrite (noescape "\"$PROXIED_DBUS_SOCKET_DIR\""))
] (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,47 +1073,57 @@ 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
(add-runtime '' include-once "jail-to-host-channel-${jailTxName}" (compose [
# Set up jail-to-host channel "${jailTxName}" (add-runtime ''
${varPrefix}_TMP=$(mktemp -d) # Set up jail-to-host channel "${jailTxName}"
mkfifo "''$${varPrefix}_TMP/fifo" ${varPrefix}_TMP=$(mktemp -d)
( mkfifo "''$${varPrefix}_TMP/fifo"
while true; do (
MSG=$(<"''$${varPrefix}_TMP/fifo") while true; do
${pkgs.lib.getExe (pkgs.writeShellApplication { MSG=$(<"''$${varPrefix}_TMP/fifo")
name = "${jailTxName}-host-rx-handler"; ${
text = hostRxHandler; pkgs.lib.getExe (
})} "$MSG" > "''$${varPrefix}_TMP/fifo" || break pkgs.writeShellApplication {
done name = "${jailTxName}-host-rx-handler";
) & text = hostRxHandler;
${varPrefix}_RX_PID=$! }
'') )
(add-cleanup '' } "$MSG" > "''$${varPrefix}_TMP/fifo" || break
kill "''$${varPrefix}_RX_PID" done
rm -rf "''$${varPrefix}_TMP" ) &
'') ${varPrefix}_RX_PID=$!
(ro-bind (noescape "\"\$${varPrefix}_TMP/fifo\"") "/run/j2hc-${jailTxName}") '')
(add-pkg-deps [(pkgs.writeShellApplication { (add-cleanup ''
kill "''$${varPrefix}_RX_PID"
rm -rf "''$${varPrefix}_TMP"
'')
(ro-bind (noescape "\"\$${varPrefix}_TMP/fifo\"") "/run/j2hc-${jailTxName}")
(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 ${
name = "${jailTxName}-locked"; pkgs.lib.getExe (
text = '' pkgs.writeShellApplication {
echo "$1" > /run/j2hc-${jailTxName} name = "${jailTxName}-locked";
echo "$(< /run/j2hc-${jailTxName})" text = ''
''; echo "$1" > /run/j2hc-${jailTxName}
})} "$1" echo "$(< /run/j2hc-${jailTxName})"
'';
}
)
} "$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,28 +1,35 @@
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 =
final, opts@{
prev, final,
packages ? _: {}, prev,
... packages ? _: { },
}: let ...
fwdOptsKey = key: if opts ? ${key} then { ${key} = opts.${key}; } else {}; }:
jail = jailNix ( let
{ pkgs = prev; } fwdOptsKey = key: if opts ? ${key} then { ${key} = opts.${key}; } else { };
// fwdOptsKey "additionalCombinators" jail = jailNix (
// fwdOptsKey "basePermissions" {
// fwdOptsKey "bubblewrapPackage" pkgs = prev;
); }
wrap = prev.lib.mapAttrs (name: opts: // fwdOptsKey "additionalCombinators"
let // fwdOptsKey "basePermissions"
unjailed = prev.${name}; // fwdOptsKey "bubblewrapPackage"
jailed = jail name unjailed opts; );
in jailed // { inherit jailed unjailed; } wrap = prev.lib.mapAttrs (
); name: opts:
in let
unjailed = prev.${name};
jailed = jail name unjailed opts;
in
jailed // { inherit jailed unjailed; }
);
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,88 +1,116 @@
{ 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 =
initialState = { name: exe: permissions:
name = name; let
cmd = lib.getExe bubblewrapPackage; initialState = {
entry = if builtins.typeOf exe == "string" then lib.escapeShellArg exe else lib.getExe exe; name = name;
path = []; cmd = lib.getExe bubblewrapPackage;
argv = "\"$@\""; entry = if builtins.typeOf exe == "string" then lib.escapeShellArg exe else lib.getExe exe;
runtime = ""; path = [ ];
newSession = true; argv = "\"$@\"";
hostname = "jail"; runtime = "";
env = {}; newSession = true;
namespaces = {}; hostname = "jail";
includedOnce = []; # See include-once combinator env = { };
cleanup = []; # See cleanup combinator namespaces = { };
deferredPermissions = []; # See defer combinator includedOnce = [ ]; # See include-once combinator
additionalRuntimeClosures = []; # See bind-nix-store-runtime-closure cleanup = [ ]; # See cleanup combinator
}; deferredPermissions = [ ]; # See defer combinator
in lib.pipe initialState ( additionalRuntimeClosures = [ ]; # See bind-nix-store-runtime-closure
# Permissions shared by all invocations of jail };
(normalizePermissionsToList basePermissions) in
lib.pipe initialState (
# Permissions shared by all invocations of jail
(normalizePermissionsToList basePermissions)
# Permissions for this specific jail # Permissions for this specific jail
++ (normalizePermissionsToList permissions) ++ (normalizePermissionsToList permissions)
# Permissions wrapped in `defer` combinator # Permissions wrapped in `defer` combinator
++ [(s: builtinCombinators.compose s.deferredPermissions s)] ++ [ (s: builtinCombinators.compose s.deferredPermissions s) ]
# Finalize everything remaining in state into bwrap args # Finalize everything remaining in state into bwrap args
++ (with builtinCombinators; [ ++ (with builtinCombinators; [
(s: (
# See `--unshare-*` in BWRAP(1) s:
lib.pipe ["user" "ipc" "pid" "net" "uts" "cgroup"] [ # See `--unshare-*` in BWRAP(1)
(lib.filter (ns: !(s.namespaces.${ns} or false))) lib.pipe
(map (ns: "--unshare-${ns}")) [ "user" "ipc" "pid" "net" "uts" "cgroup" ]
(builtins.concatStringsSep " ") [
unsafe-add-raw-args (lib.filter (ns: !(s.namespaces.${ns} or false)))
] s (map (ns: "--unshare-${ns}"))
) (builtins.concatStringsSep " ")
(s: if builtins.length s.path > 0 then set-env "PATH" (lib.concatStringsSep ":" s.path) s else s) unsafe-add-raw-args
(s: if s.newSession then unsafe-add-raw-args "--new-session" s else s) ]
(s: lib.foldr (envVar: s
assert pkgs.lib.isValidPosixName envVar; )
unsafe-add-raw-args "--setenv ${envVar} ${s.env.${envVar}}" (s: if builtins.length s.path > 0 then set-env "PATH" (lib.concatStringsSep ":" s.path) s else s)
) s (builtins.attrNames s.env)) (s: if s.newSession then unsafe-add-raw-args "--new-session" s else s)
]) (
s:
lib.foldr (
envVar:
assert pkgs.lib.isValidPosixName envVar;
unsafe-add-raw-args "--setenv ${envVar} ${s.env.${envVar}}"
) 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 '' ${
function cleanup { if builtins.length state.cleanup > 0 then
${lib.concatStringsSep "\n" state.cleanup} ''
function cleanup {
${lib.concatStringsSep "\n" state.cleanup}
}
trap cleanup EXIT
''
else
""
} }
trap cleanup EXIT ${state.runtime}
'' else ""} ${
${state.runtime} if builtins.length state.cleanup > 0 then "" else "exec "
${if builtins.length state.cleanup > 0 then "" else "exec "}${state.cmd} "''${RUNTIME_ARGS[@]}" -- ${state.entry} ${state.argv} }${state.cmd} "''${RUNTIME_ARGS[@]}" -- ${state.entry} ${state.argv}
'') '')
(text: pkgs.writeShellApplication { inherit name text; }) (text: pkgs.writeShellApplication { inherit name text; })
# forward man pages # forward man pages
(jailed: if exe ? man then jailed // { inherit (exe) man; } else jailed) (jailed: if exe ? man then jailed // { inherit (exe) man; } else jailed)
] ]
); );
in { in
{
combinators = allCombinators; combinators = allCombinators;
__functor = _: jail; __functor = _: jail;
} }

View file

@ -2,39 +2,52 @@
# 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 =
pkgs = import nixpkgs { system = "x86_64-linux"; }; { nixpkgs, ... }:
lib = pkgs.lib; let
haskellPackages = pkgs.haskellPackages.callCabal2nix "jail-nix-tests" ./. { }; pkgs = import nixpkgs { system = "x86_64-linux"; };
testDependencies = [ lib = pkgs.lib;
(pkgs.haskellPackages.ghc.withPackages (p: haskellPackages.buildInputs)) haskellPackages = pkgs.haskellPackages.callCabal2nix "jail-nix-tests" ./. { };
pkgs.cabal-install testDependencies = [
]; (pkgs.haskellPackages.ghc.withPackages (p: haskellPackages.buildInputs))
in { pkgs.cabal-install
apps.x86_64-linux.runChecks = {
type = "app";
program = lib.getExe (pkgs.writeShellApplication {
name = "run-all-jail-nix-tests";
runtimeInputs = testDependencies;
text = ''
${lib.pipe {
jail-nix = ../.;
nixpkgs = nixpkgs;
} [
(lib.mapAttrsToList (name: path: "${name}=${path}"))
(lib.concatStringsSep " ")
(lib.toShellVar "NIX_PATH")
]} cabal test
'';
});
};
devShells.x86_64-linux.default = pkgs.mkShell {
buildInputs = testDependencies ++ [
(pkgs.haskell-language-server.override { dynamic = true; })
pkgs.ghcid
pkgs.hpack
]; ];
mkApp = name: runtimeInputs: script: {
type = "app";
program = lib.getExe (
pkgs.writeShellApplication {
inherit name runtimeInputs;
text = script;
}
);
};
in
{
apps.x86_64-linux.runTests = mkApp "run-all-jail-nix-tests" testDependencies ''
${
lib.pipe
{
jail-nix = ../.;
nixpkgs = nixpkgs;
}
[
(lib.mapAttrsToList (name: path: "${name}=${path}"))
(lib.concatStringsSep " ")
(lib.toShellVar "NIX_PATH")
]
} 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 {
buildInputs = testDependencies ++ [
(pkgs.haskell-language-server.override { dynamic = true; })
pkgs.ghcid
pkgs.hpack
];
};
}; };
};
} }

View file

@ -3,116 +3,124 @@
# 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 =
pkgs = import nixpkgs { system = "x86_64-linux"; }; { self, nixpkgs, ... }:
lib = pkgs.lib; let
pkgs = import nixpkgs { system = "x86_64-linux"; };
lib = pkgs.lib;
repo = rec { repo = rec {
rev = if self ? rev then self.rev else lib.warn "Repo is dirty, links will not work!" "???"; rev = if self ? rev then self.rev else lib.warn "Repo is dirty, links will not work!" "???";
shortRev = lib.substring 0 8 rev; shortRev = lib.substring 0 8 rev;
urls = { urls = {
base = "https://git.sr.ht/~alexdavid/jail.nix"; base = "https://git.sr.ht/~alexdavid/jail.nix";
commit = "https://git.sr.ht/~alexdavid/jail.nix/commit/${rev}"; commit = "https://git.sr.ht/~alexdavid/jail.nix/commit/${rev}";
file = file: lineNr: "https://git.sr.ht/~alexdavid/jail.nix/tree/${rev}${file}#L${toString lineNr}"; file = file: lineNr: "https://git.sr.ht/~alexdavid/jail.nix/tree/${rev}${file}#L${toString lineNr}";
};
}; };
};
formatCombinatorDoc = name: combinatorObj: let formatCombinatorDoc =
attrPos = builtins.unsafeGetAttrPos "__functor" combinatorObj; name: combinatorObj:
file = lib.removePrefix (toString ./..) attrPos.file; let
in '' attrPos = builtins.unsafeGetAttrPos "__functor" combinatorObj;
### ${name} file = lib.removePrefix (toString ./..) attrPos.file;
**${name} :: ${combinatorObj.sig}** in
''
### ${name}
**${name} :: ${combinatorObj.sig}**
[Source](${repo.urls.file file attrPos.line}) [Source](${repo.urls.file file attrPos.line})
${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 =
lib.pipe allCombinators [ filter:
(lib.filterAttrs (_: filter)) lib.pipe allCombinators [
(lib.mapAttrsToList formatCombinatorDoc) (lib.filterAttrs (_: filter))
(lib.concatStringsSep "\n\n---\n") (lib.mapAttrsToList formatCombinatorDoc)
(lib.concatStringsSep "\n\n---\n")
];
hr = ''<hr style="border: 2px solid #272525">'';
is = flag: combinator: combinator ? ${flag} && combinator.${flag};
in
''
# Combinators
jail.nix combinators are the building blocks to create `Permission`s,
which grant a program specific permissions at runtime.
These permissions can be passed into the third argument to `jail`
function, as well as
[`basePermissions`](advanced-configuration.md#basepermissions).
A `Permission` is a `State -> State` function where `State` is an
internal type that is used to eventually build the final bubblewrap
flags. The type of `State` is not part of the public API, and may change
in the future.
${hr}
${formatSection (v: !(is "deprecated" v || is "includedInBasePermissions" v || is "internal" v))}
${hr}
## Default Included Combinators
The following combinators are enabled by default, and do not need to be
explicitly added to your jails unless you [override
`basePermissions`](advanced-configuration.md#basepermissions).
${formatSection (is "includedInBasePermissions")}
${hr}
## Deprecated Combinators
The following combinators have been deprecated, and may be removed in the
future.
${formatSection (is "deprecated")}
'';
mkdocsSettings = {
site_name = "jail-nix";
repo_url = repo.urls.base;
theme = {
name = "readthedocs";
hljs_languages = [ "nix" ];
};
# Copyright is placed directly into the page within a <p> tag.
# Concatenating with </p><p> here is super janky, but good enough for
# now.
copyright = lib.concatStringsSep "</p><p>" [
''
Copyright © 2025 Alex David ///
<a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a>.
''
''
This documentation was generated from the <a href="${repo.urls.base}">jail.nix repo</a>,
commit <a href="${repo.urls.commit}"><code>${repo.shortRev}</code></a>.
''
]; ];
hr = ''<hr style="border: 2px solid #272525">'';
is = flag: combinator: combinator ? ${flag} && combinator.${flag};
in ''
# Combinators
jail.nix combinators are the building blocks to create `Permission`s,
which grant a program specific permissions at runtime.
These permissions can be passed into the third argument to `jail`
function, as well as
[`basePermissions`](advanced-configuration.md#basepermissions).
A `Permission` is a `State -> State` function where `State` is an
internal type that is used to eventually build the final bubblewrap
flags. The type of `State` is not part of the public API, and may change
in the future.
${hr}
${formatSection (v: !(is "deprecated" v || is "includedInBasePermissions" v || is "internal" v))}
${hr}
## Default Included Combinators
The following combinators are enabled by default, and do not need to be
explicitly added to your jails unless you [override
`basePermissions`](advanced-configuration.md#basepermissions).
${formatSection (is "includedInBasePermissions")}
${hr}
## Deprecated Combinators
The following combinators have been deprecated, and may be removed in the
future.
${formatSection (is "deprecated")}
'';
mkdocsSettings = {
site_name = "jail-nix";
repo_url = repo.urls.base;
theme = {
name = "readthedocs";
hljs_languages = [ "nix" ];
}; };
# Copyright is placed directly into the page within a <p> tag. in
# Concatenating with </p><p> here is super janky, but good enough for {
# now. packages.x86_64-linux.default = pkgs.runCommand "website" { buildInputs = [ pkgs.mkdocs ]; } ''
copyright = lib.concatStringsSep "</p><p>" [ cp -r ${./static-docs} docs
'' chmod -R +w docs
Copyright © 2025 Alex David /// echo ${lib.escapeShellArg combinatorDocs} > docs/combinators.md
<a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a>. echo ${lib.escapeShellArg (builtins.toJSON mkdocsSettings)} > mkdocs.yml
'' mkdocs build
'' mv site $out
This documentation was generated from the <a href="${repo.urls.base}">jail.nix repo</a>, '';
commit <a href="${repo.urls.commit}"><code>${repo.shortRev}</code></a>.
''
];
}; };
in {
packages.x86_64-linux.default = pkgs.runCommand "website" { buildInputs = [ pkgs.mkdocs ]; } ''
cp -r ${./static-docs} docs
chmod -R +w docs
echo ${lib.escapeShellArg combinatorDocs} > docs/combinators.md
echo ${lib.escapeShellArg (builtins.toJSON mkdocsSettings)} > mkdocs.yml
mkdocs build
mv site $out
'';
};
} }