use krab_api::crypt::SecretCodec;
use krab_api::{App, Authn, Config, Keyring, MemStore, Resealed, SyncMode};
use krab_runtime::Runtime;
use krab_runtime::docker::Docker;
use krab_runtime::host::host_info;
use krab_runtime::native::Native;
use krab_runtime::native::net::{Net, NetConfig};
use krab_tls::{kubeconfig, pki, sa::Signer, tokens};
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
fn usage() -> ! {
eprintln!(
"usage: krab serve [--listen ADDR] [--data-dir DIR] [--docker-sock PATH] [--token TOKEN]\n\
\x20 [--cgroup-root PATH] [--poll-secs N] [--watch-log-kib N]\n\
\x20 [--store-sync immediate|eventual] [--volume-root PATH] [--network NAME]\n\
\x20 [--node-name NAME] [--insecure-http] [--no-controllers]\n\
\x20 [--encryption-key-file PATH]\n\
\x20 [--allow-host-path DIR]... [--runtime docker|native]\n\
\x20 [--youki PATH] [--native-root DIR] [--native-seccomp-profile FILE] [--native-hostnet]\n\
\x20 [--native-bridge NAME] [--native-subnet CIDR] [--native-allow-cidr CIDR]...\n\
\x20 krab agent --kubeconfig FILE --node-name NAME [--runtime docker|native] [--node-ip IP]\n\
\x20 [--docker-sock PATH] [--volume-root DIR] [--network NAME] [--allow-host-path DIR]...\n\
\x20 [--youki PATH] [--native-root DIR] [--native-seccomp-profile FILE] [--native-bridge NAME] [--native-subnet CIDR]\n\
\x20 [--native-allow-cidr CIDR]... [--kubelet-listen ADDR|off] [--serving-dir DIR]\n\
\x20 [--client-ca FILE] [--cluster-cidr CIDR] [--wireguard] [--wireguard-iface NAME]\n\
\x20 [--wireguard-port N] [--wireguard-endpoint IP:PORT] [--service-proxy]\n\
\x20 [--cluster-dns] [--cluster-domain NAME] [--native-trust-cidr CIDR]... [--native-pod-host-port PORT]... (--native-subnet auto uses Node.spec.podCIDR)\n\
\x20 krab agent join --server https://HOST:PORT --token-file FILE --ca-hash sha256:HEX [--data-dir DIR]\n\
\x20 [--node-name NAME] ...agent flags above\n\
\x20 krab net-clean [--data-dir DIR] [--native-root DIR] [--native-bridge NAME]\n\
\x20 krab kubeconfig [--server URL] [--data-dir DIR] [--out FILE]\n\
\x20 krab token create USER [--data-dir DIR] [--groups G]\n\
\x20 krab keygen --out PATH [--id ID]\n\
\x20 krab rekey --encryption-key-file PATH [--data-dir DIR]"
);
std::process::exit(2);
}
fn fail(what: &str, e: impl std::fmt::Display) -> ! {
eprintln!("krab: {what}: {e}");
std::process::exit(1);
}
fn next_val(rest: &mut Vec<String>, name: &str) -> String {
if rest.is_empty() || rest[0].starts_with("--") {
eprintln!("missing value for {name}");
std::process::exit(2);
}
rest.remove(0)
}
fn data_dir(cli: Option<String>) -> PathBuf {
match cli {
Some(d) => PathBuf::from(d),
None => {
let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
PathBuf::from(home).join(".krab")
}
}
}
fn split_listen(listen: &str) -> (String, u16) {
let (host, port) = listen.rsplit_once(':').unwrap_or(("127.0.0.1", "6443"));
let port = port.parse().unwrap_or(6443);
match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
Some(h) => (h.to_string(), port),
None => (host.to_string(), port),
}
}
fn server_url(listen: &str) -> String {
let (host, port) = split_listen(listen);
let host = match host.as_str() {
"" | "0.0.0.0" | "::" => "127.0.0.1".to_string(),
other => other.to_string(),
};
format!("https://{host}:{port}")
}
fn is_loopback(listen: &str) -> bool {
let (host, _) = split_listen(listen);
if host == "localhost" {
return true;
}
matches!(IpAddr::from_str(&host), Ok(ip) if ip.is_loopback())
}
fn private_dir(dir: &Path) {
use std::os::unix::fs::PermissionsExt;
if let Err(e) = std::fs::create_dir_all(dir)
.and_then(|_| std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)))
{
fail(&dir.display().to_string(), e);
}
}
fn ensure_pki(dir: &Path, node_name: &str, extra_hosts: &[String]) -> pki::Pki {
match pki::ensure(&dir.join("pki"), node_name, extra_hosts) {
Ok(p) => p,
Err(e) => fail("pki", e),
}
}
fn extra_sans(listen: &str, node_ip: Option<&str>) -> Vec<String> {
let (host, _) = split_listen(listen);
let mut out = Vec::new();
for candidate in std::iter::once(host).chain(node_ip.map(str::to_string)) {
let covered = candidate.is_empty()
|| candidate == "0.0.0.0"
|| candidate == "::"
|| candidate == "localhost"
|| matches!(IpAddr::from_str(&candidate), Ok(ip) if ip.is_loopback());
if !covered {
out.push(candidate);
}
}
out
}
fn load_tokens(dir: &Path) -> tokens::StaticTokens {
let path = dir.join("tokens.csv");
match std::fs::read(&path) {
Ok(b) => match tokens::StaticTokens::parse(&String::from_utf8_lossy(&b)) {
Ok(t) => t,
Err(e) => fail("tokens.csv", e),
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
match tokens::StaticTokens::parse("") {
Ok(t) => t,
Err(e) => fail("tokens", e),
}
}
Err(e) => fail("tokens.csv", e),
}
}
fn agent_home() -> String {
match std::env::var("HOME") {
Ok(h) if h.starts_with('/') => h,
_ => fail(
"HOME",
"not set; pass --data-dir, --serving-dir and --native-root explicitly",
),
}
}
fn take_flag(rest: &mut Vec<String>, name: &str) -> Option<String> {
let i = rest.iter().position(|a| a == name)?;
rest.remove(i);
if i < rest.len() && !rest[i].starts_with("--") {
Some(rest.remove(i))
} else {
eprintln!("missing value for {name}");
std::process::exit(2);
}
}
fn join_step(rest: &mut Vec<String>) -> PathBuf {
let server = take_flag(rest, "--server");
let ca_hash = take_flag(rest, "--ca-hash");
let token_file = take_flag(rest, "--token-file");
let token_arg = take_flag(rest, "--token");
let dir = take_flag(rest, "--data-dir")
.map(PathBuf::from)
.unwrap_or_else(|| {
let home = agent_home();
PathBuf::from(home).join(".krab").join("agent")
});
let node_name = rest
.iter()
.position(|a| a == "--node-name")
.and_then(|i| rest.get(i + 1).cloned())
.or_else(|| std::env::var("KRAB_NODE_NAME").ok())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| host_info().hostname);
if let Some(kubeconfig) = krab_agent::join::existing(&dir, &node_name) {
rest.push("--kubeconfig".into());
rest.push(kubeconfig.to_string_lossy().into_owned());
return dir;
}
let server = server.unwrap_or_else(|| {
eprintln!("krab agent join: --server is required");
std::process::exit(2);
});
let ca_hash = ca_hash.unwrap_or_else(|| {
eprintln!("krab agent join: --ca-hash is required");
std::process::exit(2);
});
let token = match (
token_file,
token_arg,
std::env::var("KRAB_JOIN_TOKEN")
.ok()
.filter(|s| !s.is_empty()),
) {
(Some(f), _, _) => std::fs::read_to_string(&f)
.map(|s| s.trim().to_string())
.unwrap_or_else(|e| fail(&f, e)),
(None, Some(t), _) => t,
(None, None, Some(t)) => t,
_ => {
eprintln!("krab agent join: pass --token-file FILE (or KRAB_JOIN_TOKEN)");
std::process::exit(2);
}
};
let r = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let kubeconfig = r
.block_on(krab_agent::join::join(&krab_agent::join::JoinOpts {
server,
token,
ca_hash,
node_name,
dir: dir.clone(),
}))
.unwrap_or_else(|e| fail("join", e));
rest.push("--kubeconfig".into());
rest.push(kubeconfig.to_string_lossy().into_owned());
dir
}
fn agent(args: &[String]) {
let mut rest = args.to_vec();
let mut rotate_dir = None;
if rest.first().map(String::as_str) == Some("join") {
rest.remove(0);
rotate_dir = Some(join_step(&mut rest));
}
let mut kubeconfig: Option<String> = None;
let mut node_name: Option<String> = None;
let mut node_ip: Option<String> = None;
let mut cluster_cidr: Option<String> = None;
let mut wireguard = false;
let mut wg_iface = "wg-krab".to_string();
let mut wg_port: u16 = 51820;
let mut wg_endpoint: Option<String> = None;
let mut service_proxy = false;
let mut cluster_dns = false;
let mut cluster_domain = "cluster.local".to_string();
let mut kubelet_listen = "0.0.0.0:10250".to_string();
let mut serving_dir: Option<String> = None;
let mut client_ca: Option<String> = None;
let mut sock = "/var/run/docker.sock".to_string();
let mut vol_root: Option<String> = None;
let mut network: Option<String> = None;
let mut allow_host: Vec<PathBuf> = Vec::new();
let mut runtime = "docker".to_string();
let mut youki = "youki".to_string();
let mut native_root: Option<String> = None;
let mut native_seccomp = None;
let mut native_bridge = "krab0".to_string();
let mut native_subnet = "10.88.0.0/16".to_string();
let mut native_allow: Vec<String> = Vec::new();
let mut native_trust: Vec<String> = Vec::new();
let mut native_host_ports: Vec<u16> = Vec::new();
while !rest.is_empty() {
let name = rest.remove(0);
match name.as_str() {
"--kubeconfig" => kubeconfig = Some(next_val(&mut rest, &name)),
"--node-name" => node_name = Some(next_val(&mut rest, &name)),
"--node-ip" => node_ip = Some(next_val(&mut rest, &name)),
"--cluster-cidr" => cluster_cidr = Some(next_val(&mut rest, &name)),
"--wireguard" => wireguard = true,
"--wireguard-iface" => wg_iface = next_val(&mut rest, &name),
"--wireguard-port" => {
wg_port = next_val(&mut rest, &name)
.parse()
.unwrap_or_else(|e| fail("--wireguard-port", e))
}
"--wireguard-endpoint" => wg_endpoint = Some(next_val(&mut rest, &name)),
"--service-proxy" => service_proxy = true,
"--cluster-dns" => cluster_dns = true,
"--cluster-domain" => cluster_domain = next_val(&mut rest, &name),
"--kubelet-listen" => kubelet_listen = next_val(&mut rest, &name),
"--serving-dir" => serving_dir = Some(next_val(&mut rest, &name)),
"--client-ca" => client_ca = Some(next_val(&mut rest, &name)),
"--docker-sock" => sock = next_val(&mut rest, &name),
"--volume-root" => vol_root = Some(next_val(&mut rest, &name)),
"--network" => network = Some(next_val(&mut rest, &name)),
"--runtime" => runtime = next_val(&mut rest, &name),
"--youki" => youki = next_val(&mut rest, &name),
"--native-root" => native_root = Some(next_val(&mut rest, &name)),
"--native-seccomp-profile" => {
native_seccomp = Some(PathBuf::from(next_val(&mut rest, &name)))
}
"--native-bridge" => native_bridge = next_val(&mut rest, &name),
"--native-subnet" => native_subnet = next_val(&mut rest, &name),
"--native-allow-cidr" => native_allow.push(next_val(&mut rest, &name)),
"--native-pod-host-port" => native_host_ports.push(
next_val(&mut rest, &name)
.parse()
.unwrap_or_else(|e| fail("--native-pod-host-port", e)),
),
"--native-trust-cidr" => native_trust.push(next_val(&mut rest, &name)),
"--allow-host-path" => {
let d = next_val(&mut rest, &name);
match std::fs::canonicalize(&d) {
Ok(p) if p.is_dir() && p != Path::new("/") => allow_host.push(p),
Ok(_) => fail(
&d,
"--allow-host-path must be an existing directory other than /",
),
Err(e) => fail(&d, e),
}
}
other => {
eprintln!("unknown flag {other}");
std::process::exit(2);
}
}
}
let kubelet_bind = match kubelet_listen.as_str() {
"off" => None,
addr => match addr.parse() {
Ok(a) => Some(a),
Err(e) => fail("--kubelet-listen", e),
},
};
let Some(kubeconfig) = kubeconfig.or_else(|| std::env::var("KUBECONFIG").ok()) else {
eprintln!("krab agent: --kubeconfig is required");
std::process::exit(2);
};
let node_name = node_name
.or_else(|| std::env::var("KRAB_NODE_NAME").ok())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| host_info().hostname);
let opts = krab_agent::Options {
kubeconfig: kubeconfig.into(),
node_name,
node_ip: node_ip
.or_else(|| std::env::var("KRAB_NODE_IP").ok())
.filter(|s| !s.is_empty()),
volume_root: vol_root.map(PathBuf::from),
network,
allow_host_paths: allow_host,
kubelet_bind,
serving_dir: serving_dir.map(PathBuf::from).unwrap_or_else(|| {
let home = agent_home();
PathBuf::from(home).join(".krab").join("agent")
}),
client_ca: client_ca.map(PathBuf::from),
cluster: None,
rotate_dir,
};
let wants_cluster = wireguard || service_proxy || cluster_dns || cluster_cidr.is_some();
if wants_cluster && runtime != "native" {
eprintln!("krab agent: cluster networking flags require --runtime native");
std::process::exit(2);
}
if native_seccomp.is_some() && runtime != "native" {
fail("--native-seccomp-profile", "requires --runtime native");
}
let mut opts = opts;
match runtime.as_str() {
"docker" => run_agent(opts, Docker::new(sock)),
"native" => {
let root = native_root.map(PathBuf::from).unwrap_or_else(|| {
let home = agent_home();
PathBuf::from(home).join(".krab").join("native")
});
if native_subnet == "auto" {
let r = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
native_subnet = r
.block_on(krab_agent::wait_pod_cidr(
&opts.kubeconfig,
&opts.node_name,
opts.node_ip.clone(),
"native",
))
.unwrap_or_else(|e| fail("podCIDR", e));
}
let mut net = match NetConfig::new(&native_bridge, &native_subnet)
.and_then(|c| c.with_allow(&native_allow))
.and_then(|c| c.with_trust(&native_trust))
.map(|c| c.with_host_ports(&native_host_ports))
{
Ok(c) => c,
Err(e) => {
eprintln!("krab: {e}");
std::process::exit(2);
}
};
if wants_cluster {
let Some(cidr) = cluster_cidr.as_deref() else {
eprintln!(
"krab agent: --cluster-cidr is required with cluster networking flags"
);
std::process::exit(2);
};
let ingress: Vec<String> = if wireguard {
vec![wg_iface.clone()]
} else {
Vec::new()
};
net = net
.with_cluster(cidr, &ingress, cluster_dns)
.unwrap_or_else(|e| fail("--cluster-cidr", e));
opts.cluster = Some(krab_agent::Cluster {
wireguard: wireguard.then(|| krab_agent::WireGuard {
cluster_subnet: net.cluster[0],
local_subnet: net.subnet,
iface: wg_iface.clone(),
port: wg_port,
endpoint: wg_endpoint.clone(),
}),
service_proxy,
dns: net.dns_ip().map(|ip| (ip, cluster_domain.clone())),
});
}
let net = Some(net);
match Native::new_with_profile(root, youki, net, native_seccomp) {
Ok(rt) => run_agent(opts, rt),
Err(e) => fail("native runtime", e),
}
}
other => {
eprintln!("krab: unknown runtime {other}, expected docker or native");
std::process::exit(2);
}
}
}
fn run_agent<R: Runtime + Clone>(opts: krab_agent::Options, rt: R) {
let tokio_rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
if let Err(e) = tokio_rt.block_on(krab_agent::run(opts, Arc::new(rt))) {
fail("agent", e);
}
}
fn serve(args: &[String]) {
let mut cfg = Config::default();
let mut rest = args.to_vec();
let mut sock = "/var/run/docker.sock".to_string();
let mut data: Option<String> = None;
let mut vol_root: Option<String> = None;
let mut network: Option<String> = None;
let mut node_name: Option<String> = None;
let mut store_sync = "immediate".to_string();
let mut insecure = false;
let mut no_controllers = false;
let mut allow_host: Vec<PathBuf> = Vec::new();
let mut runtime = "docker".to_string();
let mut youki = "youki".to_string();
let mut native_root: Option<String> = None;
let mut native_seccomp = None;
let mut native_hostnet = false;
let mut native_bridge = "krab0".to_string();
let mut native_subnet = "10.88.0.0/16".to_string();
let mut native_allow: Vec<String> = Vec::new();
let mut key_file: Option<String> = None;
while !rest.is_empty() {
let name = rest.remove(0);
match name.as_str() {
"--listen" => cfg.listen = next_val(&mut rest, &name),
"--encryption-key-file" => key_file = Some(next_val(&mut rest, &name)),
"--docker-sock" => sock = next_val(&mut rest, &name),
"--token" => cfg.token = Some(next_val(&mut rest, &name)),
"--cgroup-root" => cfg.cgroup_root = next_val(&mut rest, &name),
"--poll-secs" => {
cfg.poll_interval =
Duration::from_secs(next_val(&mut rest, &name).parse().unwrap_or(2))
}
"--watch-log-kib" => {
cfg.watch_log_bytes =
next_val(&mut rest, &name).parse::<usize>().unwrap_or(512) * 1024
}
"--data-dir" => data = Some(next_val(&mut rest, &name)),
"--volume-root" => vol_root = Some(next_val(&mut rest, &name)),
"--network" => network = Some(next_val(&mut rest, &name)),
"--node-name" => node_name = Some(next_val(&mut rest, &name)),
"--store-sync" => store_sync = next_val(&mut rest, &name),
"--insecure-http" => insecure = true,
"--no-controllers" => no_controllers = true,
"--runtime" => runtime = next_val(&mut rest, &name),
"--youki" => youki = next_val(&mut rest, &name),
"--native-root" => native_root = Some(next_val(&mut rest, &name)),
"--native-seccomp-profile" => {
native_seccomp = Some(PathBuf::from(next_val(&mut rest, &name)))
}
"--native-hostnet" => native_hostnet = true,
"--native-bridge" => native_bridge = next_val(&mut rest, &name),
"--native-subnet" => native_subnet = next_val(&mut rest, &name),
"--native-allow-cidr" => native_allow.push(next_val(&mut rest, &name)),
"--allow-host-path" => {
let d = next_val(&mut rest, &name);
match std::fs::canonicalize(&d) {
Ok(p) if p.is_dir() && p != Path::new("/") => allow_host.push(p),
Ok(_) => fail(
&d,
"--allow-host-path must be an existing directory other than /",
),
Err(e) => fail(&d, e),
}
}
other => {
eprintln!("unknown flag {other}");
std::process::exit(2);
}
}
}
if native_seccomp.is_some() && runtime != "native" {
fail("--native-seccomp-profile", "requires --runtime native");
}
if cfg.token.is_none() {
cfg.token = std::env::var("KRAB_TOKEN").ok();
}
if let Err(e) = check_native_auth(&runtime, insecure, cfg.token.as_deref()) {
eprintln!("krab: {e}");
std::process::exit(2);
}
cfg.allow_host_paths = Arc::new(allow_host.clone());
let dir = data_dir(data);
private_dir(&dir);
let mode = match SyncMode::from_str(&store_sync) {
Ok(m) => m,
Err(e) => {
eprintln!("krab: {e}");
std::process::exit(2);
}
};
let store = match MemStore::open_with(dir.join("store.redb"), cfg.watch_log_bytes, 256, mode) {
Ok(s) => s,
Err(e) => fail("store", e),
};
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(
dir.join("store.redb"),
std::fs::Permissions::from_mode(0o600),
);
}
let migrated = seal_secrets(&store, key_file.as_deref(), false).rewritten;
if migrated > 0 {
eprintln!("krab: encrypted {migrated} plaintext secrets");
}
let node_ip = std::env::var("KRAB_NODE_IP").ok().filter(|s| !s.is_empty());
let node_name = node_name
.or_else(|| std::env::var("KRAB_NODE_NAME").ok())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| host_info().hostname);
let opts = ServeOpts {
cfg,
insecure,
dir,
node_name,
node_ip,
store,
vol_root,
network,
no_controllers,
allow_host,
};
match runtime.as_str() {
"docker" => launch(Docker::new(sock), opts),
"native" => {
let root = native_root
.map(PathBuf::from)
.unwrap_or_else(|| opts.dir.join("native"));
let net = if native_hostnet {
None
} else {
match NetConfig::new(&native_bridge, &native_subnet)
.and_then(|c| c.with_allow(&native_allow))
{
Ok(c) => Some(c),
Err(e) => {
eprintln!("krab: {e}");
std::process::exit(2);
}
}
};
match Native::new_with_profile(root, youki, net, native_seccomp) {
Ok(rt) => launch(rt, opts),
Err(e) => fail("native runtime", e),
}
}
other => {
eprintln!("krab: unknown runtime {other}, expected docker or native");
std::process::exit(2);
}
}
}
struct ServeOpts {
cfg: Config,
insecure: bool,
dir: PathBuf,
node_name: String,
node_ip: Option<String>,
store: Arc<MemStore>,
vol_root: Option<String>,
network: Option<String>,
no_controllers: bool,
allow_host: Vec<PathBuf>,
}
fn launch<R: Runtime + Clone>(docker: R, o: ServeOpts) {
let ServeOpts {
cfg,
insecure,
dir,
node_name,
node_ip,
store,
vol_root,
network,
no_controllers,
allow_host,
} = o;
let bind_addr = cfg.listen.clone();
let tls_pki = if insecure {
if !is_loopback(&cfg.listen) && cfg.token.is_none() {
eprintln!("krab: --insecure-http outside loopback requires --token");
std::process::exit(2);
}
None
} else {
Some(ensure_pki(
&dir,
&node_name,
&extra_sans(&cfg.listen, node_ip.as_deref()),
))
};
let bind = move || async move {
match tokio::net::TcpListener::bind(&bind_addr).await {
Ok(l) => l,
Err(e) => fail(&format!("bind {bind_addr}"), e),
}
};
match &tls_pki {
None => {
let app = App::new(cfg, docker.clone(), store.clone());
let stopper = docker.clone();
run_serve(stopper, async move {
start_controllers(
&dir,
store,
docker,
node_name,
vol_root,
network,
no_controllers,
allow_host,
);
krab_api::serve(app, bind().await).await
})
}
Some(p) => {
let signer = match Signer::new(&dir) {
Ok(s) => s,
Err(e) => fail("service account signer", e),
};
let auth = Authn {
static_tokens: load_tokens(&dir),
signer: Some(signer),
};
let url = server_url(&cfg.listen);
let kc_path = dir.join("kubeconfig");
match kubeconfig::write(&kc_path, &kubeconfig::render(&url, p, "krab")) {
Ok(()) => println!("kubeconfig: {}", kc_path.display()),
Err(e) => fail("kubeconfig", e),
}
let app = App::with_auth(cfg, docker.clone(), store.clone(), Some(auth));
let stopper = docker.clone();
run_serve(stopper, async move {
start_controllers(
&dir,
store,
docker,
node_name,
vol_root,
network,
no_controllers,
allow_host,
);
krab_api::serve_tls(app, bind().await, p).await
})
}
}
}
#[allow(clippy::too_many_arguments)]
fn start_controllers<R: Runtime>(
dir: &Path,
store: Arc<MemStore>,
docker: R,
node_name: String,
vol_root: Option<String>,
network: Option<String>,
no_controllers: bool,
allow_host: Vec<PathBuf>,
) {
if no_controllers {
return;
}
let mut kcfg = krab_controllers::Config::new(node_name);
kcfg.volume_root = match vol_root {
Some(v) => v.into(),
None => dir.join("volumes"),
};
if let Some(v) = network {
kcfg.network = v;
}
kcfg.allow_host_paths = allow_host;
tokio::spawn(krab_controllers::run_with(store, Arc::new(docker), kcfg));
}
async fn term_signal() {
use tokio::signal::unix::{SignalKind, signal};
match (
signal(SignalKind::terminate()),
signal(SignalKind::interrupt()),
) {
(Ok(mut t), Ok(mut i)) => {
tokio::select! {
_ = t.recv() => {}
_ = i.recv() => {}
}
}
_ => std::future::pending().await,
}
}
fn run_serve<R, T>(stopper: T, future: R)
where
R: std::future::Future<Output = std::io::Result<()>>,
T: Runtime,
{
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let res = rt.block_on(async move {
tokio::select! {
r = future => r,
_ = term_signal() => {
eprintln!("krab: shutting down");
stopper.shutdown().await;
Ok(())
}
}
});
if let Err(e) = res {
eprintln!("krab: {e}");
std::process::exit(1);
}
}
fn kubeconfig_cmd(args: &[String]) {
let mut rest = args.to_vec();
let mut server = "https://127.0.0.1:6443".to_string();
let mut data: Option<String> = None;
let mut out: Option<String> = None;
while !rest.is_empty() {
let name = rest.remove(0);
let mut next = || next_val(&mut rest, &name);
match name.as_str() {
"--server" => server = next(),
"--data-dir" => data = Some(next()),
"--out" => out = Some(next()),
_ => usage(),
}
}
let dir = data_dir(data);
if let Err(e) = std::fs::create_dir_all(&dir) {
fail(&dir.display().to_string(), e);
}
let host = server
.split_once("://")
.map(|(_, r)| r.rsplit_once(':').map_or(r, |(h, _)| h).to_string())
.unwrap_or_default();
let pki = ensure_pki(&dir, "krab", &[host]);
let kc = kubeconfig::render(&server, &pki, "krab");
match out {
Some(p) => {
if let Err(e) = kubeconfig::write(Path::new(&p), &kc) {
fail("kubeconfig", e);
}
}
None => {
use std::io::Write;
let mut so = std::io::stdout().lock();
let _ = so.write_all(kc.as_bytes());
}
}
}
fn token_cmd(args: &[String]) {
let mut rest = args.to_vec();
if rest.first().map(String::as_str) != Some("create") {
usage();
}
rest.remove(0);
if rest.is_empty() || rest[0].starts_with("--") {
usage();
}
let user = rest.remove(0);
let mut data: Option<String> = None;
let mut groups = "system:masters".to_string();
while !rest.is_empty() {
let name = rest.remove(0);
let mut next = || next_val(&mut rest, &name);
match name.as_str() {
"--data-dir" => data = Some(next()),
"--groups" => groups = next(),
_ => usage(),
}
}
let bad = |x: &str, extra: char| {
x.chars()
.any(|c| matches!(c, '"' | '\n' | '\r') || c == extra)
};
if user.is_empty() || bad(&user, ',') || bad(&groups, '"') {
fail(
"token",
"user and group names must not contain commas, quotes or newlines",
);
}
let dir = data_dir(data);
private_dir(&dir);
let token = match tokens::generate() {
Ok(t) => t,
Err(e) => fail("token", e),
};
let path = dir.join("tokens.csv");
let line = format!("{token},{user},krab,\"{groups}\"\n");
let res = (|| -> std::io::Result<()> {
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(line.as_bytes())
})();
if let Err(e) = res {
fail(&path.display().to_string(), e);
}
println!("{token}");
eprintln!(
"user {user} added to {}; restart krab serve to load it",
path.display()
);
}
fn load_keyring(path: &str) -> Keyring {
match Keyring::from_file(Path::new(path)) {
Ok(k) => k,
Err(e) => fail(&format!("encryption key file {path}"), e),
}
}
fn seal_secrets(store: &MemStore, key_file: Option<&str>, all: bool) -> Resealed {
store.set_codec(Box::new(SecretCodec::new(key_file.map(load_keyring))));
let r = match store.reseal(all && key_file.is_some()) {
Ok(r) => r,
Err(e) => fail("secret encryption", e),
};
if r.unreadable > 0 {
eprintln!(
"krab: {} stored secrets cannot be decrypted: missing or wrong --encryption-key-file",
r.unreadable
);
}
r
}
fn keygen_cmd(args: &[String]) {
let mut rest = args.to_vec();
let mut out: Option<String> = None;
let mut id = "key1".to_string();
while !rest.is_empty() {
let name = rest.remove(0);
let mut next = || next_val(&mut rest, &name);
match name.as_str() {
"--out" => out = Some(next()),
"--id" => id = next(),
_ => usage(),
}
}
let Some(out) = out else { usage() };
if let Err(e) = Keyring::generate_file(Path::new(&out), &id) {
fail(&out, e);
}
eprintln!("key {id} written to {out}");
}
fn rekey_cmd(args: &[String]) {
let mut rest = args.to_vec();
let mut data: Option<String> = None;
let mut key_file: Option<String> = None;
while !rest.is_empty() {
let name = rest.remove(0);
let mut next = || next_val(&mut rest, &name);
match name.as_str() {
"--data-dir" => data = Some(next()),
"--encryption-key-file" => key_file = Some(next()),
_ => usage(),
}
}
let Some(key_file) = key_file else { usage() };
let path = data_dir(data).join("store.redb");
if !path.exists() {
fail(&path.display().to_string(), "store not found");
}
let store = match MemStore::open(&path, 1 << 20, 16) {
Ok(s) => s,
Err(e) => fail("store", e),
};
let r = seal_secrets(&store, Some(&key_file), true);
eprintln!(
"krab: re-encrypted {} secrets with the first key",
r.rewritten
);
if r.unreadable > 0 {
std::process::exit(1);
}
}
fn check_native_auth(runtime: &str, insecure: bool, token: Option<&str>) -> Result<(), String> {
if runtime == "native" && insecure && token.is_none_or(str::is_empty) {
return Err(
"--runtime native with --insecure-http requires --token: pods share the host network and would reach the API without authentication"
.into(),
);
}
Ok(())
}
fn net_clean_cmd(args: &[String]) {
let mut rest = args.to_vec();
let mut data: Option<String> = None;
let mut root: Option<String> = None;
let mut bridge = "krab0".to_string();
while !rest.is_empty() {
let name = rest.remove(0);
let mut next = || next_val(&mut rest, &name);
match name.as_str() {
"--data-dir" => data = Some(next()),
"--native-root" => root = Some(next()),
"--native-bridge" => bridge = next(),
_ => usage(),
}
}
let root = root
.map(PathBuf::from)
.unwrap_or_else(|| data_dir(data).join("native"));
let res = NetConfig::new(&bridge, "10.88.0.0/16")
.and_then(|c| Net::open(&root.join("net"), c))
.and_then(|n| n.clean());
if let Err(e) = res {
fail("net-clean", e);
}
}
fn main() {
let mut args = std::env::args().skip(1);
let cmd = args.next().unwrap_or_default();
let rest: Vec<String> = args.collect();
match cmd.as_str() {
"serve" => serve(&rest),
"agent" => agent(&rest),
"kubeconfig" => kubeconfig_cmd(&rest),
"token" => token_cmd(&rest),
"net-clean" => net_clean_cmd(&rest),
"shim" => std::process::exit(krab_runtime::native::shim::main(&rest)),
"keygen" => keygen_cmd(&rest),
"rekey" => rekey_cmd(&rest),
_ => usage(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn native_insecure_requires_token() {
assert!(check_native_auth("native", true, None).is_err());
assert!(check_native_auth("native", true, Some("")).is_err());
assert!(check_native_auth("native", true, Some("t")).is_ok());
assert!(check_native_auth("native", false, None).is_ok());
assert!(check_native_auth("docker", true, None).is_ok());
}
}