krab-agent 0.2.2

Lightweight kubelet for a real Kubernetes control plane (krab agent)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
use crate::client::Client;
use hyper::body::Incoming;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
use krab_api::kubelet_bridge::{self, Op};
use krab_api::{App, Body};
use krab_controllers::util::{self, s};
use krab_runtime::cgroup::container_usage;
use krab_runtime::host::{cpu_busy_ticks, meminfo};
use krab_runtime::{Runtime, is_managed};
use krab_store::MemStore;
use krab_tls::{Identity, b64, csr, der, identity_from_peer, tls};
use rustls_pki_types::CertificateDer;
use rustls_pki_types::pem::PemObject;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::net::TcpListener;
use tokio_rustls::TlsAcceptor;

const CACHE_TTL: Duration = Duration::from_secs(60);
const CACHE_MAX: usize = 256;
const REVIEWS: usize = 8;
const REVIEW_WAIT: Duration = Duration::from_secs(5);
const CGROUP_ROOT: &str = "/sys/fs/cgroup";

pub struct Opts {
    pub bind: SocketAddr,
    pub serving_dir: PathBuf,
    pub client_ca: Option<PathBuf>,
    pub node_name: String,
    pub node_ip: String,
}

struct Ctx<R> {
    app: Arc<App<R>>,
    rt: R,
    store: Arc<MemStore>,
    client: Arc<Client>,
    node: String,
    bind: SocketAddr,
    cache: Mutex<HashMap<String, (Instant, bool)>>,
    tokens: Mutex<HashMap<String, (Instant, Option<Identity>)>>,
    reviews: tokio::sync::Semaphore,
}

fn status(code: u16, reason: &str, msg: &str) -> Response<Body> {
    let body = json!({"apiVersion": "v1", "kind": "Status", "metadata": {}, "status": "Failure", "message": msg, "reason": reason, "code": code});
    Response::builder()
        .status(StatusCode::from_u16(code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR))
        .header("content-type", "application/json")
        .body(Body::full(body.to_string()))
        .unwrap()
}

fn reply(ctype: &str, body: String) -> Response<Body> {
    Response::builder()
        .status(StatusCode::OK)
        .header("content-type", ctype)
        .body(Body::full(body))
        .unwrap()
}

fn subresource(path: &str) -> &'static str {
    let first = path.trim_start_matches('/').split('/').next().unwrap_or("");
    match first {
        "stats" => "stats",
        "metrics" => "metrics",
        "logs" => "log",
        "spec" => "spec",
        "checkpoint" => "checkpoint",
        _ => "proxy",
    }
}

fn verb(m: &Method) -> &'static str {
    match *m {
        Method::GET | Method::HEAD => "get",
        Method::POST => "create",
        Method::PUT => "update",
        Method::PATCH => "patch",
        Method::DELETE => "delete",
        _ => "get",
    }
}

fn required_verb(path: &str, m: &Method) -> &'static str {
    match path.trim_start_matches('/').split('/').next().unwrap_or("") {
        "exec" | "attach" | "portForward" | "run" => "create",
        _ => verb(m),
    }
}

fn bearer(req: &Request<Incoming>) -> Option<String> {
    req.headers()
        .get("authorization")?
        .to_str()
        .ok()?
        .strip_prefix("Bearer ")
        .map(str::to_string)
}

fn bounded<V>(m: &mut HashMap<String, V>) {
    if m.len() >= CACHE_MAX {
        m.clear();
    }
}

