krab-api 0.2.0

Kubernetes-compatible API server for krabkube
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
use crate::objects_util::base64;
use krab_runtime::policy::{data_key_ok, dns_label, host_path, rel_path_ok};
use serde_json::{Map, Value, json};
use std::collections::HashSet;
use std::path::PathBuf;

const VOLUME_TYPES: [&str; 5] = [
    "emptyDir",
    "hostPath",
    "configMap",
    "secret",
    "persistentVolumeClaim",
];

fn obj<'a>(v: &'a mut Value, k: &str) -> Option<&'a mut Map<String, Value>> {
    if !v.get(k).is_some_and(Value::is_object) {
        if !v.is_object() {
            return None;
        }
        v[k] = json!({});
    }
    v.get_mut(k)?.as_object_mut()
}

fn dflt(m: &mut Map<String, Value>, k: &str, v: Value) {
    if m.get(k).is_none_or(Value::is_null) {
        m.insert(k.into(), v);
    }
}

fn pull_policy(image: &str) -> &'static str {
    let last = image.rsplit('/').next().unwrap_or(image);
    if image.contains('@') {
        return "IfNotPresent";
    }
    match last.split_once(':') {
        Some((_, "latest")) | None => "Always",
        Some(_) => "IfNotPresent",
    }
}

fn containers(spec: &mut Map<String, Value>, field: &str) {
    let Some(list) = spec.get_mut(field).and_then(Value::as_array_mut) else {
        return;
    };
    for c in list.iter_mut().filter_map(Value::as_object_mut) {
        let img = c
            .get("image")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        dflt(c, "imagePullPolicy", json!(pull_policy(&img)));
        dflt(c, "terminationMessagePath", json!("/dev/termination-log"));
        dflt(c, "terminationMessagePolicy", json!("File"));
        dflt(c, "resources", json!({}));
        if let Some(ports) = c.get_mut("ports").and_then(Value::as_array_mut) {
            for p in ports.iter_mut().filter_map(Value::as_object_mut) {
                dflt(p, "protocol", json!("TCP"));
            }
        }
    }
}

pub fn pod_spec(spec: &mut Value) {
    let Some(s) = spec.as_object_mut() else {
        return;
    };
    dflt(s, "restartPolicy", json!("Always"));
    dflt(s, "dnsPolicy", json!("ClusterFirst"));
    dflt(s, "terminationGracePeriodSeconds", json!(30));
    dflt(s, "schedulerName", json!("default-scheduler"));
    dflt(s, "securityContext", json!({}));
    containers(s, "containers");
    containers(s, "initContainers");
}

fn template(o: &mut Value) {
    if let Some(t) = o.pointer_mut("/spec/template") {
        if let Some(spec) = t.get_mut("spec") {
            pod_spec(spec);
        }
        if let Some(m) = obj(t, "metadata") {
            dflt(m, "creationTimestamp", Value::Null);
        }
    }
}

