krab-api 0.1.0

Kubernetes-compatible API server for krabkube
Documentation
use crate::objects_util::base64;
use serde_json::{Map, Value, json};

struct Reader<'a> {
    b: &'a [u8],
    i: usize,
}

enum Field<'a> {
    Varint(u64),
    Bytes(&'a [u8]),
}

impl<'a> Reader<'a> {
    fn new(b: &'a [u8]) -> Self {
        Self { b, i: 0 }
    }

    fn varint(&mut self) -> Option<u64> {
        let mut v = 0u64;
        for shift in (0..64).step_by(7) {
            let c = *self.b.get(self.i)?;
            self.i += 1;
            v |= ((c & 0x7f) as u64) << shift;
            if c & 0x80 == 0 {
                return Some(v);
            }
        }
        None
    }

    fn next(&mut self) -> Option<Result<(u64, Field<'a>), ()>> {
        if self.i >= self.b.len() {
            return None;
        }
        let Some(tag) = self.varint() else {
            return Some(Err(()));
        };
        let f = match tag & 7 {
            0 => self.varint().map(Field::Varint),
            2 => self.varint().and_then(|n| {
                let end = self.i.checked_add(n as usize)?;
                let s = self.b.get(self.i..end)?;
                self.i = end;
                Some(Field::Bytes(s))
            }),
            1 => {
                self.i += 8;
                Some(Field::Varint(0))
            }
            5 => {
                self.i += 4;
                Some(Field::Varint(0))
            }
            _ => None,
        };
        Some(f.map(|f| (tag >> 3, f)).ok_or(()))
    }
}

fn fields(b: &[u8]) -> Result<Vec<(u64, Field<'_>)>, ()> {
    let mut r = Reader::new(b);
    let mut out = Vec::new();
    while let Some(f) = r.next() {
        out.push(f?);
    }
    Ok(out)
}

fn text(b: &[u8]) -> Value {
    json!(String::from_utf8_lossy(b))
}

fn map_entry(b: &[u8], bytes_value: bool) -> Result<(String, Value), ()> {
    let mut k = String::new();
    let mut v = json!("");
    for (n, f) in fields(b)? {
        match (n, f) {
            (1, Field::Bytes(s)) => k = String::from_utf8_lossy(s).into_owned(),
            (2, Field::Bytes(s)) if bytes_value => v = json!(base64(s)),
            (2, Field::Bytes(s)) => v = text(s),
            _ => {}
        }
    }
    Ok((k, v))
}

fn put_map(o: &mut Map<String, Value>, key: &str, entry: (String, Value)) {
    let m = o.entry(key).or_insert_with(|| json!({}));
    if let Some(m) = m.as_object_mut() {
        m.insert(entry.0, entry.1);
    }
}

fn push(o: &mut Map<String, Value>, key: &str, v: Value) {
    let a = o.entry(key).or_insert_with(|| json!([]));
    if let Some(a) = a.as_array_mut() {
        a.push(v);
    }
}

fn object_meta(b: &[u8]) -> Result<Value, ()> {
    let mut m = Map::new();
    for (n, f) in fields(b)? {
        match (n, f) {
            (1, Field::Bytes(s)) if !s.is_empty() => {
                m.insert("name".into(), text(s));
            }
            (2, Field::Bytes(s)) if !s.is_empty() => {
                m.insert("generateName".into(), text(s));
            }
            (3, Field::Bytes(s)) if !s.is_empty() => {
                m.insert("namespace".into(), text(s));
            }
            (11, Field::Bytes(s)) => put_map(&mut m, "labels", map_entry(s, false)?),
            (12, Field::Bytes(s)) => put_map(&mut m, "annotations", map_entry(s, false)?),
            (14, Field::Bytes(s)) => push(&mut m, "finalizers", text(s)),
            _ => {}
        }
    }
    Ok(Value::Object(m))
}