impl<R: Runtime + Clone> Ctx<R> {
    async fn review_permit(&self) -> Option<tokio::sync::SemaphorePermit<'_>> {
        tokio::time::timeout(REVIEW_WAIT, self.reviews.acquire())
            .await
            .ok()?
            .ok()
    }

    async fn token_identity(&self, token: &str) -> Option<Identity> {
        if let Some((t, v)) = self
            .tokens
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(token)
            && t.elapsed() < CACHE_TTL
        {
            return v.clone();
        }
        let _permit = self.review_permit().await?;
        let body = json!({"apiVersion": "authentication.k8s.io/v1", "kind": "TokenReview", "spec": {"token": token}});
        let (code, out) = self
            .client
            .post("/apis/authentication.k8s.io/v1/tokenreviews", &body)
            .await
            .ok()?;
        if !matches!(code, 200 | 201) {
            return None;
        }
        let id = (out["status"]["authenticated"] == true).then(|| Identity {
            user: s(&out, "/status/user/username").to_string(),
            groups: out["status"]["user"]["groups"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(|g| g.as_str().map(str::to_string))
                .collect(),
        });
        let mut m = self.tokens.lock().unwrap_or_else(|e| e.into_inner());
        bounded(&mut m);
        m.insert(token.to_string(), (Instant::now(), id.clone()));
        id
    }

    async fn allowed(&self, id: &Identity, verb: &str, sub: &str) -> bool {
        if id.groups.iter().any(|g| g == "system:masters") {
            return true;
        }
        let key = format!("{}|{}|{verb}|{sub}", id.user, id.groups.join(","));
        if let Some((t, v)) = self
            .cache
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(&key)
            && t.elapsed() < CACHE_TTL
        {
            return *v;
        }
        let Some(_permit) = self.review_permit().await else {
            return false;
        };
        let body = json!({"apiVersion": "authorization.k8s.io/v1", "kind": "SubjectAccessReview", "spec": {
            "user": id.user,
            "groups": id.groups,
            "resourceAttributes": {"verb": verb, "version": "v1", "resource": "nodes", "subresource": sub, "name": self.node}
        }});
        let ok = match self
            .client
            .post("/apis/authorization.k8s.io/v1/subjectaccessreviews", &body)
            .await
        {
            Ok((200 | 201, out)) => out["status"]["allowed"] == true,
            _ => return false,
        };
        let mut m = self.cache.lock().unwrap_or_else(|e| e.into_inner());
        bounded(&mut m);
        m.insert(key, (Instant::now(), ok));
        ok
    }
}

async fn handle<R: Runtime + Clone>(
    cx: Arc<Ctx<R>>,
    req: Request<Incoming>,
    peer: Option<Identity>,
) -> Response<Body> {
    let path = req.uri().path().trim_end_matches('/').to_string();
    if path == "/healthz" {
        return reply("text/plain", "ok".into());
    }
    let id = match peer {
        Some(id) => id,
        None => match bearer(&req) {
            Some(t) => match cx.token_identity(&t).await {
                Some(id) => id,
                None => return status(401, "Unauthorized", "Unauthorized"),
            },
            None => return status(401, "Unauthorized", "Unauthorized"),
        },
    };
    let sub = subresource(&path);
    let v = required_verb(&path, req.method());
    if !cx.allowed(&id, v, sub).await {
        return status(
            403,
            "Forbidden",
            &format!("user {} cannot {v} nodes/{sub}", id.user),
        );
    }
    let segs: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect();
    match (req.method().clone(), segs.as_slice()) {
        (Method::GET, ["containerLogs", n, p, c]) => {
            kubelet_bridge::handle(&cx.app, req, n, p, Some(c), Op::Logs).await
        }
        (Method::GET | Method::POST, [op @ ("exec" | "attach"), n, p, c])
        | (Method::GET | Method::POST, [op @ ("exec" | "attach"), n, p, _, c]) => {
            let op = if *op == "exec" { Op::Exec } else { Op::Attach };
            kubelet_bridge::handle(&cx.app, req, n, p, Some(c), op).await
        }
        (Method::GET | Method::POST, ["portForward", n, p])
        | (Method::GET | Method::POST, ["portForward", n, p, _]) => {
            kubelet_bridge::handle(&cx.app, req, n, p, None, Op::PortForward).await
        }
        (Method::GET, ["metrics", "resource"]) => {
            reply("text/plain; version=0.0.4", resource_metrics(&cx).await)
        }
        (Method::GET, ["configz"]) => reply(
            "application/json",
            json!({"kubeletconfig": {
                "apiVersion": "kubelet.config.k8s.io/v1beta1",
                "kind": "KubeletConfiguration",
                "address": cx.bind.ip().to_string(),
                "port": cx.bind.port(),
                "readOnlyPort": 0,
                "authentication": {"anonymous": {"enabled": false}, "webhook": {"enabled": true}},
                "authorization": {"mode": "Webhook"}
            }})
            .to_string(),
        ),
        (Method::GET, ["stats", "summary"]) => {
            reply("application/json", stats_summary(&cx).await.to_string())
        }
        (Method::GET, ["pods"]) => {
            let items: Vec<Value> = util::list(&cx.store, "pods/")
                .into_iter()
                .map(|(_, p)| p)
                .collect();
            reply(
                "application/json",
                json!({"apiVersion": "v1", "kind": "PodList", "items": items}).to_string(),
            )
        }
        _ => status(404, "NotFound", "page not found"),
    }
}