pub fn apply(kind: &str, o: &mut Value) {
    match kind {
        "Pod" => {
            if let Some(s) = o.get_mut("spec") {
                pod_spec(s);
            }
        }
        "Deployment" => {
            if let Some(s) = obj(o, "spec") {
                dflt(s, "replicas", json!(1));
                dflt(s, "revisionHistoryLimit", json!(10));
                dflt(s, "progressDeadlineSeconds", json!(600));
                dflt(
                    s,
                    "strategy",
                    json!({"type": "RollingUpdate", "rollingUpdate": {"maxUnavailable": "25%", "maxSurge": "25%"}}),
                );
                if let Some(st) = s.get_mut("strategy").and_then(Value::as_object_mut) {
                    dflt(st, "type", json!("RollingUpdate"));
                    if st.get("type") == Some(&json!("RollingUpdate")) {
                        let ru = st.entry("rollingUpdate").or_insert_with(|| json!({}));
                        if let Some(ru) = ru.as_object_mut() {
                            dflt(ru, "maxUnavailable", json!("25%"));
                            dflt(ru, "maxSurge", json!("25%"));
                        }
                    }
                }
            }
            template(o);
        }
        "ReplicaSet" => {
            if let Some(s) = obj(o, "spec") {
                dflt(s, "replicas", json!(1));
            }
            template(o);
        }
        "Service" => {
            if let Some(s) = obj(o, "spec") {
                dflt(s, "type", json!("ClusterIP"));
                dflt(s, "sessionAffinity", json!("None"));
                if s.get("type") != Some(&json!("ExternalName")) {
                    dflt(s, "internalTrafficPolicy", json!("Cluster"));
                }
                if let Some(ports) = s.get_mut("ports").and_then(Value::as_array_mut) {
                    for p in ports.iter_mut().filter_map(Value::as_object_mut) {
                        dflt(p, "protocol", json!("TCP"));
                        if let Some(port) = p.get("port").cloned() {
                            dflt(p, "targetPort", port);
                        }
                    }
                }
            }
        }
        "Namespace" => {
            let name = o.pointer("/metadata/name").cloned().unwrap_or(Value::Null);
            if let Some(m) = obj(o, "metadata") {
                let labels = m.entry("labels").or_insert_with(|| json!({}));
                if let Some(l) = labels.as_object_mut() {
                    l.insert("kubernetes.io/metadata.name".into(), name);
                }
            }
            if let Some(s) = obj(o, "spec") {
                dflt(s, "finalizers", json!(["kubernetes"]));
            }
            if let Some(s) = obj(o, "status") {
                dflt(s, "phase", json!("Active"));
            }
        }
        "PersistentVolumeClaim" => {
            if let Some(m) = obj(o, "metadata") {
                let f = m.entry("finalizers").or_insert_with(|| json!([]));
                if let Some(a) = f.as_array_mut()
                    && !a.iter().any(|x| x == "kubernetes.io/pvc-protection")
                {
                    a.push(json!("kubernetes.io/pvc-protection"));
                }
            }
            if let Some(s) = obj(o, "spec") {
                dflt(s, "volumeMode", json!("Filesystem"));
            }
        }
        "PersistentVolume" => {
            if let Some(s) = obj(o, "spec") {
                dflt(s, "persistentVolumeReclaimPolicy", json!("Retain"));
                dflt(s, "volumeMode", json!("Filesystem"));
            }
        }
        "StorageClass" => {
            if let Some(m) = o.as_object_mut() {
                dflt(m, "reclaimPolicy", json!("Delete"));
                dflt(m, "volumeBindingMode", json!("Immediate"));
            }
        }
        "Secret" => {
            if let Some(m) = o.as_object_mut() {
                dflt(m, "type", json!("Opaque"));
                if let Some(Value::Object(sd)) = m.remove("stringData") {
                    let data = m.entry("data").or_insert_with(|| json!({}));
                    if let Some(d) = data.as_object_mut() {
                        for (k, v) in sd {
                            let s = v
                                .as_str()
                                .map(str::to_string)
                                .unwrap_or_else(|| v.to_string());
                            d.insert(k, json!(base64(s.as_bytes())));
                        }
                    }
                }
            }
        }
        _ => {}
    }
}

pub fn initial_status(kind: &str) -> Option<Value> {
    match kind {
        "Pod" => Some(json!({"phase": "Pending", "qosClass": "BestEffort"})),
        "Deployment" | "ReplicaSet" => Some(json!({})),
        "Service" => Some(json!({"loadBalancer": {}})),
        "Namespace" => Some(json!({"phase": "Active"})),
        "PersistentVolumeClaim" | "PersistentVolume" => Some(json!({"phase": "Pending"})),
        _ => None,
    }
}

pub fn has_generation(kind: &str) -> bool {
    matches!(kind, "Pod" | "Deployment" | "ReplicaSet")
}

fn is_label(s: &str, first_alpha: bool) -> bool {
    let b = s.as_bytes();
    !b.is_empty()
        && b.len() <= 63
        && b.iter()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
        && if first_alpha {
            b[0].is_ascii_lowercase()
        } else {
            b[0].is_ascii_alphanumeric()
        }
        && b[b.len() - 1].is_ascii_alphanumeric()
}

