1use crate::util::{self, base64_decode, name, ns, quantity, s, uid};
2use krab_runtime::policy::{dns_label, host_path, rel_path_ok};
3use krab_runtime::{ContainerSpec, MANAGED_LABEL, Mount, PortSpec, RestartPolicy, container_name};
4use krab_store::MemStore;
5use serde_json::Value;
6use std::collections::{BTreeMap, HashMap};
7use std::fs;
8use std::io::Write;
9use std::path::{Path, PathBuf};
10
11pub struct Ctx<'a> {
12 pub store: &'a MemStore,
13 pub pod: &'a Value,
14 pub node: &'a str,
15 pub pod_ip: &'a str,
16 pub host_ip: &'a str,
17 pub subpaths: Option<&'a Path>,
18}
19
20pub const SPEC_HASH: &str = "krab.io/spec-hash";
21
22pub fn spec_hash(c: &Value) -> String {
23 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
24 for b in c.to_string().bytes() {
25 h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
26 }
27 format!("{h:016x}")
28}
29
30pub fn volume_name(pod_uid: &str, vol: &str) -> String {
31 let short: String = pod_uid.chars().filter(|c| *c != '-').take(12).collect();
32 format!("krab_{short}_{vol}")
33}
34
35fn data_of(
36 store: &MemStore,
37 kind: &str,
38 namespace: &str,
39 obj: &str,
40) -> Option<BTreeMap<String, Vec<u8>>> {
41 let v = util::get(store, &format!("{kind}/{namespace}/{obj}"))?;
42 let mut out = BTreeMap::new();
43 if let Some(m) = v["data"].as_object() {
44 for (k, val) in m {
45 let raw = val.as_str().unwrap_or("");
46 let bytes = if kind == "secrets" {
47 base64_decode(raw)?
48 } else {
49 raw.as_bytes().to_vec()
50 };
51 out.insert(k.clone(), bytes);
52 }
53 }
54 if let Some(m) = v["stringData"].as_object().filter(|_| kind == "secrets") {
55 for (k, val) in m {
56 out.insert(k.clone(), val.as_str().unwrap_or("").as_bytes().to_vec());
57 }
58 }
59 if let Some(m) = v["binaryData"].as_object() {
60 for (k, val) in m {
61 out.insert(k.clone(), base64_decode(val.as_str().unwrap_or(""))?);
62 }
63 }
64 Some(out)
65}
66
67fn write_file(dir: &Path, rel: &str, data: &[u8], mode: u32) -> Result<(), String> {
68 if !rel_path_ok(rel) {
69 return Err(format!("invalid file path {rel:?}"));
70 }
71 let parts: Vec<&str> = rel.split('/').collect();
72 let mut cur = dir.to_path_buf();
73 for (i, part) in parts.iter().enumerate() {
74 cur.push(part);
75 let last = i + 1 == parts.len();
76 match fs::symlink_metadata(&cur) {
77 Ok(m) if m.file_type().is_symlink() => {
78 return Err(format!("refusing to follow symlink {}", cur.display()));
79 }
80 Ok(m) if !last && !m.is_dir() => {
81 return Err(format!("{} is not a directory", cur.display()));
82 }
83 Ok(m) if last && m.is_dir() => {
84 return Err(format!("{} is a directory", cur.display()));
85 }
86 Ok(_) if last => {}
87 Ok(_) => {}
88 Err(_) if !last => fs::create_dir(&cur).map_err(|e| e.to_string())?,
89 Err(_) => {}
90 }
91 }
92 let mut o = fs::OpenOptions::new();
93 o.write(true).create_new(true);
94 #[cfg(unix)]
95 {
96 use std::os::unix::fs::OpenOptionsExt;
97 o.mode(mode);
98 }
99 let tmp = cur.with_file_name(format!(
100 ".{}.krab-tmp",
101 cur.file_name().and_then(|n| n.to_str()).unwrap_or("f")
102 ));
103 let _ = fs::remove_file(&tmp);
104 let mut f = o.open(&tmp).map_err(|e| e.to_string())?;
105 f.write_all(data).map_err(|e| e.to_string())?;
106 #[cfg(unix)]
107 {
108 use std::os::unix::fs::PermissionsExt;
109 f.set_permissions(fs::Permissions::from_mode(mode))
110 .map_err(|e| e.to_string())?;
111 }
112 fs::rename(&tmp, &cur).map_err(|e| e.to_string())
113}
114
115fn real_dir(dir: &Path) -> Result<(), String> {
116 fs::create_dir_all(dir).map_err(|e| e.to_string())?;
117 match fs::symlink_metadata(dir) {
118 Ok(m) if m.is_dir() => Ok(()),
119 _ => Err(format!("{} is not a directory", dir.display())),
120 }
121}
122
123pub enum VolSrc {
124 Bind(String),
125 ReadOnly(String),
126 Named(String),
127 Tmpfs,
128}
129
130fn uid_ok(u: &str) -> bool {
131 !u.is_empty() && u.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
132}
133
134fn claim_volume(
135 store: &MemStore,
136 namespace: &str,
137 claim: &str,
138 root: &Path,
139) -> Result<String, String> {
140 let pvc = util::get(
141 store,
142 &format!("persistentvolumeclaims/{namespace}/{claim}"),
143 )
144 .ok_or_else(|| format!("persistentvolumeclaim \"{claim}\" not found"))?;
145 if !pvc["metadata"]["deletionTimestamp"].is_null() {
146 return Err(format!(
147 "persistentvolumeclaim \"{claim}\" is being deleted"
148 ));
149 }
150 if s(&pvc, "/status/phase") != "Bound" {
151 return Err(format!("persistentvolumeclaim \"{claim}\" is not bound"));
152 }
153 let pv_ok = util::get(
154 store,
155 &format!("persistentvolumes/{}", s(&pvc, "/spec/volumeName")),
156 )
157 .is_some_and(|pv| {
158 s(&pv, "/spec/claimRef/uid") == uid(&pvc)
159 && s(
160 &pv,
161 "/metadata/annotations/pv.kubernetes.io~1provisioned-by",
162 ) == crate::pvc::PROVISIONER
163 });
164 if !pv_ok {
165 return Err(format!(
166 "persistentvolumeclaim \"{claim}\" has no local-path volume"
167 ));
168 }
169 crate::pvc::checked_dir(root, namespace, claim, uid(&pvc))
170 .map(|p| p.to_string_lossy().into_owned())
171}
172
173pub fn prepare_volumes(
174 store: &MemStore,
175 pod: &Value,
176 root: &Path,
177 allow: &[PathBuf],
178) -> Result<HashMap<String, VolSrc>, String> {
179 let mut out = HashMap::new();
180 let namespace = ns(pod);
181 if !uid_ok(uid(pod)) {
182 return Err(format!("invalid pod uid {:?}", uid(pod)));
183 }
184 let pod_dir = root.join(uid(pod));
185 for v in pod["spec"]["volumes"].as_array().into_iter().flatten() {
186 let vname = s(v, "/name").to_string();
187 if !dns_label(&vname) {
188 return Err(format!("invalid volume name {vname:?}"));
189 }
190 let src = if v["emptyDir"].is_object() {
191 if s(v, "/emptyDir/medium") == "Memory" {
192 VolSrc::Tmpfs
193 } else {
194 VolSrc::Named(volume_name(uid(pod), &vname))
195 }
196 } else if v["hostPath"].is_object() {
197 let path = s(v, "/hostPath/path");
198 let real = host_path(path, allow)?;
199 if !real.exists() {
200 fs::create_dir_all(&real).map_err(|e| e.to_string())?;
201 }
202 let real = host_path(path, allow)?;
203 VolSrc::Bind(real.to_string_lossy().into_owned())
204 } else if v["configMap"].is_object() || v["secret"].is_object() {
205 let secret = v["secret"].is_object();
206 let (kind, src, obj) = if secret {
207 ("secrets", &v["secret"], s(v, "/secret/secretName"))
208 } else {
209 ("configmaps", &v["configMap"], s(v, "/configMap/name"))
210 };
211 let dir = pod_dir.join(&vname);
212 let optional = src["optional"].as_bool() == Some(true);
213 match data_of(store, kind, namespace, obj) {
214 None if !optional => return Err(format!("{kind} \"{obj}\" not found")),
215 found => {
216 real_dir(&dir)?;
217 let data = found.unwrap_or_default();
218 let mode = if secret {
219 0o400
220 } else {
221 src["defaultMode"].as_u64().unwrap_or(0o644) as u32 & 0o777
222 };
223 let items: Vec<(String, String)> = match src["items"].as_array() {
224 Some(items) => items
225 .iter()
226 .map(|i| (s(i, "/key").to_string(), s(i, "/path").to_string()))
227 .collect(),
228 None => data.keys().map(|k| (k.clone(), k.clone())).collect(),
229 };
230 for (k, rel) in items {
231 if let Some(bytes) = data.get(&k) {
232 write_file(&dir, &rel, bytes, mode)?;
233 }
234 }
235 VolSrc::ReadOnly(dir.to_string_lossy().into_owned())
236 }
237 }
238 } else if v["persistentVolumeClaim"].is_object() {
239 let dir = claim_volume(
240 store,
241 namespace,
242 s(v, "/persistentVolumeClaim/claimName"),
243 root,
244 )?;
245 if v["persistentVolumeClaim"]["readOnly"].as_bool() == Some(true) {
246 VolSrc::ReadOnly(dir)
247 } else {
248 VolSrc::Bind(dir)
249 }
250 } else if v.as_object().is_some_and(|m| m.keys().any(|k| k != "name")) {
251 return Err(format!("volume {vname}: unsupported volume type"));
252 } else {
253 VolSrc::Named(volume_name(uid(pod), &vname))
254 };
255 out.insert(vname, src);
256 }
257 Ok(out)
258}
259
260fn sub_path(base: &str, sub: &str) -> Result<String, String> {
261 if sub.is_empty() {
262 return Ok(base.to_string());
263 }
264 if !rel_path_ok(sub) {
265 return Err(format!("invalid subPath {sub:?}"));
266 }
267 let root = fs::canonicalize(base).map_err(|e| format!("volume {base}: {e}"))?;
268 let mut cur = root.clone();
269 for part in sub.split('/') {
270 cur.push(part);
271 match fs::symlink_metadata(&cur) {
272 Ok(m) if m.file_type().is_symlink() => {
273 return Err(format!("subPath {sub:?} must not contain symlinks"));
274 }
275 Ok(_) => {}
276 Err(_) => fs::create_dir(&cur).map_err(|e| e.to_string())?,
277 }
278 }
279 let real = fs::canonicalize(&cur).map_err(|e| e.to_string())?;
280 if !real.starts_with(&root) {
281 return Err(format!("subPath {sub:?} escapes the volume"));
282 }
283 Ok(real.to_string_lossy().into_owned())
284}
285
286fn pinned(base: &str, sub: &str, pin: Option<&Path>, i: usize) -> Result<String, String> {
287 let checked = sub_path(base, sub)?;
288 let Some(dir) = pin.filter(|_| !sub.is_empty()) else {
289 return Ok(checked);
290 };
291 let target = dir.join(i.to_string());
292 let root = fs::canonicalize(base).map_err(|e| format!("volume {base}: {e}"))?;
293 krab_runtime::subpath::pin(&root, sub, &target).map_err(|e| format!("subPath {sub:?}: {e}"))?;
294 Ok(target.to_string_lossy().into_owned())
295}
296
297pub fn mounts(c: &Value, vols: &HashMap<String, VolSrc>) -> Result<Vec<Mount>, String> {
298 mounts_in(c, vols, None)
299}
300
301pub fn mounts_in(
302 c: &Value,
303 vols: &HashMap<String, VolSrc>,
304 pin: Option<&Path>,
305) -> Result<Vec<Mount>, String> {
306 let mut out = Vec::new();
307 for (i, m) in c["volumeMounts"]
308 .as_array()
309 .into_iter()
310 .flatten()
311 .enumerate()
312 {
313 let dst = s(m, "/mountPath").to_string();
314 if !dst.starts_with('/') || dst.contains(':') {
315 return Err(format!("invalid mountPath {dst:?}"));
316 }
317 let ro = m["readOnly"].as_bool() == Some(true);
318 let sub = s(m, "/subPath");
319 let Some(v) = vols.get(s(m, "/name")) else {
320 continue;
321 };
322 out.push(match v {
323 VolSrc::Bind(p) => Mount::Bind {
324 src: pinned(p, sub, pin, i)?,
325 dst,
326 read_only: ro,
327 },
328 VolSrc::ReadOnly(p) => Mount::Bind {
329 src: pinned(p, sub, pin, i)?,
330 dst,
331 read_only: true,
332 },
333 VolSrc::Named(_) if !sub.is_empty() => {
334 return Err(format!(
335 "subPath {sub:?} is not supported for emptyDir volume {:?}",
336 s(m, "/name")
337 ));
338 }
339 VolSrc::Named(n) => Mount::Volume {
340 name: n.clone(),
341 dst,
342 read_only: ro,
343 },
344 VolSrc::Tmpfs => Mount::Tmpfs { dst },
345 });
346 }
347 Ok(out)
348}
349
350fn env_name(svc: &str) -> String {
351 svc.to_uppercase().replace(['-', '.'], "_")
352}
353
354pub fn service_env(store: &MemStore, namespace: &str) -> Vec<(String, String)> {
355 let mut out = Vec::new();
356 let mut services = util::list(store, &format!("services/{namespace}/"));
357 if namespace != "default"
358 && let Some(master) = util::get(store, "services/default/kubernetes")
359 {
360 services.push(("services/default/kubernetes".into(), master));
361 }
362 for (_, svc) in services {
363 let ports = svc["spec"]["ports"].as_array().cloned().unwrap_or_default();
364 let Some(first) = ports.first() else { continue };
365 let n = env_name(name(&svc));
366 let routed = s(&svc, "/metadata/annotations/krab.io~1routed-clusterip") == "true";
367 let host = match s(&svc, "/spec/clusterIP").parse::<std::net::Ipv4Addr>() {
368 Ok(ip) if routed => ip.to_string(),
369 _ => format!(
370 "{}.{}.svc.cluster.local",
371 name(&svc),
372 Some(ns(&svc))
373 .filter(|n| !n.is_empty())
374 .unwrap_or(namespace)
375 ),
376 };
377 let port = first["port"].as_i64().unwrap_or(0);
378 let proto = first["protocol"].as_str().unwrap_or("TCP").to_lowercase();
379 out.push((format!("{n}_SERVICE_HOST"), host.clone()));
380 out.push((format!("{n}_SERVICE_PORT"), port.to_string()));
381 for p in &ports {
382 if let Some(pn) = p["name"].as_str().filter(|x| !x.is_empty()) {
383 out.push((
384 format!("{n}_SERVICE_PORT_{}", env_name(pn)),
385 p["port"].as_i64().unwrap_or(0).to_string(),
386 ));
387 }
388 }
389 out.push((format!("{n}_PORT"), format!("{proto}://{host}:{port}")));
390 for p in &ports {
391 let pp = p["port"].as_i64().unwrap_or(0);
392 let pr = p["protocol"].as_str().unwrap_or("TCP");
393 let base = format!("{n}_PORT_{pp}_{}", pr.to_uppercase());
394 out.push((base.clone(), format!("{}://{host}:{pp}", pr.to_lowercase())));
395 out.push((format!("{base}_PROTO"), pr.to_lowercase()));
396 out.push((format!("{base}_PORT"), pp.to_string()));
397 out.push((format!("{base}_ADDR"), host.clone()));
398 }
399 }
400 out
401}
402
403fn expand(v: &str, env: &[(String, String)]) -> String {
404 let mut out = String::with_capacity(v.len());
405 let mut rest = v;
406 while let Some(i) = rest.find("$(") {
407 out.push_str(&rest[..i]);
408 let tail = &rest[i + 2..];
409 match tail.find(')') {
410 Some(j) => {
411 let key = &tail[..j];
412 match env.iter().rev().find(|(k, _)| k == key) {
413 Some((_, val)) => out.push_str(val),
414 None => {
415 out.push_str("$(");
416 out.push_str(key);
417 out.push(')');
418 }
419 }
420 rest = &tail[j + 1..];
421 }
422 None => {
423 out.push_str(&rest[i..]);
424 rest = "";
425 }
426 }
427 }
428 out.push_str(rest);
429 out
430}
431
432fn field_ref(ctx: &Ctx, path: &str) -> Option<String> {
433 let p = ctx.pod;
434 let label = |prefix: &str, field: &str| -> Option<String> {
435 let k = path.strip_prefix(prefix)?.strip_suffix("']")?;
436 p["metadata"][field][k].as_str().map(str::to_string)
437 };
438 Some(match path {
439 "metadata.name" => name(p).to_string(),
440 "metadata.namespace" => ns(p).to_string(),
441 "metadata.uid" => uid(p).to_string(),
442 "spec.nodeName" => ctx.node.to_string(),
443 "spec.serviceAccountName" => s(p, "/spec/serviceAccountName").to_string(),
444 "status.podIP" | "status.podIPs" if ctx.pod_ip.is_empty() => {
445 krab_runtime::POD_IP_TOKEN.to_string()
446 }
447 "status.podIP" | "status.podIPs" => ctx.pod_ip.to_string(),
448 "status.hostIP" | "status.hostIPs" => ctx.host_ip.to_string(),
449 _ => {
450 return label("metadata.labels['", "labels")
451 .or_else(|| label("metadata.annotations['", "annotations"));
452 }
453 })
454}
455
456fn resource_ref(c: &Value, r: &Value) -> String {
457 let res = s(r, "/resource");
458 let (kind, what) = res.split_once('.').unwrap_or(("limits", res));
459 let mut val = c["resources"][kind][what]
460 .as_str()
461 .and_then(quantity)
462 .or_else(|| c["resources"]["limits"][what].as_str().and_then(quantity));
463 if val.is_none() && what == "cpu" {
464 val = std::thread::available_parallelism()
465 .ok()
466 .map(|n| n.get() as f64);
467 }
468 if val.is_none() && what == "memory" {
469 val = Some(krab_runtime::host::meminfo().0 as f64 * 1024.0);
470 }
471 let div = r["divisor"]
472 .as_str()
473 .and_then(quantity)
474 .filter(|d| *d > 0.0)
475 .unwrap_or(1.0);
476 format!("{}", (val.unwrap_or(0.0) / div).ceil() as i64)
477}
478
479pub fn build_env(ctx: &Ctx, c: &Value) -> Result<Vec<(String, String)>, String> {
480 let namespace = ns(ctx.pod);
481 let mut env: Vec<(String, String)> = Vec::new();
482 let set = |env: &mut Vec<(String, String)>, k: String, v: String| {
483 env.retain(|(x, _)| *x != k);
484 env.push((k, v));
485 };
486 if ctx.pod["spec"]["enableServiceLinks"].as_bool() != Some(false) {
487 for (k, v) in service_env(ctx.store, namespace) {
488 set(&mut env, k, v);
489 }
490 }
491 for ef in c["envFrom"].as_array().into_iter().flatten() {
492 let prefix = s(ef, "/prefix");
493 let (kind, r) = if ef["secretRef"].is_object() {
494 ("secrets", &ef["secretRef"])
495 } else {
496 ("configmaps", &ef["configMapRef"])
497 };
498 match data_of(ctx.store, kind, namespace, s(r, "/name")) {
499 Some(d) => {
500 for (k, v) in d {
501 set(
502 &mut env,
503 format!("{prefix}{k}"),
504 String::from_utf8_lossy(&v).into_owned(),
505 );
506 }
507 }
508 None if r["optional"].as_bool() == Some(true) => {}
509 None => return Err(format!("{kind} \"{}\" not found", s(r, "/name"))),
510 }
511 }
512 for e in c["env"].as_array().into_iter().flatten() {
513 let k = s(e, "/name").to_string();
514 let vf = &e["valueFrom"];
515 let val = if vf.is_object() {
516 let key_ref = |kind: &str, r: &Value| -> Result<Option<String>, String> {
517 let obj = s(r, "/name");
518 let key = s(r, "/key");
519 let opt = r["optional"].as_bool() == Some(true);
520 match data_of(ctx.store, kind, namespace, obj).and_then(|d| d.get(key).cloned()) {
521 Some(b) => Ok(Some(String::from_utf8_lossy(&b).into_owned())),
522 None if opt => Ok(None),
523 None => Err(format!(
524 "couldn't find key {key} in {kind} {namespace}/{obj}"
525 )),
526 }
527 };
528 if vf["configMapKeyRef"].is_object() {
529 key_ref("configmaps", &vf["configMapKeyRef"])?
530 } else if vf["secretKeyRef"].is_object() {
531 key_ref("secrets", &vf["secretKeyRef"])?
532 } else if vf["fieldRef"].is_object() {
533 Some(field_ref(ctx, s(vf, "/fieldRef/fieldPath")).unwrap_or_default())
534 } else if vf["resourceFieldRef"].is_object() {
535 let cname = s(vf, "/resourceFieldRef/containerName");
536 let target = if cname.is_empty() {
537 c
538 } else {
539 ctx.pod["spec"]["containers"]
540 .as_array()
541 .and_then(|a| a.iter().find(|x| x["name"] == cname))
542 .unwrap_or(c)
543 };
544 Some(resource_ref(target, &vf["resourceFieldRef"]))
545 } else {
546 None
547 }
548 } else {
549 Some(expand(s(e, "/value"), &env))
550 };
551 if let Some(v) = val {
552 set(&mut env, k, v);
553 }
554 }
555 Ok(env)
556}
557
558pub fn default_pull_policy(image: &str) -> &'static str {
559 let (_, tag) = krab_runtime::docker::split_image(image);
560 if tag == "latest" {
561 "Always"
562 } else {
563 "IfNotPresent"
564 }
565}
566
567fn seccomp_profile(pod: &Value, c: &Value) -> Result<Option<String>, String> {
568 let p = c
569 .pointer("/securityContext/seccompProfile")
570 .filter(|v| !v.is_null())
571 .or_else(|| {
572 pod.pointer("/spec/securityContext/seccompProfile")
573 .filter(|v| !v.is_null())
574 });
575 let Some(p) = p else {
576 return Ok(None);
577 };
578 match s(p, "/type") {
579 t @ ("Unconfined" | "RuntimeDefault") => Ok(Some(t.to_string())),
580 "Localhost" => {
581 if s(p, "/localhostProfile").is_empty() {
582 return Err("seccompProfile type Localhost requires localhostProfile".into());
583 }
584 Ok(Some("Localhost".to_string()))
585 }
586 t => Err(format!("unsupported seccompProfile type {t:?}")),
587 }
588}
589
590pub fn container_spec(
591 ctx: &Ctx,
592 c: &Value,
593 init: bool,
594 vols: &HashMap<String, VolSrc>,
595 network: &str,
596 aliases: Vec<String>,
597) -> Result<ContainerSpec, String> {
598 let pod = ctx.pod;
599 let env = build_env(ctx, c)?;
600 let strs = |v: &Value| -> Vec<String> {
601 v.as_array()
602 .map(|a| {
603 a.iter()
604 .filter_map(|x| x.as_str())
605 .map(|x| expand(x, &env))
606 .collect()
607 })
608 .unwrap_or_default()
609 };
610 let cname = s(c, "/name");
611 let mut labels = BTreeMap::new();
612 labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
613 labels.insert("krab.io/pod".into(), name(pod).into());
614 labels.insert("krab.io/namespace".into(), ns(pod).into());
615 labels.insert("krab.io/uid".into(), uid(pod).into());
616 labels.insert("krab.io/container".into(), cname.into());
617 labels.insert("krab.io/node".into(), ctx.node.into());
618 labels.insert(SPEC_HASH.into(), spec_hash(c));
619 if init {
620 labels.insert("krab.io/init".into(), "true".into());
621 }
622 let limit = |r: &str| c["resources"]["limits"][r].as_str().and_then(quantity);
623 let hostname = match s(pod, "/spec/hostname") {
624 "" => name(pod),
625 h => h,
626 };
627 let namespace = ns(pod);
628 let ports = c["ports"]
629 .as_array()
630 .into_iter()
631 .flatten()
632 .filter_map(|p| {
633 Some(PortSpec {
634 container_port: u16::try_from(p["containerPort"].as_u64()?).ok()?,
635 protocol: p["protocol"].as_str().unwrap_or("TCP").to_string(),
636 host_port: p["hostPort"].as_u64().and_then(|x| u16::try_from(x).ok()),
637 host_ip: p["hostIP"].as_str().map(str::to_string),
638 })
639 })
640 .collect();
641 let user = c["securityContext"]["runAsUser"]
642 .as_i64()
643 .or_else(|| pod["spec"]["securityContext"]["runAsUser"].as_i64())
644 .map(|u| u.to_string());
645 let seccomp = seccomp_profile(pod, c)?;
646 Ok(ContainerSpec {
647 name: container_name(namespace, name(pod), cname),
648 image: s(c, "/image").to_string(),
649 command: strs(&c["command"]),
650 args: strs(&c["args"]),
651 env: env.iter().map(|(k, v)| format!("{k}={v}")).collect(),
652 working_dir: c["workingDir"].as_str().map(str::to_string),
653 ports,
654 labels,
655 restart: if init {
656 RestartPolicy::Never
657 } else {
658 RestartPolicy::parse(s(pod, "/spec/restartPolicy"))
659 },
660 memory_bytes: limit("memory").map(|m| m as i64),
661 nano_cpus: limit("cpu").map(|c| (c * 1e9) as i64),
662 mounts: mounts_in(c, vols, ctx.subpaths)?,
663 hostname: Some(hostname.chars().take(63).collect()),
664 dns_search: vec![
665 format!("{namespace}.svc.cluster.local"),
666 "svc.cluster.local".into(),
667 "cluster.local".into(),
668 ],
669 dns_options: vec!["ndots:5".into()],
670 network: Some(network.to_string()),
671 aliases,
672 user,
673 tty: c["tty"].as_bool() == Some(true),
674 stdin: c["stdin"].as_bool() == Some(true),
675 allow_privilege_escalation: c["securityContext"]["allowPrivilegeEscalation"].as_bool()
676 == Some(true),
677 read_only_root: c["securityContext"]["readOnlyRootFilesystem"].as_bool() == Some(true),
678 seccomp,
679 })
680}
681
682#[cfg(test)]
683mod tests {
684 use super::*;
685 use serde_json::json;
686
687 #[test]
688 fn env_resolution() {
689 let st = MemStore::new(1 << 20, 16);
690 util::create(
691 &st,
692 "configmaps/default/cfg",
693 json!({"metadata": {"name": "cfg"}, "data": {"MODE": "prod", "X": "1"}}),
694 );
695 util::create(
696 &st,
697 "secrets/default/sec",
698 json!({"metadata": {"name": "sec"}, "data": {"PASS": "aHVudGVyMg=="}}),
699 );
700 util::create(
701 &st,
702 "services/default/my-db",
703 json!({"metadata": {"name": "my-db"}, "spec": {"ports": [{"name": "pg", "port": 5432}]}}),
704 );
705 let pod = json!({"metadata": {"name": "p", "namespace": "default", "uid": "u1", "labels": {"app": "a"}}, "spec": {}});
706 let c = json!({"name": "c", "resources": {"limits": {"memory": "64Mi", "cpu": "500m"}},
707 "envFrom": [{"configMapRef": {"name": "cfg"}, "prefix": "CFG_"}],
708 "env": [
709 {"name": "A", "value": "x"},
710 {"name": "B", "value": "$(A)-y"},
711 {"name": "MODE", "valueFrom": {"configMapKeyRef": {"name": "cfg", "key": "MODE"}}},
712 {"name": "PASS", "valueFrom": {"secretKeyRef": {"name": "sec", "key": "PASS"}}},
713 {"name": "POD", "valueFrom": {"fieldRef": {"fieldPath": "metadata.name"}}},
714 {"name": "APP", "valueFrom": {"fieldRef": {"fieldPath": "metadata.labels['app']"}}},
715 {"name": "IP", "valueFrom": {"fieldRef": {"fieldPath": "status.podIP"}}},
716 {"name": "MEM", "valueFrom": {"resourceFieldRef": {"resource": "limits.memory", "divisor": "1Mi"}}},
717 {"name": "CPU", "valueFrom": {"resourceFieldRef": {"resource": "limits.cpu", "divisor": "1m"}}}
718 ]});
719 let ctx = Ctx {
720 store: &st,
721 pod: &pod,
722 node: "n1",
723 pod_ip: "10.1.1.1",
724 host_ip: "",
725 subpaths: None,
726 };
727 let env: BTreeMap<String, String> = build_env(&ctx, &c).unwrap().into_iter().collect();
728 assert_eq!(env["CFG_MODE"], "prod");
729 assert_eq!(env["B"], "x-y");
730 assert_eq!(env["MODE"], "prod");
731 assert_eq!(env["PASS"], "hunter2");
732 assert_eq!(env["POD"], "p");
733 assert_eq!(env["APP"], "a");
734 assert_eq!(env["IP"], "10.1.1.1");
735 assert_eq!(env["MEM"], "64");
736 assert_eq!(env["CPU"], "500");
737 assert_eq!(env["MY_DB_SERVICE_HOST"], "my-db.default.svc.cluster.local");
738 assert_eq!(env["MY_DB_SERVICE_PORT"], "5432");
739 assert_eq!(env["MY_DB_SERVICE_PORT_PG"], "5432");
740 let bad = json!({"name": "c", "env": [{"name": "Z", "valueFrom": {"secretKeyRef": {"name": "nope", "key": "k"}}}]});
741 assert!(build_env(&ctx, &bad).is_err());
742 let spec = container_spec(&ctx, &c, false, &HashMap::new(), "krab", vec![]).unwrap();
743 assert_eq!(spec.name, "krab_default_p_c");
744 assert_eq!(spec.memory_bytes, Some(64 << 20));
745 assert_eq!(spec.nano_cpus, Some(500_000_000));
746 assert_eq!(spec.labels["krab.io/uid"], "u1");
747 assert_eq!(spec.labels[SPEC_HASH], spec_hash(&c));
748 let mut c2 = c.clone();
749 c2["image"] = json!("other:1");
750 assert_ne!(spec_hash(&c2), spec_hash(&c));
751 }
752
753 #[test]
754 fn seccomp_profile_resolution() {
755 let st = MemStore::new(1 << 20, 16);
756 let pod = |sc: Value| {
757 json!({"metadata": {"name": "p", "namespace": "default", "uid": "u1"},
758 "spec": {"securityContext": sc}})
759 };
760 let c = |sc: Value| json!({"name": "c", "securityContext": sc});
761 let build = |pod: &Value, c: &Value| {
762 let ctx = Ctx {
763 store: &st,
764 pod,
765 node: "n1",
766 pod_ip: "",
767 host_ip: "",
768 subpaths: None,
769 };
770 container_spec(&ctx, c, false, &HashMap::new(), "krab", vec![])
771 };
772 assert_eq!(build(&pod(json!({})), &c(json!({}))).unwrap().seccomp, None);
773 let p = pod(json!({"seccompProfile": {"type": "RuntimeDefault"}}));
774 assert_eq!(
775 build(&p, &c(json!({}))).unwrap().seccomp.as_deref(),
776 Some("RuntimeDefault")
777 );
778 assert_eq!(
779 build(&p, &c(json!({"seccompProfile": null})))
780 .unwrap()
781 .seccomp
782 .as_deref(),
783 Some("RuntimeDefault")
784 );
785 let over = c(json!({"seccompProfile": {"type": "Unconfined"}}));
786 assert_eq!(
787 build(&p, &over).unwrap().seccomp.as_deref(),
788 Some("Unconfined")
789 );
790 for bad in [
791 c(json!({"seccompProfile": {"type": "runtimeDefault"}})),
792 c(json!({"seccompProfile": {"type": "DockerDefault"}})),
793 c(json!({"seccompProfile": {}})),
794 c(json!({"seccompProfile": {"type": "Localhost"}})),
795 ] {
796 assert!(build(&pod(json!({})), &bad).is_err(), "{bad}");
797 }
798 let local =
799 c(json!({"seccompProfile": {"type": "Localhost", "localhostProfile": "x.json"}}));
800 assert_eq!(
801 build(&pod(json!({})), &local).unwrap().seccomp.as_deref(),
802 Some("Localhost")
803 );
804 }
805
806 #[test]
807 fn secret_volume_files() {
808 let st = MemStore::new(1 << 20, 16);
809 util::create(
810 &st,
811 "secrets/default/sec",
812 json!({"metadata": {"name": "sec"}, "data": {"token": "aHVudGVyMg=="}}),
813 );
814 util::create(
815 &st,
816 "configmaps/default/cfg",
817 json!({"metadata": {"name": "cfg"}, "data": {"a.conf": "x=1"}}),
818 );
819 let root = std::env::temp_dir().join(format!("krab-test-{}", util::rand_suffix(8)));
820 let pod = json!({"metadata": {"name": "p", "namespace": "default", "uid": "u2"}, "spec": {"volumes": [
821 {"name": "s", "secret": {"secretName": "sec"}},
822 {"name": "c", "configMap": {"name": "cfg", "items": [{"key": "a.conf", "path": "sub/app.conf"}]}},
823 {"name": "e", "emptyDir": {}},
824 {"name": "m", "emptyDir": {"medium": "Memory"}}
825 ]}});
826 let vols = prepare_volumes(&st, &pod, &root, &[]).unwrap();
827 let f = root.join("u2/s/token");
828 assert_eq!(fs::read(&f).unwrap(), b"hunter2");
829 #[cfg(unix)]
830 {
831 use std::os::unix::fs::PermissionsExt;
832 assert_eq!(
833 fs::metadata(&f).unwrap().permissions().mode() & 0o777,
834 0o400
835 );
836 }
837 assert_eq!(
838 fs::read_to_string(root.join("u2/c/sub/app.conf")).unwrap(),
839 "x=1"
840 );
841 let c = json!({"volumeMounts": [{"name": "s", "mountPath": "/s"}, {"name": "e", "mountPath": "/e"}, {"name": "m", "mountPath": "/m"}]});
842 let m = mounts(&c, &vols).unwrap();
843 assert!(matches!(&m[1], Mount::Volume { name, .. } if name == "krab_u2_e"));
844 assert!(matches!(&m[2], Mount::Tmpfs { .. }));
845 fs::remove_dir_all(&root).unwrap();
846 let missing = json!({"metadata": {"name": "p", "namespace": "default", "uid": "u3"}, "spec": {"volumes": [{"name": "s", "secret": {"secretName": "nope"}}]}});
847 assert!(prepare_volumes(&st, &missing, &root, &[]).is_err());
848 }
849
850 #[test]
851 fn pvc_volume_binds_provisioned_dir() {
852 let st = MemStore::new(1 << 20, 16);
853 let rec = util::Recorder::default();
854 let root = std::env::temp_dir().join(format!("krab-pvcvol-{}", util::rand_suffix(8)));
855 crate::pvc::ensure_default_class(&st);
856 let pod = |claim: &str, ro: bool| json!({"metadata": {"name": "p", "namespace": "default", "uid": "u9"}, "spec": {"volumes": [{"name": "d", "persistentVolumeClaim": {"claimName": claim, "readOnly": ro}}]}});
857 assert!(prepare_volumes(&st, &pod("data", false), &root, &[]).is_err());
858 util::create(
859 &st,
860 "persistentvolumeclaims/default/data",
861 json!({"metadata": {"name": "data", "namespace": "default"}, "spec": {"accessModes": ["ReadWriteOnce"], "resources": {"requests": {"storage": "1Gi"}}}, "status": {"phase": "Pending"}}),
862 );
863 assert!(prepare_volumes(&st, &pod("data", false), &root, &[]).is_err());
864 crate::pvc::sync_all(&st, &rec, &root);
865 let vols = prepare_volumes(&st, &pod("data", false), &root, &[]).unwrap();
866 let c = json!({"volumeMounts": [{"name": "d", "mountPath": "/data"}, {"name": "d", "mountPath": "/sub", "subPath": "a/b", "readOnly": true}]});
867 let m = mounts(&c, &vols).unwrap();
868 let claim = util::get(&st, "persistentvolumeclaims/default/data").unwrap();
869 let dir = fs::canonicalize(
870 root.join("pvc")
871 .join(format!("default_data_{}", uid(&claim))),
872 )
873 .unwrap();
874 assert!(
875 matches!(&m[0], Mount::Bind { src, read_only: false, .. } if Path::new(src) == dir)
876 );
877 assert!(
878 matches!(&m[1], Mount::Bind { src, read_only: true, .. } if Path::new(src) == dir.join("a/b"))
879 );
880 let bad = json!({"volumeMounts": [{"name": "d", "mountPath": "/x", "subPath": "../.."}]});
881 assert!(mounts(&bad, &vols).is_err());
882 let vols = prepare_volumes(&st, &pod("data", true), &root, &[]).unwrap();
883 assert!(matches!(
884 &mounts(&c, &vols).unwrap()[0],
885 Mount::Bind {
886 read_only: true,
887 ..
888 }
889 ));
890 util::update(
891 &st,
892 &format!("persistentvolumes/pvc-{}", uid(&claim)),
893 |pv| {
894 pv["spec"]["claimRef"]["uid"] = json!("other");
895 true
896 },
897 );
898 assert!(prepare_volumes(&st, &pod("data", false), &root, &[]).is_err());
899 fs::remove_dir_all(&root).unwrap();
900 }
901
902 #[test]
903 fn volume_paths_cannot_escape() {
904 let st = MemStore::new(1 << 20, 16);
905 let root = std::env::temp_dir().join(format!("krab-esc-{}", util::rand_suffix(8)));
906 let outside = root.join("outside");
907 fs::create_dir_all(&outside).unwrap();
908 util::create(
909 &st,
910 "configmaps/default/evil",
911 json!({"metadata": {"name": "evil"}, "data": {"/tmp/x": "pwn", "ok": "1"}}),
912 );
913 let pod = |uid: &str, vols: Value| json!({"metadata": {"name": "p", "namespace": "default", "uid": uid}, "spec": {"volumes": vols}});
914 let abs_key = pod("u1", json!([{"name": "c", "configMap": {"name": "evil"}}]));
915 assert!(prepare_volumes(&st, &abs_key, &root, &[]).is_err());
916 let abs_item = pod(
917 "u2",
918 json!([{"name": "c", "configMap": {"name": "evil", "items": [{"key": "ok", "path": outside.join("f").to_string_lossy()}]}}]),
919 );
920 assert!(prepare_volumes(&st, &abs_item, &root, &[]).is_err());
921 assert!(!outside.join("f").exists());
922 for bad in ["/", "../../etc", "a/b"] {
923 let p = pod("u3", json!([{"name": bad, "nfs": {}}]));
924 assert!(prepare_volumes(&st, &p, &root, &[]).is_err(), "{bad}");
925 }
926 let unknown = pod("u3", json!([{"name": "n", "nfs": {}}]));
927 assert!(prepare_volumes(&st, &unknown, &root, &[]).is_err());
928 let host = pod("u4", json!([{"name": "h", "hostPath": {"path": "/"}}]));
929 assert!(prepare_volumes(&st, &host, &root, &[]).is_err());
930 let sock = pod(
931 "u4",
932 json!([{"name": "h", "hostPath": {"path": "/var/run/docker.sock"}}]),
933 );
934 assert!(prepare_volumes(&st, &sock, &root, &[PathBuf::from("/")]).is_err());
935 let allowed = pod(
936 "u5",
937 json!([{"name": "h", "hostPath": {"path": outside.join("data").to_string_lossy()}}]),
938 );
939 let vols = prepare_volumes(&st, &allowed, &root, std::slice::from_ref(&outside)).unwrap();
940 assert!(outside.join("data").is_dir());
941 #[cfg(unix)]
942 std::os::unix::fs::symlink("/", outside.join("data/up")).unwrap();
943 for sub in ["/etc", "../x", "up"] {
944 let c = json!({"volumeMounts": [{"name": "h", "mountPath": "/m", "subPath": sub}]});
945 assert!(mounts(&c, &vols).is_err(), "{sub}");
946 }
947 let c = json!({"volumeMounts": [{"name": "h", "mountPath": "/m", "subPath": "inner"}]});
948 let m = mounts(&c, &vols).unwrap();
949 assert!(matches!(&m[0], Mount::Bind { src, .. } if src.ends_with("data/inner")));
950 let link_dir = root.join("u6/c");
951 fs::create_dir_all(&link_dir).unwrap();
952 #[cfg(unix)]
953 std::os::unix::fs::symlink(&outside, link_dir.join("sub")).unwrap();
954 util::create(
955 &st,
956 "configmaps/default/good",
957 json!({"metadata": {"name": "good"}, "data": {"a": "1"}}),
958 );
959 let linked = pod(
960 "u6",
961 json!([{"name": "c", "configMap": {"name": "good", "items": [{"key": "a", "path": "sub/a"}]}}]),
962 );
963 assert!(prepare_volumes(&st, &linked, &root, &[]).is_err());
964 assert!(!outside.join("a").exists());
965 let ro = pod("u7", json!([{"name": "c", "configMap": {"name": "good"}}]));
966 let vols = prepare_volumes(&st, &ro, &root, &[]).unwrap();
967 let c = json!({"volumeMounts": [{"name": "c", "mountPath": "/c"}]});
968 assert!(matches!(
969 &mounts(&c, &vols).unwrap()[0],
970 Mount::Bind {
971 read_only: true,
972 ..
973 }
974 ));
975 fs::remove_dir_all(&root).unwrap();
976 }
977
978 #[test]
979 fn subpath_on_emptydir_is_rejected() {
980 let mut vols = HashMap::new();
981 vols.insert("e".to_string(), VolSrc::Named("krab_x_e".into()));
982 let c = json!({"volumeMounts": [{"name": "e", "mountPath": "/m", "subPath": "s"}]});
983 let e = mounts(&c, &vols).unwrap_err();
984 assert!(e.contains("not supported for emptyDir"), "{e}");
985 let ok = json!({"volumeMounts": [{"name": "e", "mountPath": "/m"}]});
986 assert!(mounts(&ok, &vols).is_ok());
987 }
988
989 #[test]
990 fn resource_ref_treats_zero_divisor_as_one() {
991 let c = json!({"resources": {"limits": {"memory": "64Mi", "cpu": "250m"}}});
992 assert_eq!(
993 resource_ref(&c, &json!({"resource": "limits.memory", "divisor": "0"})),
994 "67108864"
995 );
996 assert_eq!(
997 resource_ref(&c, &json!({"resource": "limits.memory"})),
998 "67108864"
999 );
1000 assert_eq!(
1001 resource_ref(&c, &json!({"resource": "limits.cpu", "divisor": "1m"})),
1002 "250"
1003 );
1004 assert_eq!(
1005 resource_ref(&c, &json!({"resource": "limits.cpu", "divisor": "0"})),
1006 "1"
1007 );
1008 }
1009
1010 #[test]
1011 fn service_env_uses_cluster_ip_and_master_service() {
1012 let st = MemStore::new(1 << 20, 16);
1013 util::create(
1014 &st,
1015 "services/default/kubernetes",
1016 json!({"metadata": {"name": "kubernetes", "namespace": "default", "annotations": {"krab.io/routed-clusterip": "true"}}, "spec": {"clusterIP": "10.43.0.1", "ports": [{"name": "https", "port": 443}]}}),
1017 );
1018 util::create(
1019 &st,
1020 "services/work/db",
1021 json!({"metadata": {"name": "db", "namespace": "work"}, "spec": {"clusterIP": "None", "ports": [{"port": 5432}]}}),
1022 );
1023 let env: BTreeMap<String, String> = service_env(&st, "work").into_iter().collect();
1024 assert_eq!(env["KUBERNETES_SERVICE_HOST"], "10.43.0.1");
1025 assert_eq!(env["KUBERNETES_SERVICE_PORT"], "443");
1026 assert_eq!(env["KUBERNETES_SERVICE_PORT_HTTPS"], "443");
1027 assert_eq!(env["DB_SERVICE_HOST"], "db.work.svc.cluster.local");
1028 util::create(
1029 &st,
1030 "services/work/plain",
1031 json!({"metadata": {"name": "plain", "namespace": "work"}, "spec": {"clusterIP": "10.96.0.9", "ports": [{"port": 80}]}}),
1032 );
1033 let env: BTreeMap<String, String> = service_env(&st, "work").into_iter().collect();
1034 assert_eq!(env["PLAIN_SERVICE_HOST"], "plain.work.svc.cluster.local");
1035 let default: BTreeMap<String, String> = service_env(&st, "default").into_iter().collect();
1036 assert_eq!(
1037 default
1038 .keys()
1039 .filter(|k| k.starts_with("KUBERNETES_SERVICE_HOST"))
1040 .count(),
1041 1
1042 );
1043 }
1044}