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");
}
}