struct Sample {
    ns: String,
    pod: String,
    uid: String,
    container: String,
    cpu_usec: u64,
    mem: u64,
    started: i64,
}

async fn samples<R: Runtime + Clone>(cx: &Ctx<R>) -> Vec<Sample> {
    let Ok(list) = cx.rt.list().await else {
        return Vec::new();
    };
    let node = Some(&cx.node);
    list.into_iter()
        .filter(|c| is_managed(c) && c.state == "running" && c.labels.get("krab.io/node") == node)
        .filter_map(|c| {
            let u = container_usage(CGROUP_ROOT, &c.id)?;
            let l = |k: &str| c.labels.get(k).cloned().unwrap_or_default();
            Some(Sample {
                ns: l("krab.io/namespace"),
                pod: l("krab.io/pod"),
                uid: l("krab.io/uid"),
                container: l("krab.io/container"),
                cpu_usec: u.cpu_usec,
                mem: u.mem_bytes,
                started: util::parse_rfc3339(&c.started_at).unwrap_or(0),
            })
        })
        .collect()
}

fn node_usage() -> (f64, u64) {
    let cpu = cpu_busy_ticks().unwrap_or(0) as f64 / 100.0;
    let (total, avail) = meminfo();
    (cpu, total.saturating_sub(avail) * 1024)
}

fn esc(v: &str) -> String {
    v.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
}

async fn resource_metrics<R: Runtime + Clone>(cx: &Ctx<R>) -> String {
    let ts = util::now_secs() * 1000;
    let (cpu, mem) = node_usage();
    let mut out = format!(
        "# TYPE node_cpu_usage_seconds_total counter\nnode_cpu_usage_seconds_total {cpu} {ts}\n# TYPE node_memory_working_set_bytes gauge\nnode_memory_working_set_bytes {mem} {ts}\n"
    );
    let list = samples(cx).await;
    let mut pods: HashMap<(String, String), (u64, u64)> = HashMap::new();
    out.push_str("# TYPE container_cpu_usage_seconds_total counter\n");
    for c in &list {
        out.push_str(&format!(
            "container_cpu_usage_seconds_total{{container=\"{}\",namespace=\"{}\",pod=\"{}\"}} {} {ts}\n",
            esc(&c.container),
            esc(&c.ns),
            esc(&c.pod),
            c.cpu_usec as f64 / 1e6
        ));
        let e = pods.entry((c.ns.clone(), c.pod.clone())).or_default();
        e.0 += c.cpu_usec;
        e.1 += c.mem;
    }
    out.push_str("# TYPE container_memory_working_set_bytes gauge\n");
    for c in &list {
        out.push_str(&format!(
            "container_memory_working_set_bytes{{container=\"{}\",namespace=\"{}\",pod=\"{}\"}} {} {ts}\n",
            esc(&c.container),
            esc(&c.ns),
            esc(&c.pod),
            c.mem
        ));
    }
    out.push_str("# TYPE container_start_time_seconds gauge\n");
    for c in &list {
        out.push_str(&format!(
            "container_start_time_seconds{{container=\"{}\",namespace=\"{}\",pod=\"{}\"}} {}\n",
            esc(&c.container),
            esc(&c.ns),
            esc(&c.pod),
            c.started
        ));
    }
    out.push_str("# TYPE pod_cpu_usage_seconds_total counter\n");
    for ((n, p), (cpu, _)) in &pods {
        out.push_str(&format!(
            "pod_cpu_usage_seconds_total{{namespace=\"{}\",pod=\"{}\"}} {} {ts}\n",
            esc(n),
            esc(p),
            *cpu as f64 / 1e6
        ));
    }
    out.push_str("# TYPE pod_memory_working_set_bytes gauge\n");
    for ((n, p), (_, mem)) in &pods {
        out.push_str(&format!(
            "pod_memory_working_set_bytes{{namespace=\"{}\",pod=\"{}\"}} {mem} {ts}\n",
            esc(n),
            esc(p)
        ));
    }
    out.push_str("# TYPE scrape_error gauge\nscrape_error 0\n");
    out
}