pub fn validate_name(kind: &str, name: &str) -> Option<String> {
    match kind {
        "Namespace" => (!is_label(name, false)).then(|| format!("Invalid value: \"{name}\": a lowercase RFC 1123 label must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character (e.g. 'my-name',  or '123-abc', regex used for validation is '[a-z0-9]([-a-z0-9]*[a-z0-9])?')")),
        "Service" => (!is_label(name, true)).then(|| format!("Invalid value: \"{name}\": a DNS-1035 label must consist of lower case alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character (e.g. 'my-name',  or 'abc-123', regex used for validation is '[a-z]([-a-z0-9]*[a-z0-9])?')")),
        _ => (name.len() > 253 || !name.split('.').all(|l| is_label(l, false))).then(|| format!("Invalid value: \"{name}\": a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character (e.g. 'example.com', regex used for validation is '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*')")),
    }
}

fn string_map(v: Option<&Value>, at: &str, out: &mut Vec<(String, String)>) {
    if let Some(v) = v.filter(|v| !v.is_null())
        && !v
            .as_object()
            .is_some_and(|m| m.values().all(Value::is_string))
    {
        out.push((
            at.into(),
            "Invalid value: must be a map of string keys to string values".into(),
        ));
    }
}

fn object_at(v: Option<&Value>, at: &str, out: &mut Vec<(String, String)>) {
    if v.is_some_and(|v| !v.is_null() && !v.is_object()) {
        out.push((at.into(), "Invalid value: must be an object".into()));
    }
}

pub fn validate_shape(o: &Value) -> Vec<(String, String)> {
    let mut out = Vec::new();
    object_at(o.get("metadata"), "metadata", &mut out);
    string_map(o.pointer("/metadata/labels"), "metadata.labels", &mut out);
    string_map(
        o.pointer("/metadata/annotations"),
        "metadata.annotations",
        &mut out,
    );
    object_at(o.get("spec"), "spec", &mut out);
    object_at(o.get("status"), "status", &mut out);
    out
}

fn check_mode(v: &Value, at: String, out: &mut Vec<(String, String)>) {
    if v.get("defaultMode")
        .or_else(|| v.get("mode"))
        .is_some_and(|m| m.as_u64().is_none_or(|m| m > 0o777))
    {
        out.push((
            at,
            "Invalid value: must be a number between 0 and 0777 (octal)".into(),
        ));
    }
}