fn decode_kind(kind: &str, b: &[u8]) -> Result<Value, ()> {
    let mut o = Map::new();
    for (n, f) in fields(b)? {
        match (kind, n, f) {
            (_, 1, Field::Bytes(s)) => {
                o.insert("metadata".into(), object_meta(s)?);
            }
            ("Namespace", 2, Field::Bytes(s)) => {
                let mut spec = Map::new();
                for (n, f) in fields(s)? {
                    if let (1, Field::Bytes(x)) = (n, f) {
                        push(&mut spec, "finalizers", text(x));
                    }
                }
                o.insert("spec".into(), Value::Object(spec));
            }
            ("ConfigMap", 2, Field::Bytes(s)) => put_map(&mut o, "data", map_entry(s, false)?),
            ("ConfigMap", 3, Field::Bytes(s)) => put_map(&mut o, "binaryData", map_entry(s, true)?),
            ("ConfigMap", 4, Field::Varint(v)) | ("Secret", 5, Field::Varint(v)) => {
                o.insert("immutable".into(), json!(v != 0));
            }
            ("Secret", 2, Field::Bytes(s)) => put_map(&mut o, "data", map_entry(s, true)?),
            ("Secret", 3, Field::Bytes(s)) if !s.is_empty() => {
                o.insert("type".into(), text(s));
            }
            ("Secret", 4, Field::Bytes(s)) => put_map(&mut o, "stringData", map_entry(s, false)?),
            ("ServiceAccount", 4, Field::Varint(v)) => {
                o.insert("automountServiceAccountToken".into(), json!(v != 0));
            }
            _ => {}
        }
    }
    Ok(Value::Object(o))
}

pub fn decode(body: &[u8]) -> Result<Value, String> {
    let raw = body
        .strip_prefix(b"k8s\x00")
        .ok_or("missing protobuf envelope")?;
    let mut av = String::new();
    let mut kind = String::new();
    let mut obj: &[u8] = &[];
    for (n, f) in fields(raw).map_err(|_| "malformed protobuf")? {
        match (n, f) {
            (1, Field::Bytes(tm)) => {
                for (n, f) in fields(tm).map_err(|_| "malformed protobuf")? {
                    match (n, f) {
                        (1, Field::Bytes(s)) => av = String::from_utf8_lossy(s).into_owned(),
                        (2, Field::Bytes(s)) => kind = String::from_utf8_lossy(s).into_owned(),
                        _ => {}
                    }
                }
            }
            (2, Field::Bytes(s)) => obj = s,
            _ => {}
        }
    }
    if !matches!(
        kind.as_str(),
        "Namespace" | "ConfigMap" | "Secret" | "ServiceAccount"
    ) {
        return Err(format!(
            "krab decodes protobuf only for Namespace, ConfigMap, Secret and ServiceAccount (got {kind:?}); send JSON, e.g. kubectl create -f / kubectl apply -f"
        ));
    }
    let mut v = decode_kind(&kind, obj).map_err(|_| "malformed protobuf object".to_string())?;
    v["apiVersion"] = json!(av);
    v["kind"] = json!(kind);
    Ok(v)
}

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

    fn ld(n: u8, b: &[u8]) -> Vec<u8> {
        let mut v = vec![n << 3 | 2, b.len() as u8];
        v.extend_from_slice(b);
        v
    }

    #[test]
    fn decodes_secret_envelope() {
        let tm = [ld(1, b"v1"), ld(2, b"Secret")].concat();
        let meta = [ld(1, b"s1"), ld(11, &[ld(1, b"app"), ld(2, b"x")].concat())].concat();
        let obj = [
            ld(1, &meta),
            ld(2, &[ld(1, b"k"), ld(2, b"hello")].concat()),
            ld(3, b"Opaque"),
        ]
        .concat();
        let body = [b"k8s\x00".to_vec(), ld(1, &tm), ld(2, &obj)].concat();
        let v = decode(&body).unwrap();
        assert_eq!(v["kind"], "Secret");
        assert_eq!(v["metadata"]["name"], "s1");
        assert_eq!(v["metadata"]["labels"]["app"], "x");
        assert_eq!(v["data"]["k"], "aGVsbG8=");
        assert_eq!(v["type"], "Opaque");
        let empty = [ld(1, &ld(1, b"s2")), ld(3, b"")].concat();
        let body = [b"k8s\x00".to_vec(), ld(1, &tm), ld(2, &empty)].concat();
        assert!(decode(&body).unwrap().get("type").is_none());
        let bad = [b"k8s\x00".to_vec(), ld(1, &[ld(2, b"Pod")].concat())].concat();
        assert!(decode(&bad).is_err());
    }
}