async fn stats_summary<R: Runtime + Clone>(cx: &Ctx<R>) -> Value {
    let time = util::now_rfc();
    let (cpu, mem) = node_usage();
    let mut pods: HashMap<(String, String, String), Vec<Value>> = HashMap::new();
    for c in samples(cx).await {
        pods.entry((c.ns, c.pod, c.uid)).or_default().push(json!({
            "name": c.container,
            "startTime": util::rfc3339(c.started),
            "cpu": {"time": time, "usageCoreNanoSeconds": c.cpu_usec * 1000},
            "memory": {"time": time, "workingSetBytes": c.mem, "usageBytes": c.mem}
        }));
    }
    let pods: Vec<Value> = pods
        .into_iter()
        .map(|((n, p, u), cs)| {
            let cpu: u64 = cs
                .iter()
                .map(|c| c["cpu"]["usageCoreNanoSeconds"].as_u64().unwrap_or(0))
                .sum();
            let mem: u64 = cs
                .iter()
                .map(|c| c["memory"]["workingSetBytes"].as_u64().unwrap_or(0))
                .sum();
            json!({
                "podRef": {"name": p, "namespace": n, "uid": u},
                "cpu": {"time": time, "usageCoreNanoSeconds": cpu},
                "memory": {"time": time, "workingSetBytes": mem, "usageBytes": mem},
                "containers": cs
            })
        })
        .collect();
    json!({
        "node": {
            "nodeName": cx.node,
            "cpu": {"time": time, "usageCoreNanoSeconds": (cpu * 1e9) as u64},
            "memory": {"time": time, "workingSetBytes": mem, "usageBytes": mem}
        },
        "pods": pods
    })
}

async fn client_ca(client: &Client, file: Option<&Path>) -> Option<String> {
    if let Some(f) = file {
        return std::fs::read_to_string(f).ok();
    }
    let (code, cm) = client
        .get("/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication")
        .await
        .ok()?;
    (code == 200)
        .then(|| s(&cm, "/data/client-ca-file").to_string())
        .filter(|c| !c.is_empty())
}

pub fn write_private(path: &Path, data: &[u8]) -> std::io::Result<()> {
    use std::io::Write;
    use std::os::unix::fs::OpenOptionsExt;
    let tmp = path.with_extension("tmp");
    let mut f = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o600)
        .open(&tmp)?;
    f.write_all(data)?;
    f.sync_all()?;
    std::fs::rename(&tmp, path)
}