fn check_volumes(spec: &Value, at: &str, out: &mut Vec<(String, String)>) -> HashSet<String> {
    let mut names = HashSet::new();
    let Some(vols) = spec.get("volumes").filter(|v| !v.is_null()) else {
        return names;
    };
    let Some(vols) = vols.as_array() else {
        out.push((
            format!("{at}.volumes"),
            "Invalid value: must be a list".into(),
        ));
        return names;
    };
    for (i, v) in vols.iter().enumerate() {
        let vat = format!("{at}.volumes[{i}]");
        let name = v.get("name").and_then(Value::as_str).unwrap_or("");
        if !dns_label(name) {
            out.push((
                format!("{vat}.name"),
                format!("Invalid value: \"{name}\": must be a lowercase RFC 1123 label"),
            ));
        } else if !names.insert(name.to_string()) {
            out.push((
                format!("{vat}.name"),
                format!("Duplicate value: \"{name}\""),
            ));
        }
        let Some(m) = v.as_object() else { continue };
        if let Some(k) = m
            .keys()
            .find(|k| *k != "name" && !VOLUME_TYPES.contains(&k.as_str()))
        {
            out.push((
                format!("{vat}.{k}"),
                "Unsupported value: supported volume types: emptyDir, hostPath, configMap, secret, persistentVolumeClaim"
                    .into(),
            ));
        }
        if VOLUME_TYPES.iter().filter(|t| m.contains_key(**t)).count() > 1 {
            out.push((
                vat.clone(),
                "Forbidden: may not specify more than 1 volume type".into(),
            ));
        }
        if let Some(h) = m.get("hostPath")
            && h.get("path")
                .and_then(Value::as_str)
                .is_none_or(str::is_empty)
        {
            out.push((format!("{vat}.hostPath.path"), "Required value".into()));
        }
        if let Some(c) = m.get("persistentVolumeClaim")
            && c.get("claimName")
                .and_then(Value::as_str)
                .is_none_or(str::is_empty)
        {
            out.push((
                format!("{vat}.persistentVolumeClaim.claimName"),
                "Required value".into(),
            ));
        }
        for t in ["configMap", "secret"] {
            let Some(src) = m.get(t) else { continue };
            check_mode(src, format!("{vat}.{t}.defaultMode"), out);
            for (j, it) in src
                .get("items")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
                .enumerate()
            {
                let iat = format!("{vat}.{t}.items[{j}]");
                let key = it.get("key").and_then(Value::as_str).unwrap_or("");
                if !data_key_ok(key) {
                    out.push((format!("{iat}.key"), format!("Invalid value: \"{key}\"")));
                }
                let path = it.get("path").and_then(Value::as_str).unwrap_or("");
                if !rel_path_ok(path) {
                    out.push((
                        format!("{iat}.path"),
                        format!("Invalid value: \"{path}\": must be a relative path without '..'"),
                    ));
                }
                check_mode(it, format!("{iat}.mode"), out);
            }
        }
    }
    names
}

fn check_port(p: &Value, k: &str, min: u64, at: String, out: &mut Vec<(String, String)>) {
    if p.get(k)
        .is_some_and(|v| v.as_u64().is_none_or(|n| n < min || n > 65535))
    {
        out.push((
            at,
            format!("Invalid value: must be between {min} and 65535, inclusive"),
        ));
    }
}

fn check_containers(
    spec: &Value,
    at: &str,
    names: &HashSet<String>,
    out: &mut Vec<(String, String)>,
) {
    for list in ["containers", "initContainers"] {
        for (i, c) in spec
            .get(list)
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
            .enumerate()
        {
            let cat = format!("{at}.{list}[{i}]");
            for (j, vm) in c
                .get("volumeMounts")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
                .enumerate()
            {
                let mat = format!("{cat}.volumeMounts[{j}]");
                let name = vm.get("name").and_then(Value::as_str).unwrap_or("");
                if !names.contains(name) {
                    out.push((format!("{mat}.name"), format!("Not found: \"{name}\"")));
                }
                let mp = vm.get("mountPath").and_then(Value::as_str).unwrap_or("");
                if !mp.starts_with('/') || mp.contains(':') || mp.contains('\0') {
                    out.push((
                        format!("{mat}.mountPath"),
                        format!("Invalid value: \"{mp}\": must be an absolute path without ':'"),
                    ));
                }
                let sub = vm.get("subPath").and_then(Value::as_str).unwrap_or("");
                if !sub.is_empty() && !rel_path_ok(sub) {
                    out.push((
                        format!("{mat}.subPath"),
                        format!("Invalid value: \"{sub}\": must be a relative path without '..'"),
                    ));
                }
            }
            for (j, p) in c
                .get("ports")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
                .enumerate()
            {
                let pat = format!("{cat}.ports[{j}]");
                check_port(p, "containerPort", 1, format!("{pat}.containerPort"), out);
                check_port(p, "hostPort", 0, format!("{pat}.hostPort"), out);
            }
        }
    }
}

