Skip to main content

krab_api/
lib.rs

1mod body;
2mod defaults;
3mod discovery;
4mod gc;
5mod objects;
6pub mod objects_util;
7pub mod patch;
8mod proto;
9pub mod registry;
10mod select;
11mod spdy;
12mod status;
13mod stream;
14mod sync;
15mod table;
16mod util;
17mod write;
18
19use body::Body;
20use bytes::Bytes;
21use http_body_util::BodyExt;
22use hyper::body::Incoming;
23use hyper::{Method, Request, Response, StatusCode};
24use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
25use krab_runtime::host::{HostInfo, host_info, rss_kib};
26use krab_runtime::{ContainerInfo, LogOpts, Runtime, is_managed};
27use krab_store::WatchError;
28pub use krab_store::{MemStore, SyncMode};
29use krab_tls::sa::Signer;
30use krab_tls::tokens::StaticTokens;
31use krab_tls::{Identity, Pki, identity_from_peer};
32use registry::ResDef;
33use select::Selector;
34use serde_json::{Value, json};
35use status::ApiError;
36use std::collections::HashMap;
37use std::convert::Infallible;
38use std::io;
39use std::net::IpAddr;
40use std::path::PathBuf;
41use std::sync::{Arc, Mutex, PoisonError};
42use std::time::Duration;
43use tokio::net::TcpListener;
44use tokio::sync::mpsc;
45use util::now_secs;
46use write::{Opts, Sub};
47
48const MAX_BODY: usize = 3 << 20;
49const MAX_CONNS: usize = 128;
50const MAX_CONNS_PER_IP: u32 = 64;
51const MAX_WATCH_SECS: u64 = 3600;
52const HEADER_TIMEOUT: Duration = Duration::from_secs(30);
53
54pub struct Config {
55    pub listen: String,
56    pub token: Option<String>,
57    pub cgroup_root: String,
58    pub poll_interval: Duration,
59    pub watch_log_bytes: usize,
60    pub bookmark_interval: Duration,
61    pub allow_host_paths: Arc<Vec<PathBuf>>,
62}
63
64impl Default for Config {
65    fn default() -> Self {
66        Self {
67            listen: "127.0.0.1:6443".into(),
68            token: None,
69            cgroup_root: "/sys/fs/cgroup".into(),
70            poll_interval: Duration::from_secs(2),
71            watch_log_bytes: 512 * 1024,
72            bookmark_interval: Duration::from_secs(60),
73            allow_host_paths: Arc::default(),
74        }
75    }
76}
77
78pub struct Authn {
79    pub static_tokens: StaticTokens,
80    pub signer: Option<Signer>,
81}
82
83pub struct App<R> {
84    store: Arc<MemStore>,
85    rt: R,
86    host: HostInfo,
87    node_ip: String,
88    cfg: Config,
89    metrics: Mutex<sync::Metrics>,
90    auth: Option<Authn>,
91    conns: Mutex<HashMap<IpAddr, u32>>,
92}
93
94impl<R: Runtime> App<R> {
95    pub fn new(cfg: Config, rt: R, store: Arc<MemStore>) -> Arc<Self> {
96        App::with_auth(cfg, rt, store, None)
97    }
98
99    pub fn with_auth(cfg: Config, rt: R, store: Arc<MemStore>, auth: Option<Authn>) -> Arc<Self> {
100        let node_ip = std::env::var("KRAB_NODE_IP").unwrap_or_else(|_| "127.0.0.1".into());
101        sync::ensure_base_namespaces(&store);
102        Arc::new(App {
103            store,
104            rt,
105            host: host_info(),
106            node_ip,
107            cfg,
108            metrics: Mutex::new(sync::Metrics::default()),
109            auth,
110            conns: Mutex::new(HashMap::new()),
111        })
112    }
113
114    pub fn store(&self) -> Arc<MemStore> {
115        self.store.clone()
116    }
117}
118
119pub fn new_store(cfg: &Config) -> Arc<MemStore> {
120    MemStore::new(cfg.watch_log_bytes, 256)
121}
122
123#[derive(Default)]
124struct Query {
125    watch: bool,
126    rv: Option<u64>,
127    label: Selector,
128    field: Selector,
129    label_s: String,
130    field_s: String,
131    timeout: u64,
132    follow: bool,
133    tail: Option<usize>,
134    timestamps: bool,
135    since_seconds: Option<u64>,
136    limit: Option<usize>,
137    cont: Option<String>,
138    bookmarks: bool,
139    dry: bool,
140    manager: Option<String>,
141    force: bool,
142    propagation: Option<String>,
143    container: Option<String>,
144}
145
146fn hex_val(c: u8) -> Option<u8> {
147    (c as char).to_digit(16).map(|d| d as u8)
148}
149
150fn percent_decode(s: &str) -> String {
151    let b = s.as_bytes();
152    let mut out = Vec::with_capacity(b.len());
153    let mut i = 0;
154    while i < b.len() {
155        match b[i] {
156            b'%' if i + 2 < b.len() => {
157                if let (Some(h), Some(l)) = (hex_val(b[i + 1]), hex_val(b[i + 2])) {
158                    out.push(h << 4 | l);
159                    i += 3;
160                    continue;
161                }
162                out.push(b'%');
163                i += 1;
164            }
165            b'+' => {
166                out.push(b' ');
167                i += 1;
168            }
169            c => {
170                out.push(c);
171                i += 1;
172            }
173        }
174    }
175    String::from_utf8_lossy(&out).into_owned()
176}
177
178fn parse_query(q: Option<&str>) -> Query {
179    let mut out = Query {
180        timeout: 1800,
181        ..Default::default()
182    };
183    for pair in q.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
184        let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
185        let v = percent_decode(v);
186        match k {
187            "watch" => out.watch = v == "true" || v == "1",
188            "resourceVersion" => out.rv = v.parse().ok(),
189            "labelSelector" => {
190                out.label = Selector::parse(&v);
191                out.label_s = v;
192            }
193            "fieldSelector" => {
194                out.field = Selector::parse(&v);
195                out.field_s = v;
196            }
197            "timeoutSeconds" => out.timeout = v.parse().unwrap_or(1800).min(MAX_WATCH_SECS),
198            "follow" => out.follow = v == "true",
199            "tailLines" => out.tail = v.parse().ok(),
200            "timestamps" => out.timestamps = v == "true",
201            "sinceSeconds" => out.since_seconds = v.parse().ok(),
202            "limit" => out.limit = v.parse().ok().filter(|n| *n > 0),
203            "continue" => out.cont = Some(v).filter(|s| !s.is_empty()),
204            "allowWatchBookmarks" => out.bookmarks = v == "true" || v == "1",
205            "dryRun" => out.dry = v == "All",
206            "fieldManager" => out.manager = Some(v),
207            "force" => out.force = v == "true" || v == "1",
208            "propagationPolicy" => out.propagation = Some(v),
209            "container" => out.container = Some(v).filter(|c| !c.is_empty()),
210            _ => {}
211        }
212    }
213    out
214}
215
216impl Query {
217    fn opts(&self, allow_host: &Arc<Vec<PathBuf>>) -> Opts {
218        Opts {
219            dry: self.dry,
220            manager: self.manager.clone(),
221            force: self.force,
222            propagation: self.propagation.clone(),
223            allow_host: allow_host.clone(),
224        }
225    }
226}
227
228fn respond(status: StatusCode, ctype: &str, body: impl Into<Bytes>) -> Response<Body> {
229    Response::builder()
230        .status(status)
231        .header("Content-Type", ctype)
232        .body(Body::full(body))
233        .unwrap()
234}
235
236fn json_ok(v: &Value) -> Response<Body> {
237    respond(
238        StatusCode::OK,
239        "application/json",
240        serde_json::to_vec(v).unwrap(),
241    )
242}
243
244fn json_code(code: u16, b: Bytes) -> Response<Body> {
245    respond(
246        StatusCode::from_u16(code).unwrap_or(StatusCode::OK),
247        "application/json",
248        b,
249    )
250}
251
252fn error(e: ApiError) -> Response<Body> {
253    respond(
254        StatusCode::from_u16(e.code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
255        "application/json",
256        serde_json::to_vec(&e.to_json()).unwrap(),
257    )
258}
259
260fn failure(code: u16, reason: &'static str, message: &str) -> Response<Body> {
261    error(ApiError::new(code, reason, message))
262}
263
264fn not_found_kind(kind: &str, name: &str) -> Response<Body> {
265    let plural = kind.to_lowercase() + "s";
266    let mut e = ApiError::new(404, "NotFound", format!("{plural} \"{name}\" not found"));
267    e.details = json!({"name": name, "kind": plural});
268    error(e)
269}
270
271fn header<'a>(req: &'a Request<Incoming>, name: &str) -> &'a str {
272    req.headers()
273        .get(name)
274        .and_then(|v| v.to_str().ok())
275        .unwrap_or("")
276}
277
278pub async fn run<R: Runtime>(cfg: Config, rt: R) -> io::Result<()> {
279    let store = new_store(&cfg);
280    run_with_store(cfg, rt, store).await
281}
282
283pub async fn run_with_store<R: Runtime>(
284    cfg: Config,
285    rt: R,
286    store: Arc<MemStore>,
287) -> io::Result<()> {
288    let listener = TcpListener::bind(&cfg.listen).await?;
289    serve(App::new(cfg, rt, store), listener).await
290}
291
292struct ConnSlot<R: Runtime> {
293    app: Arc<App<R>>,
294    ip: IpAddr,
295}
296
297impl<R: Runtime> Drop for ConnSlot<R> {
298    fn drop(&mut self) {
299        let mut m = self
300            .app
301            .conns
302            .lock()
303            .unwrap_or_else(PoisonError::into_inner);
304        if let Some(n) = m.get_mut(&self.ip) {
305            *n -= 1;
306            if *n == 0 {
307                m.remove(&self.ip);
308            }
309        }
310    }
311}
312
313fn conn_slot<R: Runtime>(app: &Arc<App<R>>, ip: IpAddr) -> Option<ConnSlot<R>> {
314    let mut m = app.conns.lock().unwrap_or_else(PoisonError::into_inner);
315    let n = m.entry(ip).or_insert(0);
316    if *n >= MAX_CONNS_PER_IP {
317        return None;
318    }
319    *n += 1;
320    Some(ConnSlot {
321        app: app.clone(),
322        ip,
323    })
324}
325
326pub async fn serve<R: Runtime>(app: Arc<App<R>>, listener: TcpListener) -> io::Result<()> {
327    spawn_background(&app);
328    let permits = Arc::new(tokio::sync::Semaphore::new(MAX_CONNS));
329    loop {
330        let (stream, addr) = listener.accept().await?;
331        let Ok(permit) = permits.clone().try_acquire_owned() else {
332            continue;
333        };
334        let Some(slot) = conn_slot(&app, addr.ip()) else {
335            continue;
336        };
337        let app = app.clone();
338        tokio::spawn(async move {
339            let _permit = permit;
340            let _slot = slot;
341            serve_conn(app, stream, None).await;
342        });
343    }
344}
345
346pub async fn serve_tls<R: Runtime>(
347    app: Arc<App<R>>,
348    listener: TcpListener,
349    pki: &Pki,
350) -> io::Result<()> {
351    let acceptor = krab_tls::tls::acceptor(pki).map_err(|e| io::Error::other(e.to_string()))?;
352    spawn_background(&app);
353    let permits = Arc::new(tokio::sync::Semaphore::new(MAX_CONNS));
354    loop {
355        let (stream, addr) = listener.accept().await?;
356        let Ok(permit) = permits.clone().try_acquire_owned() else {
357            continue;
358        };
359        let Some(slot) = conn_slot(&app, addr.ip()) else {
360            continue;
361        };
362        let app = app.clone();
363        let acceptor = acceptor.clone();
364        tokio::spawn(async move {
365            let _permit = permit;
366            let _slot = slot;
367            let Ok(Ok(tls)) =
368                tokio::time::timeout(Duration::from_secs(10), acceptor.accept(stream)).await
369            else {
370                return;
371            };
372            let peer = identity_from_peer(tls.get_ref().1);
373            serve_conn(app, tls, peer).await;
374        });
375    }
376}
377
378fn spawn_background<R: Runtime>(app: &Arc<App<R>>) {
379    tokio::spawn(sync::run(app.clone()));
380    tokio::spawn(gc::run(app.store.clone()));
381}
382
383async fn serve_conn<R, S>(app: Arc<App<R>>, stream: S, peer: Option<Identity>)
384where
385    R: Runtime,
386    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
387{
388    let svc = hyper::service::service_fn(move |req| {
389        let app = app.clone();
390        let peer = peer.clone();
391        async move { Ok::<_, Infallible>(handle(app, req, peer).await) }
392    });
393    let mut b = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
394    b.http1()
395        .timer(TokioTimer::new())
396        .header_read_timeout(HEADER_TIMEOUT);
397    b.http2()
398        .timer(TokioTimer::new())
399        .max_concurrent_streams(64)
400        .keep_alive_interval(Duration::from_secs(60))
401        .keep_alive_timeout(Duration::from_secs(20));
402    let _ = b
403        .serve_connection_with_upgrades(TokioIo::new(stream), svc)
404        .await;
405}
406
407fn bearer(req: &Request<Incoming>) -> Option<&str> {
408    req.headers()
409        .get("authorization")
410        .and_then(|v| v.to_str().ok())
411        .and_then(|v| v.strip_prefix("Bearer "))
412}
413
414fn is_admin(id: &Identity) -> bool {
415    id.groups.iter().any(|g| g == "system:masters")
416}
417
418fn public_path(p: &str) -> bool {
419    matches!(p, "/healthz" | "/livez" | "/readyz" | "/version")
420        || p.starts_with("/healthz/")
421        || p.starts_with("/livez/")
422        || p.starts_with("/readyz/")
423}
424
425fn authenticate<R>(app: &App<R>, req: &Request<Incoming>, peer: Option<&Identity>) -> Option<bool> {
426    if app.auth.is_some()
427        && let Some(id) = peer
428    {
429        return Some(is_admin(id));
430    }
431    if let Some(t) = &app.cfg.token {
432        return bearer(req)
433            .is_some_and(|b| krab_tls::tokens::ct_eq(b.as_bytes(), t.as_bytes()))
434            .then_some(true);
435    }
436    if let Some(auth) = &app.auth {
437        let b = bearer(req)?;
438        if let Some(id) = auth.static_tokens.authenticate(b) {
439            return Some(is_admin(&id));
440        }
441        if let Some(c) = auth.signer.as_ref().and_then(|s| s.verify(b).ok()) {
442            return Some(is_admin(&c.identity()));
443        }
444        return None;
445    }
446    Some(true)
447}
448
449const PRIVILEGED_SUBS: [&str; 5] = ["log", "exec", "attach", "portforward", "proxy"];
450
451fn reader_allowed(verb: &str, resource: &str, sub: &str) -> bool {
452    matches!(verb, "get" | "list" | "watch")
453        && resource != "secrets"
454        && !PRIVILEGED_SUBS.contains(&sub)
455}
456
457fn reader_request_allowed(req: &Request<Incoming>, segs: &[&str]) -> bool {
458    if req.method() == Method::POST
459        && segs
460            == [
461                "apis",
462                "authorization.k8s.io",
463                "v1",
464                "selfsubjectaccessreviews",
465            ]
466    {
467        return true;
468    }
469    (req.method() == Method::GET || req.method() == Method::HEAD)
470        && !segs.contains(&"secrets")
471        && !segs.last().is_some_and(|s| PRIVILEGED_SUBS.contains(s))
472}
473
474fn discovery_response(accept: &str, legacy: bool, fallback: Value) -> Response<Body> {
475    let mut r = match discovery::aggregated_version(accept) {
476        Some(v) => respond(
477            StatusCode::OK,
478            &discovery::content_type(v),
479            serde_json::to_vec(&discovery::aggregated(legacy, v)).unwrap(),
480        ),
481        None => json_ok(&fallback),
482    };
483    r.headers_mut()
484        .insert("Vary", hyper::header::HeaderValue::from_static("Accept"));
485    r
486}
487
488fn opt_json(v: Option<Value>) -> Response<Body> {
489    match v {
490        Some(v) => json_ok(&v),
491        None => error(ApiError::not_found_path()),
492    }
493}
494
495async fn handle<R: Runtime>(
496    app: Arc<App<R>>,
497    req: Request<Incoming>,
498    peer: Option<Identity>,
499) -> Response<Body> {
500    let admin = if public_path(req.uri().path()) {
501        true
502    } else {
503        match authenticate(&app, &req, peer.as_ref()) {
504            Some(a) => a,
505            None => return failure(401, "Unauthorized", "Unauthorized"),
506        }
507    };
508    let path = req.uri().path().trim_end_matches('/').to_string();
509    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
510    if !admin && !reader_request_allowed(&req, &segs) {
511        return failure(
512            403,
513            "Forbidden",
514            "forbidden: only members of system:masters may modify objects, read secrets or use log, exec, attach and portforward",
515        );
516    }
517    let q = parse_query(req.uri().query());
518    let accept = header(&req, "accept").to_string();
519    let table = accept.contains("as=Table");
520    let get = req.method() == Method::GET || req.method() == Method::HEAD;
521    match segs.as_slice() {
522        ["api", "v1", rest @ ..] if !rest.is_empty() => {
523            resource(&app, req, "", "v1", rest, &q, table).await
524        }
525        ["apis", "metrics.k8s.io", "v1beta1", rest @ ..] if !rest.is_empty() => {
526            if get {
527                metrics_api(&app, rest, &q)
528            } else {
529                error(ApiError::method_not_allowed())
530            }
531        }
532        [
533            "apis",
534            "authorization.k8s.io",
535            "v1",
536            "selfsubjectaccessreviews",
537        ] => {
538            if req.method() == Method::POST {
539                ssar(req, admin).await
540            } else {
541                error(ApiError::method_not_allowed())
542            }
543        }
544        ["apis", g, v, rest @ ..] if !rest.is_empty() => {
545            let (g, v) = (g.to_string(), v.to_string());
546            resource(&app, req, &g, &v, rest, &q, table).await
547        }
548        _ if !get => error(ApiError::method_not_allowed()),
549        [] => json_ok(
550            &json!({"paths": ["/api", "/api/v1", "/apis", "/healthz", "/livez", "/readyz", "/version", "/metrics", "/openapi/v3"]}),
551        ),
552        ["healthz" | "livez" | "readyz", ..] => respond(StatusCode::OK, "text/plain", "ok"),
553        ["version"] => json_ok(
554            &json!({"major": "1", "minor": "34", "gitVersion": objects::VERSION, "gitCommit": "krab", "gitTreeState": "clean", "buildDate": "2026-11-30T00:00:00Z", "goVersion": "rust", "compiler": "rustc", "platform": format!("linux/{}", app.host.arch)}),
555        ),
556        ["metrics"] => prometheus(&app),
557        ["openapi", "v3"] => json_ok(&discovery::openapi_index()),
558        ["openapi", "v3", "api", "v1"] => opt_json(discovery::openapi_doc("", "v1")),
559        ["openapi", "v3", "apis", g, v] => opt_json(discovery::openapi_doc(g, v)),
560        ["openapi", "v2"] | ["swagger.json"] => json_ok(
561            &json!({"swagger": "2.0", "info": {"title": "krab", "version": objects::VERSION}, "paths": {}}),
562        ),
563        ["api"] => discovery_response(
564            &accept,
565            true,
566            json!({"kind": "APIVersions", "versions": ["v1"], "serverAddressByClientCIDRs": [{"clientCIDR": "0.0.0.0/0", "serverAddress": ""}]}),
567        ),
568        ["apis"] => discovery_response(&accept, false, discovery::api_group_list()),
569        ["api", "v1"] => opt_json(discovery::resource_list("", "v1")),
570        ["apis", g] => opt_json(discovery::api_group(g)),
571        ["apis", g, v] => opt_json(discovery::resource_list(g, v)),
572        _ => error(ApiError::not_found_path()),
573    }
574}
575
576async fn read_body(req: Request<Incoming>) -> Result<Bytes, ApiError> {
577    match http_body_util::Limited::new(req.into_body(), MAX_BODY)
578        .collect()
579        .await
580    {
581        Ok(b) => Ok(b.to_bytes()),
582        Err(e) if e.is::<http_body_util::LengthLimitError>() => Err(ApiError::new(
583            413,
584            "RequestEntityTooLarge",
585            "Request entity too large: limit is 3145728",
586        )),
587        Err(_) => Err(ApiError::bad_request("unreadable body")),
588    }
589}
590
591async fn ssar(req: Request<Incoming>, admin: bool) -> Response<Body> {
592    let bytes = match read_body(req).await {
593        Ok(b) => b,
594        Err(e) => return error(e),
595    };
596    let mut v: Value = serde_json::from_slice(&bytes)
597        .ok()
598        .filter(Value::is_object)
599        .unwrap_or_else(|| json!({}));
600    let attr = |k: &str| -> String {
601        v.pointer(&format!("/spec/resourceAttributes/{k}"))
602            .or_else(|| v.pointer(&format!("/spec/nonResourceAttributes/{k}")))
603            .and_then(Value::as_str)
604            .unwrap_or("")
605            .to_string()
606    };
607    let allowed = admin || reader_allowed(&attr("verb"), &attr("resource"), &attr("subresource"));
608    let reason = if admin {
609        "system:masters may perform any action"
610    } else if allowed {
611        "authenticated users may read non-secret objects"
612    } else {
613        "only system:masters may perform this action"
614    };
615    v["apiVersion"] = json!("authorization.k8s.io/v1");
616    v["kind"] = json!("SelfSubjectAccessReview");
617    v["status"] = json!({"allowed": allowed, "reason": reason});
618    respond(
619        StatusCode::CREATED,
620        "application/json",
621        serde_json::to_vec(&v).unwrap(),
622    )
623}
624
625fn parse_body(ctype: &str, b: &[u8]) -> Result<Value, ApiError> {
626    if ctype.contains("protobuf") {
627        return proto::decode(b).map_err(ApiError::unsupported_media);
628    }
629    if !ctype.is_empty() && !ctype.contains("json") && !ctype.contains("yaml") {
630        return Err(ApiError::unsupported_media(format!(
631            "the body of the request was in an unknown format - accepted media types include: application/json, application/yaml, application/vnd.kubernetes.protobuf (got {ctype})"
632        )));
633    }
634    write::parse_json(b)
635}
636
637struct Target {
638    def: &'static ResDef,
639    ns: Option<String>,
640    name: Option<String>,
641    sub: Option<String>,
642}
643
644fn target(group: &str, version: &str, rest: &[&str]) -> Result<Target, ApiError> {
645    let (ns, rest) = if rest.len() >= 3
646        && rest[0] == "namespaces"
647        && !(rest.len() == 3 && matches!(rest[2], "status" | "finalize"))
648    {
649        (Some(rest[1].to_string()), &rest[2..])
650    } else {
651        (None, rest)
652    };
653    let (plural, name, sub) = match rest {
654        [p] => (*p, None, None),
655        [p, n] => (*p, Some(n.to_string()), None),
656        [p, n, s] => (*p, Some(n.to_string()), Some(s.to_string())),
657        _ => return Err(ApiError::not_found_path()),
658    };
659    let def = registry::find(group, version, plural)
660        .filter(|d| d.stored)
661        .ok_or_else(ApiError::not_found_path)?;
662    if (ns.is_some() && !def.namespaced) || (ns.is_none() && def.namespaced && name.is_some()) {
663        return Err(ApiError::not_found_path());
664    }
665    if sub.as_deref().is_some_and(|s| !def.has_sub(s)) {
666        return Err(ApiError::not_found_path());
667    }
668    Ok(Target { def, ns, name, sub })
669}
670
671async fn resource<R: Runtime>(
672    app: &Arc<App<R>>,
673    req: Request<Incoming>,
674    group: &str,
675    version: &str,
676    rest: &[&str],
677    q: &Query,
678    table: bool,
679) -> Response<Body> {
680    let t = match target(group, version, rest) {
681        Ok(t) => t,
682        Err(e) => return error(e),
683    };
684    let def = t.def;
685    let ns = t.ns.as_deref();
686    let sub = t.sub.as_deref();
687    let method = req.method().clone();
688    let ctype = header(&req, "content-type").to_string();
689    let deny = || error(ApiError::method_not_allowed());
690    let store = &app.store;
691    if t.name.is_some()
692        && sub.is_some_and(|s| matches!(s, "exec" | "attach" | "portforward"))
693        && (method == Method::GET || method == Method::POST)
694    {
695        let ns = ns.unwrap_or("default");
696        let name = t.name.as_deref().unwrap();
697        if header(&req, "upgrade").is_empty() {
698            return failure(
699                400,
700                "BadRequest",
701                &format!("{} requires an upgrade request", sub.unwrap()),
702            );
703        }
704        return stream::handle(app.clone(), req, ns, name, sub.unwrap()).await;
705    }
706    let out = match (&method, t.name.as_deref(), sub) {
707        (&Method::GET | &Method::HEAD, None, None) => {
708            if !def.can(if q.watch { "watch" } else { "list" }) {
709                return deny();
710            }
711            return list_or_watch(app, def, ns, q, table);
712        }
713        (&Method::GET | &Method::HEAD, Some(n), None | Some("status")) => {
714            return get_one(app, def, ns, n, table);
715        }
716        (&Method::GET, Some(n), Some("log")) => {
717            return pod_log(app, ns.unwrap_or(""), n, q).await;
718        }
719        (&Method::GET, Some(n), Some("scale")) => match store.get(&def.key(ns, n)) {
720            Some(b) => {
721                let v: Value = serde_json::from_slice(&b).unwrap_or(Value::Null);
722                return json_ok(&write::scale_view(&v));
723            }
724            None => Err(status::not_found(def, n)),
725        },
726        (&Method::POST, None, None) if def.can("create") => match read_body(req).await {
727            Ok(b) => parse_body(&ctype, &b)
728                .and_then(|v| write::create(store, def, ns, v, &q.opts(&app.cfg.allow_host_paths))),
729            Err(e) => Err(e),
730        },
731        (&Method::PUT, Some(n), None | Some("status") | Some("scale")) if def.can("update") => {
732            match read_body(req).await {
733                Ok(b) => parse_body(&ctype, &b).and_then(|v| {
734                    write::update(
735                        store,
736                        def,
737                        ns,
738                        n,
739                        Sub::from(sub),
740                        v,
741                        &q.opts(&app.cfg.allow_host_paths),
742                    )
743                }),
744                Err(e) => Err(e),
745            }
746        }
747        (&Method::PATCH, Some(n), None | Some("status") | Some("scale")) if def.can("patch") => {
748            match read_body(req).await {
749                Ok(b) => write::patch(
750                    store,
751                    def,
752                    ns,
753                    n,
754                    Sub::from(sub),
755                    &ctype,
756                    &b,
757                    &q.opts(&app.cfg.allow_host_paths),
758                ),
759                Err(e) => Err(e),
760            }
761        }
762        (&Method::DELETE, Some(n), None) if def.can("delete") => match read_body(req).await {
763            Ok(b) => {
764                let mut opts = q.opts(&app.cfg.allow_host_paths);
765                let pre = write::delete_opts(&b, &mut opts);
766                write::delete(store, def, ns, n, &opts, pre)
767            }
768            Err(e) => Err(e),
769        },
770        (&Method::DELETE, None, None) if def.can("deletecollection") => {
771            let mut opts = q.opts(&app.cfg.allow_host_paths);
772            if let Ok(b) = read_body(req).await {
773                write::delete_opts(&b, &mut opts);
774            }
775            return delete_collection(app, def, ns, q, &opts);
776        }
777        _ => return deny(),
778    };
779    match out {
780        Ok((code, b)) => json_code(code, b),
781        Err(e) => error(e),
782    }
783}
784
785fn get_one<R: Runtime>(
786    app: &Arc<App<R>>,
787    def: &ResDef,
788    ns: Option<&str>,
789    name: &str,
790    table: bool,
791) -> Response<Body> {
792    let Some(obj) = app.store.get(&def.key(ns, name)) else {
793        return error(status::not_found(def, name));
794    };
795    if !table {
796        return respond(StatusCode::OK, "application/json", obj);
797    }
798    let v: Value = serde_json::from_slice(&obj).unwrap_or(Value::Null);
799    let rv = v
800        .pointer("/metadata/resourceVersion")
801        .and_then(Value::as_str)
802        .unwrap_or("0")
803        .to_string();
804    json_ok(&table::table(def.kind, &rv, &[v], true))
805}
806
807fn keep(q: &Query, v: &Value) -> bool {
808    (q.label.is_empty() || q.label.matches_labels(v))
809        && (q.field.is_empty() || q.field.matches_fields(v))
810}
811
812fn hex_encode(s: &str) -> String {
813    s.bytes().map(|b| format!("{b:02x}")).collect()
814}
815
816fn hex_decode(s: &str) -> Option<String> {
817    if !s.len().is_multiple_of(2) {
818        return None;
819    }
820    let bytes: Option<Vec<u8>> = (0..s.len())
821        .step_by(2)
822        .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
823        .collect();
824    String::from_utf8(bytes?).ok()
825}
826
827fn delete_collection<R: Runtime>(
828    app: &Arc<App<R>>,
829    def: &'static ResDef,
830    ns: Option<&str>,
831    q: &Query,
832    opts: &Opts,
833) -> Response<Body> {
834    let snap = app.store.list(&def.prefix(ns));
835    let mut items = Vec::new();
836    for (_, b) in snap.items {
837        let Ok(v) = serde_json::from_slice::<Value>(&b) else {
838            continue;
839        };
840        if !keep(q, &v) || objects_util::is_docker(&v) {
841            continue;
842        }
843        let name = v
844            .pointer("/metadata/name")
845            .and_then(Value::as_str)
846            .unwrap_or("");
847        let ons = v.pointer("/metadata/namespace").and_then(Value::as_str);
848        if let Ok((_, d)) = write::delete(&app.store, def, ons, name, opts, (None, None))
849            && let Ok(dv) = serde_json::from_slice::<Value>(&d)
850        {
851            items.push(dv);
852        }
853    }
854    json_ok(
855        &json!({"kind": format!("{}List", def.kind), "apiVersion": def.api_version(), "metadata": {"resourceVersion": app.store.rev().to_string()}, "items": items}),
856    )
857}
858
859fn list_or_watch<R: Runtime>(
860    app: &Arc<App<R>>,
861    def: &'static ResDef,
862    ns: Option<&str>,
863    q: &Query,
864    table: bool,
865) -> Response<Body> {
866    let prefix = def.prefix(ns);
867    if q.watch {
868        return start_watch(app, def, prefix, q, table);
869    }
870    let snap = app.store.list(&prefix);
871    let after = q.cont.as_deref().and_then(hex_decode);
872    let filtered = !q.label.is_empty() || !q.field.is_empty();
873    let limit = q.limit.unwrap_or(usize::MAX);
874    let mut raw: Vec<&Bytes> = Vec::new();
875    let mut objs: Vec<Value> = Vec::new();
876    let mut last: Option<&str> = None;
877    let mut more = false;
878    for (k, b) in snap
879        .items
880        .iter()
881        .filter(|(k, _)| after.as_deref().is_none_or(|a| k.as_ref() > a))
882    {
883        let parsed = if filtered || table {
884            match serde_json::from_slice::<Value>(b) {
885                Ok(v) if keep(q, &v) => Some(v),
886                _ => continue,
887            }
888        } else {
889            None
890        };
891        if raw.len() + objs.len() == limit {
892            more = true;
893            break;
894        }
895        match parsed {
896            Some(v) => objs.push(v),
897            None => raw.push(b),
898        }
899        last = Some(k);
900    }
901    let cont = if more {
902        last.map(hex_encode).unwrap_or_default()
903    } else {
904        String::new()
905    };
906    let list_kind = format!("{}List", def.kind);
907    let av = def.api_version();
908    if table {
909        let mut t = table::table(def.kind, &snap.rev.to_string(), &objs, true);
910        if !cont.is_empty() {
911            t["metadata"]["continue"] = json!(cont);
912        }
913        return json_ok(&t);
914    }
915    let meta = if cont.is_empty() {
916        json!({"resourceVersion": snap.rev.to_string()})
917    } else {
918        json!({"resourceVersion": snap.rev.to_string(), "continue": cont})
919    };
920    if !filtered {
921        let mut out = Vec::with_capacity(raw.iter().map(|b| b.len() + 1).sum::<usize>() + 160);
922        out.extend_from_slice(
923            format!(
924                "{{\"kind\":\"{list_kind}\",\"apiVersion\":\"{av}\",\"metadata\":{meta},\"items\":["
925            )
926            .as_bytes(),
927        );
928        for (i, b) in raw.iter().enumerate() {
929            if i > 0 {
930                out.push(b',');
931            }
932            out.extend_from_slice(b);
933        }
934        out.extend_from_slice(b"]}");
935        return respond(StatusCode::OK, "application/json", out);
936    }
937    json_ok(&json!({"kind": list_kind, "apiVersion": av, "metadata": meta, "items": objs}))
938}
939
940fn start_watch<R: Runtime>(
941    app: &Arc<App<R>>,
942    def: &'static ResDef,
943    prefix: String,
944    q: &Query,
945    table: bool,
946) -> Response<Body> {
947    let w = match app.store.watch(&prefix, q.rv) {
948        Ok(w) => w,
949        Err(WatchError::Expired { oldest }) => {
950            let line = format!(
951                "{{\"type\":\"ERROR\",\"object\":{{\"kind\":\"Status\",\"apiVersion\":\"v1\",\"metadata\":{{}},\"status\":\"Failure\",\"message\":\"too old resource version: {} ({})\",\"reason\":\"Expired\",\"code\":410}}}}\n",
952                q.rv.unwrap_or(0),
953                oldest.saturating_sub(1)
954            );
955            return respond(StatusCode::OK, "application/json", line);
956        }
957    };
958    let (tx, rx) = mpsc::channel::<Bytes>(16);
959    let filter_needed = !q.label.is_empty() || !q.field.is_empty() || table;
960    let timeout = Duration::from_secs(q.timeout.max(1));
961    let (lbl, fld) = (q.label_s.clone(), q.field_s.clone());
962    let kind = def.kind;
963    let av = def.api_version();
964    let bookmarks = q.bookmarks;
965    let bm_every = app.cfg.bookmark_interval.max(Duration::from_millis(100));
966    tokio::spawn(async move {
967        let q = Query {
968            label: Selector::parse(&lbl),
969            field: Selector::parse(&fld),
970            ..Default::default()
971        };
972        let mut first = true;
973        let mut rxb = w.rx;
974        let last = w.last_rev;
975        let mut seen = last;
976        let send = |ev: krab_store::Event, first: bool| -> Option<Bytes> {
977            if !filter_needed {
978                let mut line = Vec::with_capacity(ev.obj.len() + 40);
979                line.extend_from_slice(
980                    format!("{{\"type\":\"{}\",\"object\":", ev.kind.as_str()).as_bytes(),
981                );
982                line.extend_from_slice(&ev.obj);
983                line.extend_from_slice(b"}\n");
984                return Some(Bytes::from(line));
985            }
986            let v: Value = serde_json::from_slice(&ev.obj).ok()?;
987            if !keep(&q, &v) {
988                return None;
989            }
990            let obj = if table {
991                table::table(kind, &ev.rev.to_string(), &[v], first)
992            } else {
993                v
994            };
995            let mut line =
996                serde_json::to_vec(&json!({"type": ev.kind.as_str(), "object": obj})).ok()?;
997            line.push(b'\n');
998            Some(Bytes::from(line))
999        };
1000        for ev in w.initial {
1001            if let Some(b) = send(ev, first) {
1002                first = false;
1003                if tx.send(b).await.is_err() {
1004                    return;
1005                }
1006            }
1007        }
1008        let deadline = tokio::time::sleep(timeout);
1009        tokio::pin!(deadline);
1010        let mut bm = tokio::time::interval_at(tokio::time::Instant::now() + bm_every, bm_every);
1011        loop {
1012            tokio::select! {
1013                _ = &mut deadline => break,
1014                _ = bm.tick(), if bookmarks => {
1015                    let line = format!("{{\"type\":\"BOOKMARK\",\"object\":{{\"kind\":\"{kind}\",\"apiVersion\":\"{av}\",\"metadata\":{{\"resourceVersion\":\"{seen}\"}}}}}}\n");
1016                    if tx.send(Bytes::from(line)).await.is_err() {
1017                        return;
1018                    }
1019                }
1020                got = rxb.recv() => match got {
1021                    Ok(ev) => {
1022                        if ev.rev <= last {
1023                            continue;
1024                        }
1025                        seen = ev.rev;
1026                        if !ev.key.starts_with(&prefix) {
1027                            continue;
1028                        }
1029                        if let Some(b) = send(ev, first) {
1030                            first = false;
1031                            if tx.send(b).await.is_err() {
1032                                return;
1033                            }
1034                        }
1035                    }
1036                    Err(_) => break,
1037                }
1038            }
1039        }
1040    });
1041    Response::builder()
1042        .status(StatusCode::OK)
1043        .header("Content-Type", "application/json")
1044        .body(Body::Chan(rx))
1045        .unwrap()
1046}
1047
1048async fn pod_log<R: Runtime>(app: &Arc<App<R>>, ns: &str, name: &str, q: &Query) -> Response<Body> {
1049    let Some(obj) = app.store.get(&format!("pods/{ns}/{name}")) else {
1050        return not_found_kind("Pod", name);
1051    };
1052    let v: Value = serde_json::from_slice(&obj).unwrap_or(Value::Null);
1053    let info = match pod_container(app, &v, q.container.as_deref()).await {
1054        Ok((info, _)) => info,
1055        Err(e) => return failure(400, "BadRequest", &e),
1056    };
1057    let opts = LogOpts {
1058        tail: q.tail,
1059        follow: q.follow,
1060        timestamps: q.timestamps,
1061        since_seconds: q.since_seconds,
1062    };
1063    match app.rt.logs(&info, &opts).await {
1064        Ok(rx) => Response::builder()
1065            .status(StatusCode::OK)
1066            .header("Content-Type", "text/plain")
1067            .body(Body::Chan(rx))
1068            .unwrap(),
1069        Err(e) => failure(500, "InternalError", &format!("log stream failed: {e}")),
1070    }
1071}
1072
1073fn docker_id_ok(id: &str) -> bool {
1074    (12..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_hexdigit())
1075}
1076
1077pub(crate) async fn pod_container<R: Runtime>(
1078    app: &App<R>,
1079    pod: &Value,
1080    want: Option<&str>,
1081) -> Result<(ContainerInfo, bool), String> {
1082    let name = pod
1083        .pointer("/metadata/name")
1084        .and_then(Value::as_str)
1085        .unwrap_or("");
1086    let not_running = || format!("container for pod \"{name}\" is not running");
1087    if objects_util::is_docker(pod) {
1088        let id = pod
1089            .pointer("/metadata/annotations/krab.io~1container-id")
1090            .and_then(Value::as_str)
1091            .filter(|id| docker_id_ok(id))
1092            .ok_or_else(not_running)?;
1093        let mut info = ContainerInfo {
1094            id: id.to_string(),
1095            ..Default::default()
1096        };
1097        app.rt.inspect(&mut info).await.map_err(|_| not_running())?;
1098        if is_managed(&info) || info.id != id {
1099            return Err(not_running());
1100        }
1101        return Ok((info, false));
1102    }
1103    let uid = pod
1104        .pointer("/metadata/uid")
1105        .and_then(Value::as_str)
1106        .unwrap_or("");
1107    let first = pod
1108        .pointer("/spec/containers/0/name")
1109        .and_then(Value::as_str)
1110        .unwrap_or("");
1111    let cname = want.unwrap_or(first);
1112    let list = app.rt.list().await.map_err(|e| e.to_string())?;
1113    let mut info = list
1114        .into_iter()
1115        .find(|c| {
1116            is_managed(c)
1117                && !uid.is_empty()
1118                && c.labels.get("krab.io/uid").map(String::as_str) == Some(uid)
1119                && c.labels.get("krab.io/container").map(String::as_str) == Some(cname)
1120        })
1121        .ok_or_else(not_running)?;
1122    app.rt.inspect(&mut info).await.map_err(|_| not_running())?;
1123    if !is_managed(&info) {
1124        return Err(not_running());
1125    }
1126    Ok((info, true))
1127}
1128
1129fn quantity_cpu(n: u64) -> String {
1130    format!("{n}n")
1131}
1132
1133fn metrics_api<R: Runtime>(app: &Arc<App<R>>, segs: &[&str], q: &Query) -> Response<Body> {
1134    let m = app.metrics.lock().unwrap_or_else(PoisonError::into_inner);
1135    let window = format!("{}s", m.window_secs.max(10));
1136    let ts = util::rfc3339(now_secs());
1137    let node_item = |_: ()| {
1138        m.node_cpu_nano.map(|cpu| json!({"kind": "NodeMetrics", "apiVersion": "metrics.k8s.io/v1beta1", "metadata": {"name": app.host.hostname, "creationTimestamp": ts, "labels": {"kubernetes.io/hostname": app.host.hostname}}, "timestamp": ts, "window": window, "usage": {"cpu": quantity_cpu(cpu), "memory": format!("{}Ki", m.node_mem_bytes / 1024)}}))
1139    };
1140    let pod_items = |ns: Option<&str>| -> Vec<Value> {
1141        let mut out = Vec::new();
1142        for (key, s) in &m.pods {
1143            let Some(cpu) = s.cpu_nano else { continue };
1144            let mut parts = key.splitn(3, '/');
1145            let (_, pns, pname) = (
1146                parts.next(),
1147                parts.next().unwrap_or(""),
1148                parts.next().unwrap_or(""),
1149            );
1150            if ns.is_some_and(|n| n != pns) {
1151                continue;
1152            }
1153            let item = json!({"kind": "PodMetrics", "apiVersion": "metrics.k8s.io/v1beta1", "metadata": {"name": pname, "namespace": pns, "creationTimestamp": ts}, "timestamp": ts, "window": window, "containers": [{"name": pname, "usage": {"cpu": quantity_cpu(cpu), "memory": format!("{}Ki", s.mem_bytes / 1024)}}]});
1154            if keep(q, &item) {
1155                out.push(item);
1156            }
1157        }
1158        out.sort_by(|a, b| {
1159            a["metadata"]["name"]
1160                .as_str()
1161                .cmp(&b["metadata"]["name"].as_str())
1162        });
1163        out
1164    };
1165    let list = |kind: &str, items: Vec<Value>| json!({"kind": kind, "apiVersion": "metrics.k8s.io/v1beta1", "metadata": {}, "items": items});
1166    match segs {
1167        ["nodes"] => json_ok(&list(
1168            "NodeMetricsList",
1169            node_item(()).into_iter().collect(),
1170        )),
1171        ["nodes", name] => match node_item(()) {
1172            Some(v) if *name == app.host.hostname => json_ok(&v),
1173            _ => not_found_kind("NodeMetrics", name),
1174        },
1175        ["pods"] => json_ok(&list("PodMetricsList", pod_items(None))),
1176        ["namespaces", ns, "pods"] => json_ok(&list("PodMetricsList", pod_items(Some(ns)))),
1177        ["namespaces", ns, "pods", name] => match pod_items(Some(ns))
1178            .into_iter()
1179            .find(|v| v["metadata"]["name"] == *name)
1180        {
1181            Some(v) => json_ok(&v),
1182            None => not_found_kind("PodMetrics", name),
1183        },
1184        _ => error(ApiError::not_found_path()),
1185    }
1186}
1187
1188fn prometheus<R: Runtime>(app: &Arc<App<R>>) -> Response<Body> {
1189    let pods = app.store.list("pods/").items.len();
1190    let out = format!(
1191        "# TYPE krab_process_resident_memory_bytes gauge\nkrab_process_resident_memory_bytes {}\n# TYPE krab_store_revision gauge\nkrab_store_revision {}\n# TYPE krab_store_watch_log_bytes gauge\nkrab_store_watch_log_bytes {}\n# TYPE krab_pods gauge\nkrab_pods {}\n# TYPE krab_build_info gauge\nkrab_build_info{{version=\"{}\"}} 1\n",
1192        rss_kib() * 1024,
1193        app.store.rev(),
1194        app.store.log_bytes(),
1195        pods,
1196        objects::VERSION
1197    );
1198    respond(StatusCode::OK, "text/plain; version=0.0.4", out)
1199}
1200
1201#[cfg(test)]
1202mod tests {
1203    use super::*;
1204
1205    #[test]
1206    fn percent_decode_is_byte_safe() {
1207        assert_eq!(percent_decode("%aé"), "%aé");
1208        assert_eq!(percent_decode("é%4"), "é%4");
1209        assert_eq!(percent_decode("%é%%41"), "%é%A");
1210        assert_eq!(percent_decode("a%20b+c"), "a b c");
1211        let q = parse_query(Some(
1212            "timeoutSeconds=999999999&labelSelector=%aé&container=c",
1213        ));
1214        assert_eq!(q.timeout, MAX_WATCH_SECS);
1215        assert_eq!(q.container.as_deref(), Some("c"));
1216    }
1217
1218    #[test]
1219    fn docker_ids_must_be_hex() {
1220        assert!(docker_id_ok("abcdef012345"));
1221        assert!(!docker_id_ok("victim/archive?path=/etc/shadow&"));
1222        assert!(!docker_id_ok("abc"));
1223    }
1224}