async fn serving_cert(
    client: Arc<Client>,
    dir: PathBuf,
    node: String,
    sans: Vec<String>,
    ca: String,
    slot: Arc<Mutex<TlsAcceptor>>,
) {
    let (crt, key) = (dir.join("serving.crt"), dir.join("serving.key"));
    let install = |cert: &str, key_pem: &str| match tls::acceptor_for(cert, key_pem, &ca) {
        Ok(a) => {
            *slot.lock().unwrap_or_else(|e| e.into_inner()) = a;
            true
        }
        Err(e) => {
            eprintln!("krab-agent: serving certificate: {e}");
            false
        }
    };
    'renew: loop {
        if let (Ok(c), Ok(k)) = (std::fs::read_to_string(&crt), std::fs::read_to_string(&key))
            && let Some(wait) = CertificateDer::pem_slice_iter(c.as_bytes())
                .next()
                .and_then(Result::ok)
                .and_then(|d| der::validity(d.as_ref()))
                .and_then(|(nb, na)| crate::join::rotation_wait(nb, na, util::now_secs()))
            && install(&c, &k)
        {
            tokio::time::sleep(wait).await;
            continue 'renew;
        }
        loop {
            let Ok(req) = csr::serving_request(&node, &sans) else {
                return;
            };
            let name = format!("csr-krab-{node}-{:08x}", util::rand_u64() as u32);
            let body = json!({
                "apiVersion": "certificates.k8s.io/v1",
                "kind": "CertificateSigningRequest",
                "metadata": {"name": name},
                "spec": {
                    "request": b64::encode_std(req.csr_pem.as_bytes()),
                    "signerName": "kubernetes.io/kubelet-serving",
                    "usages": ["digital signature", "key encipherment", "server auth"]
                }
            });
            match client
                .post(
                    "/apis/certificates.k8s.io/v1/certificatesigningrequests",
                    &body,
                )
                .await
            {
                Ok((200 | 201, _)) => eprintln!(
                    "krab-agent: waiting for approval of kubelet-serving certificate request {name}"
                ),
                other => {
                    eprintln!("krab-agent: create certificate request: {other:?}");
                    tokio::time::sleep(Duration::from_secs(30)).await;
                    continue;
                }
            }
            let path = format!("/apis/certificates.k8s.io/v1/certificatesigningrequests/{name}");
            let mut waited = 0u32;
            loop {
                tokio::time::sleep(Duration::from_secs(3)).await;
                waited += 3;
                let Ok((200, csr)) = client.get(&path).await else {
                    continue;
                };
                let cert = s(&csr, "/status/certificate");
                if !cert.is_empty() {
                    if let Some(pem) = util::base64_decode(cert)
                        .and_then(|b| String::from_utf8(b).ok())
                        .filter(|p| install(p, &req.key_pem))
                    {
                        let _ = write_private(&key, req.key_pem.as_bytes());
                        let _ = write_private(&crt, pem.as_bytes());
                        eprintln!("krab-agent: kubelet-serving certificate installed");
                        let _ = client.delete(&path, &json!({})).await;
                        continue 'renew;
                    }
                    break;
                }
                let failed = csr["status"]["conditions"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .any(|c| matches!(s(c, "/type"), "Denied" | "Failed"));
                if failed || waited >= 3600 {
                    break;
                }
            }
            let _ = client.delete(&path, &json!({})).await;
            tokio::time::sleep(Duration::from_secs(60)).await;
        }
    }
}