pub fn admit(kind: &str, o: &Value, allow: &[PathBuf]) -> Option<String> {
    let spec = match kind {
        "Pod" => o.get("spec"),
        "Deployment" | "ReplicaSet" => o.pointer("/spec/template/spec"),
        _ => None,
    }?;
    for f in ["hostNetwork", "hostPID", "hostIPC"] {
        if spec.get(f).and_then(Value::as_bool) == Some(true) {
            return Some(format!("{f} is not allowed"));
        }
    }
    for list in ["containers", "initContainers", "ephemeralContainers"] {
        for c in spec
            .get(list)
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
        {
            let sc = &c["securityContext"];
            if sc["privileged"].as_bool() == Some(true) {
                return Some("privileged containers are not allowed".into());
            }
            if sc
                .pointer("/capabilities/add")
                .and_then(Value::as_array)
                .is_some_and(|a| !a.is_empty())
            {
                return Some("adding capabilities is not allowed".into());
            }
        }
    }
    for v in spec
        .get("volumes")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        if let Some(h) = v.get("hostPath") {
            let path = h.get("path").and_then(Value::as_str).unwrap_or("");
            if let Err(e) = host_path(path, allow) {
                return Some(e);
            }
        }
    }
    None
}

fn check_pod_spec(spec: Option<&Value>, at: &str, out: &mut Vec<(String, String)>) {
    if let Some(sp) = spec {
        let names = check_volumes(sp, at, out);
        check_containers(sp, at, &names, out);
    }
    let cs = spec
        .and_then(|s| s.get("containers"))
        .and_then(Value::as_array);
    match cs {
        None => out.push((format!("{at}.containers"), "Required value".into())),
        Some(cs) if cs.is_empty() => {
            out.push((format!("{at}.containers"), "Required value".into()))
        }
        Some(cs) => {
            for (i, c) in cs.iter().enumerate() {
                if c.get("name")
                    .and_then(Value::as_str)
                    .is_none_or(str::is_empty)
                {
                    out.push((
                        format!("{at}.containers[{i}].name"),
                        "Required value".into(),
                    ));
                }
                if c.get("image")
                    .and_then(Value::as_str)
                    .is_none_or(str::is_empty)
                {
                    out.push((
                        format!("{at}.containers[{i}].image"),
                        "Required value".into(),
                    ));
                }
            }
        }
    }
}

