lifecycle: rewrite the container entrypoint in Rust (#26320)

* lifecycle: rewrite the container entrypoint in Rust and add a debug image

* improvements

* rename debug-image stage to just debug

* rename final stage

Co-authored-by: Marc 'risson' Schmitt <[email protected]>
Signed-off-by: Emil Burzo <[email protected]>

* message when readline is unavailable

* remove find_shell / no_shell_error

* refactor commands/arguments based on feedback

* redo

* wip

* wip

* wip

* read AUTHENTIK_DEBUGGER directly in rust instead of shelling out

---------

Signed-off-by: Emil Burzo <[email protected]>
Co-authored-by: Marc 'risson' Schmitt <[email protected]>
This commit is contained in:
Emil BurzoandMarc 'risson' Schmitt authored and GitHub committed 2026-10-14 11:43:05 +01:00
1 parent ba8463b14f
commit 8c43c174fa
12 files changed
+446 -127

No files matched your search

+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
- name: generate docs
run: |
uv run make migrate
uv run ak build_source_docs
uv run python -m manage build_source_docs
- uses: nwtgck/actions-netlify@d22a32a27c918fe470bbc562e984f80ec48c2668 # v4.0.0
id: netlify
with:
@@ -25,7 +25,7 @@ jobs:
token: ${{ steps.generate_token.outputs.token }}
- name: Setup authentik env
uses: ./.github/actions/setup
- run: uv run ak update_webauthn_mds
- run: uv run python -m manage update_webauthn_mds
- uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v7
id: cpr
with:
@@ -38,7 +38,7 @@ jobs:
uv run make i18n-extract
- name: run compile
run: |
uv run ak compilemessages
uv run python -m manage compilemessages
make web-check-compile
- name: Create Pull Request
if: ${{ github.event_name != 'pull_request' }}
+6 -1
View File
@@ -68,7 +68,12 @@ metrics-exporter-prometheus = { version = "= 0.18.3", default-features = false }
moka = { version = "= 0.12.16", default-features = false, features = [
"future",
] }
nix = { version = "= 0.31.3", features = ["hostname", "signal"] }
nix = { version = "= 0.31.3", features = [
"fs",
"hostname",
"signal",
"user",
] }
notify = "= 8.2.0"
pem = "= 4.0.0"
percent-encoding = "= 2.3.2"
+3 -3
View File
@@ -132,7 +132,7 @@ run-watch: ## Run the authentik server and worker, with auto reloading
watchexec --on-busy-update=restart --stop-signal=SIGINT --exts py,rs --no-meta --notify -- $(UV) run ak allinone
core-i18n-extract:
$(UV) run ak makemessages \
$(UV) run python -m manage makemessages \
--add-location file \
--no-obsolete \
--ignore web \
@@ -191,7 +191,7 @@ endif
gen-build: ## Generate schema.yml and blueprints/schema.json from Django model definitions
AUTHENTIK_DEBUG=true \
AUTHENTIK_OUTPOSTS__DISABLE_EMBEDDED_OUTPOST=true \
$(UV) run ak build_schema
$(UV) run python -m manage build_schema
gen-compose:
$(UV) run scripts/generate_compose.py
@@ -387,7 +387,7 @@ ci-lint-bandit: ci--meta-debug
$(UV) run bandit -c pyproject.toml -r $(PY_SOURCES) -iii
ci-lint-pending-migrations: ci--meta-debug
$(UV) run ak makemigrations --check
$(UV) run python -m manage makemigrations --check
ci-lint-cargo-deny: ci--meta-debug
$(CARGO) deny --config "${PWD}/.cargo/deny.toml" --locked --workspace check
-100
View File
@@ -1,100 +0,0 @@
#!/usr/bin/env bash
set -e -o pipefail
MODE_FILE="$TMPDIR/authentik-mode"
function log {
printf '{"event": "%s", "level": "info", "logger": "bootstrap"}\n' "$@" >&2
}
function wait_for_db {
python -m lifecycle.wait_for_db
log "Bootstrap completed"
}
function run_authentik {
case "$1" in
server | healthcheck | allinone | worker)
if [[ -x "$(command -v authentik)" ]]; then
echo authentik "$@"
else
echo cargo run -- "$@"
fi
;;
manage)
shift 1
echo python -m manage "$@"
;;
*)
echo "$@"
;;
esac
}
function check_if_root_and_run {
if [[ $EUID -ne 0 ]]; then
log "Not running as root, disabling permission fixes"
exec $(run_authentik "$@")
return
fi
SOCKET="/var/run/docker.sock"
if [[ -e "$SOCKET" ]]; then
# Get group ID of the docker socket, so we can create a matching group and
# add ourselves to it
DOCKER_GID="$(stat -c "%g" "${SOCKET}")"
# Ensure group for the id exists
getent group "${DOCKER_GID}" || groupadd -f -g "${DOCKER_GID}" docker
usermod -a -G "${DOCKER_GID}" authentik
fi
# Fix permissions of certs and media
chown -R authentik:authentik /data /certs "${PROMETHEUS_MULTIPROC_DIR}"
chmod ug+rwx /data
chmod ug+rx /certs
exec setpriv --reuid authentik --regid authentik --init-groups -- env HOME=/authentik $(run_authentik "$@")
}
function prepare_debug {
# Only attempt to install debug dependencies if we're running in a container
if [ ! -d /ak-root ]; then
return
fi
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y --no-install-recommends krb5-kdc krb5-user krb5-admin-server libkrb5-dev gcc
source "${VENV_PATH}/bin/activate"
uv sync --active --locked
touch /unittest.xml
chown authentik:authentik /unittest.xml
}
if [[ -z "${PROMETHEUS_MULTIPROC_DIR}" ]]; then
export PROMETHEUS_MULTIPROC_DIR="${TMPDIR:-/tmp}/authentik_prometheus_tmp"
fi
mkdir -p "${PROMETHEUS_MULTIPROC_DIR}"
if [[ "$(python -m authentik.lib.config debugger 2>/dev/null)" == "True" ]]; then
prepare_debug
fi
if [[ "$1" == "bash" ]]; then
exec /usr/bin/env -S bash "$@"
elif [[ "$1" == "dump_config" ]]; then
shift 1
exec python -m authentik.lib.config "$@"
elif [[ "$1" == "debug" ]]; then
exec sleep infinity
elif [[ "$1" == "test-all" ]]; then
wait_for_db
prepare_debug
chmod 777 /root
check_if_root_and_run manage test authentik
elif [[ "$1" == "allinone" ]] || [[ "$1" == "server" ]] || [[ "$1" == "worker" ]]; then
wait_for_db
check_if_root_and_run "$@"
elif [[ "$1" == "healthcheck" ]]; then
check_if_root_and_run "$@" "$(cat "$MODE_FILE")"
else
wait_for_db
exec python -m manage "$@"
fi
Regular → Executable
+27 -10
View File
@@ -1,17 +1,34 @@
"""Wrapper for lifecycle/ak, to be installed by uv"""
#!/ak-root/.venv/bin/python
"""Hands every command to the authentik binary.
from os import system, waitstatus_to_exitcode
from pathlib import Path
from sys import argv, exit
The container runs this file as `/lifecycle/ak`.
In a development checkout, uv installs it as a console script.
"""
import os
import shutil
import sys
# Subcommands of the authentik binary
COMMANDS = ("allinone", "server", "worker", "proxy", "healthcheck", "test-all", "debug")
# Subcommands that hand their arguments to another program
PASSTHROUGH_COMMANDS = ("manage", "dump_config", "bash", "sh")
def main():
"""Wrapper around ak bash script"""
current_path = Path(__file__)
args = " ".join(argv[1:])
res = system(f"{current_path.parent}/ak {args}") # nosec
exit_code = waitstatus_to_exitcode(res)
exit(exit_code)
args = sys.argv[1:]
if args and args[0] in COMMANDS:
argv = args
elif args and args[0] in PASSTHROUGH_COMMANDS:
argv = [args[0], "--", *args[1:]]
else:
argv = ["manage", "--", *args]
binary = shutil.which("authentik")
if binary:
os.execv(binary, [binary, *argv])
# A development checkout without an installed binary
os.execvp("cargo", ["cargo", "run", "--", *argv]) # nosec
if __name__ == "__main__":
+3 -2
View File
@@ -183,7 +183,7 @@ RUN --mount=type=bind,target=pyproject.toml,src=pyproject.toml \
uv sync --locked --no-install-project --no-dev
# Stage: Run
FROM python-base AS final-image
FROM python-base AS final
ARG VERSION
ARG GIT_BUILD_HASH
@@ -233,7 +233,8 @@ COPY ./lifecycle/ /lifecycle
COPY ./authentik/sources/kerberos/krb5.conf /etc/krb5.conf
COPY --from=rust-builder /bin/authentik /bin/authentik
COPY ./packages/ /ak-root/packages
RUN ln -s /ak-root/packages /packages
RUN ln -s /ak-root/packages /packages && \
ln -s ak.py /lifecycle/ak
COPY --from=python-deps /ak-root/.venv /ak-root/.venv
COPY --from=node-builder /work/web/dist/ /web/dist/
COPY --from=node-builder /work/web/authentik/ /web/authentik/
+2
View File
@@ -151,6 +151,8 @@ pub struct Config {
#[serde(deserialize_with = "deserialize_str_or_bool")]
pub debug: bool,
#[serde(deserialize_with = "deserialize_str_or_bool")]
pub debugger: bool,
#[serde(default)]
pub secret_key: String,
+345
View File
@@ -0,0 +1,345 @@
//! Container entrypoint
use std::{
fs,
os::unix::{
fs::{MetadataExt as _, PermissionsExt as _},
process::CommandExt as _,
},
path::{Path, PathBuf},
process::Command,
time::Duration,
};
use ak_common::config;
use argh::FromArgs;
use eyre::{Result, WrapErr as _, eyre};
use nix::{
fcntl::{AT_FDCWD, AtFlags},
unistd::{Gid, Group, Uid, User, getuid, setgid, setgroups, setuid},
};
use tracing::{info, warn};
/// The unprivileged user the server runs as.
const AK_USER: &str = "authentik";
/// Mounted by deployments that let the worker manage outpost containers.
const DOCKER_SOCKET: &str = "/var/run/docker.sock";
/// Where Python's prometheus client keeps the metrics of each process.
const PROMETHEUS_MULTIPROC_DIR: &str = "PROMETHEUS_MULTIPROC_DIR";
#[derive(Debug, FromArgs, PartialEq)]
/// Run a Django management command.
#[argh(subcommand, name = "manage")]
pub(crate) struct Manage {
/// the management command and its arguments
#[argh(positional, greedy)]
args: Vec<String>,
}
#[derive(Debug, FromArgs, PartialEq)]
/// Run the test suite.
#[argh(subcommand, name = "test-all")]
#[expect(
clippy::empty_structs_with_brackets,
reason = "argh doesn't support unit structs"
)]
pub(crate) struct TestAll {}
#[derive(Debug, FromArgs, PartialEq)]
/// Print the configuration, or the values of the given keys.
#[argh(subcommand, name = "dump_config")]
pub(crate) struct DumpConfig {
/// the keys to print
#[argh(positional, greedy)]
keys: Vec<String>,
}
#[derive(Debug, FromArgs, PartialEq)]
/// Run bash.
#[argh(subcommand, name = "bash")]
pub(crate) struct Bash {
/// the arguments for bash
#[argh(positional, greedy)]
args: Vec<String>,
}
#[derive(Debug, FromArgs, PartialEq)]
/// Run sh.
#[argh(subcommand, name = "sh")]
pub(crate) struct Sh {
/// the arguments for sh
#[argh(positional, greedy)]
args: Vec<String>,
}
#[derive(Debug, FromArgs, PartialEq)]
/// Idle, so that a shell can be opened in the container.
#[argh(subcommand, name = "debug")]
#[expect(
clippy::empty_structs_with_brackets,
reason = "argh doesn't support unit structs"
)]
pub(crate) struct Debug {}
/// Where Python's prometheus client keeps the metrics of each process.
fn prometheus_dir() -> Result<PathBuf> {
let dir = std::env::var_os(PROMETHEUS_MULTIPROC_DIR)
.filter(|dir| !dir.is_empty())
.map_or_else(
|| std::env::temp_dir().join("authentik_prometheus_tmp"),
PathBuf::from,
);
fs::create_dir_all(&dir)?;
Ok(dir)
}
/// Replace this process with `cmd`. Only returns when that fails.
fn exec(mut cmd: Command) -> Result<()> {
let err = cmd.exec();
Err(err).wrap_err_with(|| format!("failed to run {}", cmd.get_program().display()))
}
/// Run `cmd` and wait for it, failing when it fails.
fn run(cmd: &mut Command) -> Result<()> {
let status = cmd
.status()
.wrap_err_with(|| format!("failed to run {}", cmd.get_program().display()))?;
if !status.success() {
return Err(eyre!(
"{} exited with {status}",
cmd.get_program().display()
));
}
Ok(())
}
/// Install what `test-all` and `AUTHENTIK_DEBUGGER` need.
fn prepare_debug() -> Result<()> {
// Only in the container, a development checkout has all of it already
if !Path::new("/ak-root").is_dir() {
return Ok(());
}
let venv = std::env::var_os("VENV_PATH").ok_or_else(|| eyre!("VENV_PATH is not set"))?;
info!("installing the development dependencies");
run(Command::new("apt-get").arg("update"))?;
run(Command::new("apt-get")
.args(["install", "-y", "--no-install-recommends"])
.args([
"krb5-kdc",
"krb5-user",
"krb5-admin-server",
"libkrb5-dev",
"gcc",
])
.env("DEBIAN_FRONTEND", "noninteractive"))?;
run(Command::new("uv")
.args(["sync", "--active", "--locked"])
.env("VIRTUAL_ENV", venv))?;
// The test suite writes its report there after dropping to `authentik`, and can't create it
let user = User::from_name(AK_USER)?.ok_or_else(|| eyre!("user {AK_USER} does not exist"))?;
fs::OpenOptions::new()
.create(true)
.append(true)
.open("/unittest.xml")?;
nix::unistd::chown("/unittest.xml", Some(user.uid), Some(user.gid))?;
Ok(())
}
/// `chown -R`, skipping entries that already have the right owner.
fn chown_tree(path: &Path, uid: Uid, gid: Gid) -> Result<()> {
if !path.exists() {
return Ok(());
}
nix::unistd::chown(path, Some(uid), Some(gid))?;
let mut stack = vec![path.to_path_buf()];
while let Some(dir) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let child = entry.path();
if entry.file_type().is_ok_and(|t| t.is_dir()) {
stack.push(child.clone());
}
let Ok(meta) = fs::symlink_metadata(&child) else {
continue;
};
if meta.uid() == uid.as_raw() && meta.gid() == gid.as_raw() {
continue;
}
if let Err(err) = nix::unistd::fchownat(
AT_FDCWD,
&child,
Some(uid),
Some(gid),
AtFlags::AT_SYMLINK_NOFOLLOW,
) {
warn!(path = %child.display(), %err, "could not change owner");
}
}
}
Ok(())
}
fn add_mode(path: &Path, bits: u32) -> Result<()> {
if !path.is_dir() {
return Ok(());
}
let mut perms = fs::metadata(path)?.permissions();
perms.set_mode(perms.mode() | bits);
fs::set_permissions(path, perms)?;
Ok(())
}
/// The gid that owns a mounted docker socket, if there is one.
fn docker_socket_gid() -> Option<Gid> {
fs::metadata(DOCKER_SOCKET)
.ok()
.map(|meta| Gid::from_raw(meta.gid()))
}
/// Fix up ownership while still root, then switch to `authentik`. Returns its home directory.
fn become_authentik(prometheus_dir: &Path) -> Result<PathBuf> {
let user = User::from_name(AK_USER)?.ok_or_else(|| eyre!("user {AK_USER} does not exist"))?;
let mut groups = vec![user.gid];
if let Some(gid) = docker_socket_gid()
&& !groups.contains(&gid)
{
// setgroups takes the numeric gid directly
let name = Group::from_gid(gid)
.ok()
.flatten()
.map_or_else(|| "unnamed".to_owned(), |g| g.name);
info!(
gid = gid.as_raw(),
group = name,
"granting access to the docker socket"
);
groups.push(gid);
}
for path in [Path::new("/data"), Path::new("/certs"), prometheus_dir] {
chown_tree(path, user.uid, user.gid)
.wrap_err_with(|| format!("failed to change owner of {}", path.display()))?;
}
// Mirrors the old `chmod ug+rwx /data` and `chmod ug+rx /certs`
add_mode(Path::new("/data"), 0o770)?;
// 'certs' deliberately gets no owner write bit
add_mode(Path::new("/certs"), 0o550)?;
setgroups(&groups)?;
setgid(user.gid)?;
setuid(user.uid)?;
// Still being root would make `boot` loop
if getuid() != user.uid || getuid().is_root() {
return Err(eyre!("failed to drop privileges to {AK_USER}"));
}
Ok(user.dir)
}
fn wait_for_db() -> Result<()> {
run(Command::new("python").args(["-m", "lifecycle.wait_for_db"]))?;
info!("bootstrap completed");
Ok(())
}
/// Get the process ready to run the server or the worker.
pub(crate) fn boot() -> Result<()> {
let prometheus_dir = prometheus_dir()?;
let mut env = Vec::new();
if std::env::var_os(PROMETHEUS_MULTIPROC_DIR).as_deref() != Some(prometheus_dir.as_os_str()) {
env.push((PROMETHEUS_MULTIPROC_DIR, prometheus_dir.clone()));
}
if getuid().is_root() {
config::init()?;
if config::get().debugger {
prepare_debug()?;
}
env.push(("HOME", become_authentik(&prometheus_dir)?));
}
// Changing our own environment needs unsafe code, so exec ourselves with the new one
if !env.is_empty() {
let mut cmd = Command::new(std::env::current_exe()?);
cmd.args(std::env::args_os().skip(1)).envs(env);
return exec(cmd);
}
wait_for_db()
}
pub(crate) fn manage(args: &Manage) -> Result<()> {
// manage.py waits for the database itself
let mut cmd = Command::new("python");
cmd.args(["-m", "manage"])
.args(&args.args)
.env(PROMETHEUS_MULTIPROC_DIR, prometheus_dir()?);
exec(cmd)
}
pub(crate) fn test_all() -> Result<()> {
let prometheus_dir = prometheus_dir()?;
// manage.py waits for the database itself
let mut cmd = Command::new("python");
cmd.args(["-m", "manage", "test", "authentik"])
.env(PROMETHEUS_MULTIPROC_DIR, &prometheus_dir);
if getuid().is_root() {
prepare_debug()?;
cmd.env("HOME", become_authentik(&prometheus_dir)?);
}
exec(cmd)
}
pub(crate) fn dump_config(args: &DumpConfig) -> Result<()> {
let mut cmd = Command::new("python");
cmd.args(["-m", "authentik.lib.config"])
.args(&args.keys)
.env(PROMETHEUS_MULTIPROC_DIR, prometheus_dir()?);
exec(cmd)
}
fn shell(program: &str, args: &[String]) -> Result<()> {
let mut cmd = Command::new(program);
cmd.args(args)
.env(PROMETHEUS_MULTIPROC_DIR, prometheus_dir()?);
exec(cmd)
}
pub(crate) fn bash(args: &Bash) -> Result<()> {
shell("bash", &args.args)
}
pub(crate) fn sh(args: &Sh) -> Result<()> {
shell("sh", &args.args)
}
pub(crate) fn idle() -> ! {
loop {
std::thread::sleep(Duration::from_hours(1));
}
}
#[cfg(test)]
mod tests {
use super::*;
// `lifecycle/ak.py` puts a `--` in front of these, so that argh keeps what follows as it is
#[test]
fn arguments_after_the_separator_are_kept() {
for args in [
&["--help"][..],
&["help"],
&["shell", "-c", "print(1)"],
&["migrate", "--", "--fake"],
] {
let argv: Vec<&str> = std::iter::once("--").chain(args.iter().copied()).collect();
let manage = Manage::from_args(&["manage"], &argv).expect("failed to parse");
assert_eq!(manage.args, args);
}
}
#[test]
fn shell_flags_are_kept() {
let bash = Bash::from_args(&["bash"], &["--", "-c", "echo hi"]).expect("failed to parse");
assert_eq!(bash.args, ["-c", "echo hi"]);
}
}
+8 -3
View File
@@ -1,6 +1,6 @@
use ak_common::Mode;
use argh::FromArgs;
use eyre::{Result, eyre};
use eyre::{Result, WrapErr as _, eyre};
use reqwest::blocking::Client;
use tracing::info;
@@ -9,11 +9,16 @@ use tracing::info;
#[argh(subcommand, name = "healthcheck")]
pub(super) struct Cli {
#[argh(positional)]
mode: String,
mode: Option<String>,
}
pub(super) fn run(args: &Cli) -> Result<()> {
let mode: Mode = args.mode.parse()?;
let mode: Mode = if let Some(mode) = &args.mode {
mode.parse()?
} else {
Mode::load().wrap_err("failed to read the mode of the running server or worker")?;
Mode::get()
};
info!(%mode, "checking health");
let response = match mode {
+49 -5
View File
@@ -7,6 +7,8 @@ use argh::FromArgs;
use eyre::{Result, eyre};
use tracing::{error, info, trace};
#[cfg(feature = "core")]
mod boot;
#[cfg(feature = "core")]
pub(crate) mod brands;
mod healthcheck;
@@ -37,6 +39,18 @@ enum Command {
#[cfg(feature = "proxy")]
Proxy(outpost::proxy::Cli),
Healthcheck(healthcheck::Cli),
#[cfg(feature = "core")]
Manage(boot::Manage),
#[cfg(feature = "core")]
TestAll(boot::TestAll),
#[cfg(feature = "core")]
DumpConfig(boot::DumpConfig),
#[cfg(feature = "core")]
Bash(boot::Bash),
#[cfg(feature = "core")]
Sh(boot::Sh),
#[cfg(feature = "core")]
Debug(boot::Debug),
}
#[derive(Debug, FromArgs, PartialEq)]
@@ -50,22 +64,45 @@ pub(crate) struct AllInOne {}
fn main() -> Result<()> {
let tracing_crude = ak_tracing::install_crude();
info!(version = authentik_full_version(), "authentik is starting");
let cli: Cli = argh::from_env();
match &cli.command {
#[cfg(feature = "core")]
Command::AllInOne(_) => Mode::set(Mode::AllInOne)?,
Command::AllInOne(_) => {
boot::boot()?;
Mode::set(Mode::AllInOne)?;
}
#[cfg(feature = "core")]
Command::Server(_) => Mode::set(Mode::Server)?,
Command::Server(_) => {
boot::boot()?;
Mode::set(Mode::Server)?;
}
#[cfg(feature = "core")]
Command::Worker(_) => Mode::set(Mode::Worker)?,
Command::Worker(_) => {
boot::boot()?;
Mode::set(Mode::Worker)?;
}
#[cfg(feature = "proxy")]
Command::Proxy(_) => Mode::set(Mode::Proxy)?,
Command::Healthcheck(args) => return healthcheck::run(args),
// These don't run authentik itself, so they skip the setup below and its logging to stdout
#[cfg(feature = "core")]
Command::Manage(args) => return boot::manage(args),
#[cfg(feature = "core")]
Command::TestAll(_) => return boot::test_all(),
#[cfg(feature = "core")]
Command::DumpConfig(args) => return boot::dump_config(args),
#[cfg(feature = "core")]
Command::Bash(args) => return boot::bash(args),
#[cfg(feature = "core")]
Command::Sh(args) => return boot::sh(args),
#[cfg(feature = "core")]
Command::Debug(_) => boot::idle(),
}
info!(version = authentik_full_version(), "authentik is starting");
trace!("installing error formatting");
color_eyre::install()?;
@@ -130,7 +167,14 @@ fn main() -> Result<()> {
)
.await?;
}
// We're checking for this before starting anything else
// We're checking for these before starting anything else
#[cfg(feature = "core")]
Command::Manage(_)
| Command::TestAll(_)
| Command::DumpConfig(_)
| Command::Bash(_)
| Command::Sh(_)
| Command::Debug(_) => unreachable!(),
Command::Healthcheck(_) => unreachable!(),
}