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