pub async fn run<R: Runtime + Clone>(
    app: Arc<App<R>>,
    rt: R,
    store: Arc<MemStore>,
    client: Arc<Client>,
    opts: Opts,
) -> Result<(), String> {
    let sans = vec![opts.node_ip.clone(), opts.node_name.clone()];
    let (cert, key) =
        csr::self_signed_serving(&opts.node_name, &sans).map_err(|e| e.to_string())?;
    let ca = match client_ca(&client, opts.client_ca.as_deref()).await {
        Some(c) => c,
        None => client.ca_pem(),
    };
    if ca.is_empty() {
        eprintln!(
            "krab-agent: cluster client CA unavailable, client certificates are not accepted (bearer tokens only)"
        );
    }
    let acceptor = Arc::new(Mutex::new(
        tls::acceptor_for(&cert, &key, &ca).map_err(|e| e.to_string())?,
    ));
    tokio::spawn(serving_cert(
        client.clone(),
        opts.serving_dir.clone(),
        opts.node_name.clone(),
        sans,
        ca,
        acceptor.clone(),
    ));
    let listener = TcpListener::bind(opts.bind)
        .await
        .map_err(|e| format!("bind {}: {e}", opts.bind))?;
    let bind = listener.local_addr().map_err(|e| e.to_string())?;
    let cx = Arc::new(Ctx {
        app,
        rt,
        store,
        client,
        node: opts.node_name,
        bind,
        cache: Mutex::new(HashMap::new()),
        tokens: Mutex::new(HashMap::new()),
        reviews: tokio::sync::Semaphore::new(REVIEWS),
    });
    let permits = Arc::new(tokio::sync::Semaphore::new(64));
    let per_ip: Arc<Mutex<HashMap<std::net::IpAddr, usize>>> = Arc::new(Mutex::new(HashMap::new()));
    loop {
        let (stream, addr) = listener.accept().await.map_err(|e| e.to_string())?;
        let Ok(permit) = permits.clone().try_acquire_owned() else {
            continue;
        };
        let Some(_slot) = IpSlot::take(&per_ip, addr.ip()) else {
            continue;
        };
        let acceptor = acceptor.lock().unwrap_or_else(|e| e.into_inner()).clone();
        let cx = cx.clone();
        tokio::spawn(async move {
            let (_permit, _slot) = (permit, _slot);
            let Ok(Ok(tls)) =
                tokio::time::timeout(Duration::from_secs(10), acceptor.accept(stream)).await
            else {
                return;
            };
            let peer = identity_from_peer(tls.get_ref().1);
            let svc = hyper::service::service_fn(move |req| {
                let (cx, peer) = (cx.clone(), peer.clone());
                async move { Ok::<_, Infallible>(handle(cx, req, peer).await) }
            });
            let mut b = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
            b.http1()
                .timer(TokioTimer::new())
                .header_read_timeout(Duration::from_secs(30));
            let _ = b
                .serve_connection_with_upgrades(TokioIo::new(tls), svc)
                .await;
        });
    }
}

const PER_IP: usize = 16;

struct IpSlot {
    map: Arc<Mutex<HashMap<std::net::IpAddr, usize>>>,
    ip: std::net::IpAddr,
}

impl IpSlot {
    fn take(
        map: &Arc<Mutex<HashMap<std::net::IpAddr, usize>>>,
        ip: std::net::IpAddr,
    ) -> Option<Self> {
        let mut g = map.lock().unwrap_or_else(|e| e.into_inner());
        let n = g.entry(ip).or_insert(0);
        if *n >= PER_IP {
            return None;
        }
        *n += 1;
        Some(Self {
            map: map.clone(),
            ip,
        })
    }
}

impl Drop for IpSlot {
    fn drop(&mut self) {
        let mut g = self.map.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(n) = g.get_mut(&self.ip) {
            *n -= 1;
            if *n == 0 {
                g.remove(&self.ip);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn per_ip_slots_are_limited_and_released() {
        let map = Arc::new(Mutex::new(HashMap::new()));
        let ip: std::net::IpAddr = "10.0.0.1".parse().unwrap();
        let held: Vec<_> = (0..PER_IP)
            .map(|_| IpSlot::take(&map, ip).unwrap())
            .collect();
        assert!(IpSlot::take(&map, ip).is_none());
        assert!(IpSlot::take(&map, "10.0.0.2".parse().unwrap()).is_some());
        drop(held);
        assert!(IpSlot::take(&map, ip).is_some());
    }

    #[test]
    fn streaming_endpoints_always_need_create() {
        for p in [
            "/exec/d/p/c",
            "/attach/d/p/c",
            "/portForward/d/p",
            "/run/d/p/c",
        ] {
            assert_eq!(required_verb(p, &Method::GET), "create", "{p}");
            assert_eq!(required_verb(p, &Method::POST), "create", "{p}");
        }
        assert_eq!(required_verb("/containerLogs/d/p/c", &Method::GET), "get");
        assert_eq!(required_verb("/metrics/resource", &Method::GET), "get");
        assert_eq!(required_verb("/pods", &Method::DELETE), "delete");
    }
}