pub fn validate(kind: &str, o: &Value) -> Vec<(String, String)> {
    let mut out = validate_shape(o);
    match kind {
        "Pod" => check_pod_spec(o.get("spec"), "spec", &mut out),
        "ConfigMap" | "Secret" => {
            for f in ["data", "binaryData", "stringData"] {
                let Some(d) = o.get(f).filter(|d| !d.is_null()) else {
                    continue;
                };
                let Some(m) = d.as_object() else {
                    out.push((f.into(), "Invalid value: must be an object".into()));
                    continue;
                };
                for k in m.keys().filter(|k| !data_key_ok(k)) {
                    out.push((
                        format!("{f}[{k}]"),
                        format!("Invalid value: \"{k}\": a valid config key must consist of alphanumeric characters, '-', '_' or '.'"),
                    ));
                }
            }
        }
        "Deployment" | "ReplicaSet" => {
            string_map(
                o.pointer("/spec/selector/matchLabels"),
                "spec.selector.matchLabels",
                &mut out,
            );
            object_at(o.pointer("/spec/template"), "spec.template", &mut out);
            object_at(
                o.pointer("/spec/template/metadata"),
                "spec.template.metadata",
                &mut out,
            );
            string_map(
                o.pointer("/spec/template/metadata/labels"),
                "spec.template.metadata.labels",
                &mut out,
            );
            let sel = o.pointer("/spec/selector");
            if sel.is_none_or(|s| s.as_object().is_none_or(Map::is_empty)) {
                out.push(("spec.selector".into(), "Required value".into()));
            }
            check_pod_spec(
                o.pointer("/spec/template/spec"),
                "spec.template.spec",
                &mut out,
            );
            if let Some(ml) = o
                .pointer("/spec/selector/matchLabels")
                .and_then(Value::as_object)
            {
                let tl = o.pointer("/spec/template/metadata/labels");
                if ml.iter().any(|(k, v)| tl.and_then(|l| l.get(k)) != Some(v)) {
                    out.push((
                        "spec.template.metadata.labels".into(),
                        "Invalid value: `selector` does not match template `labels`".into(),
                    ));
                }
            }
            if o.pointer("/spec/replicas")
                .is_some_and(|r| r.as_i64().is_none_or(|n| n < 0))
            {
                out.push((
                    "spec.replicas".into(),
                    "Invalid value: must be greater than or equal to 0".into(),
                ));
            }
        }
        "Service" => {
            let ty = o
                .pointer("/spec/type")
                .and_then(Value::as_str)
                .unwrap_or("ClusterIP");
            if !matches!(
                ty,
                "ClusterIP" | "NodePort" | "LoadBalancer" | "ExternalName"
            ) {
                out.push((
                    "spec.type".into(),
                    format!("Unsupported value: \"{ty}\": supported values: \"ClusterIP\", \"ExternalName\", \"LoadBalancer\", \"NodePort\""),
                ));
            }
            let headless = o.pointer("/spec/clusterIP").and_then(Value::as_str) == Some("None");
            let ports = o.pointer("/spec/ports").and_then(Value::as_array);
            if ty != "ExternalName" && !headless && ports.is_none_or(Vec::is_empty) {
                out.push(("spec.ports".into(), "Required value".into()));
            }
            for (i, p) in ports.into_iter().flatten().enumerate() {
                if !p.is_object() {
                    out.push((
                        format!("spec.ports[{i}]"),
                        "Invalid value: must be an object".into(),
                    ));
                } else {
                    check_port(p, "port", 1, format!("spec.ports[{i}].port"), &mut out);
                    check_port(
                        p,
                        "nodePort",
                        0,
                        format!("spec.ports[{i}].nodePort"),
                        &mut out,
                    );
                }
            }
        }
        "PersistentVolumeClaim" => {
            if o.pointer("/spec/accessModes")
                .and_then(Value::as_array)
                .is_none_or(Vec::is_empty)
            {
                out.push(("spec.accessModes".into(), "Required value".into()));
            }
            if o.pointer("/spec/resources/requests/storage").is_none() {
                out.push(("spec.resources[storage]".into(), "Required value".into()));
            }
        }
        "StorageClass"
            if o.get("provisioner")
                .and_then(Value::as_str)
                .is_none_or(str::is_empty) =>
        {
            out.push(("provisioner".into(), "Required value".into()));
        }
        _ => {}
    }
    out
}

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

    #[test]
    fn deployment_defaults() {
        let mut d = json!({"spec": {"selector": {"matchLabels": {"a": "b"}}, "template": {"metadata": {"labels": {"a": "b"}}, "spec": {"containers": [{"name": "c", "image": "nginx"}]}}}});
        apply("Deployment", &mut d);
        assert_eq!(d["spec"]["replicas"], 1);
        assert_eq!(d["spec"]["strategy"]["rollingUpdate"]["maxSurge"], "25%");
        let c = &d["spec"]["template"]["spec"]["containers"][0];
        assert_eq!(c["imagePullPolicy"], "Always");
        assert_eq!(d["spec"]["template"]["spec"]["dnsPolicy"], "ClusterFirst");
        assert!(validate("Deployment", &d).is_empty());
    }

    #[test]
    fn service_and_secret() {
        let mut s = json!({"spec": {"ports": [{"port": 80}]}});
        apply("Service", &mut s);
        assert_eq!(s["spec"]["ports"][0]["targetPort"], 80);
        assert_eq!(s["spec"]["type"], "ClusterIP");
        let mut sec = json!({"stringData": {"k": "hello"}});
        apply("Secret", &mut sec);
        assert_eq!(sec["data"]["k"], "aGVsbG8=");
        assert!(sec.get("stringData").is_none());
    }

    #[test]
    fn names() {
        assert!(validate_name("Pod", "a.b-c").is_none());
        assert!(validate_name("Pod", "Bad_Name").is_some());
        assert!(validate_name("Service", "1abc").is_some());
        assert!(validate_name("Namespace", "a.b").is_some());
        assert_eq!(pull_policy("nginx:1.27"), "IfNotPresent");
        assert_eq!(pull_policy("reg:5000/nginx"), "Always");
    }
}