krab-api 0.2.1

Kubernetes-compatible API server for krabkube
Documentation
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::Request;
use hyper_util::rt::TokioIo;
use krab_api::crypt::SecretCodec;
use krab_api::{App, Config, Keyring, MemStore, serve};
use krab_runtime::{ContainerInfo, LogOpts, Runtime};
use serde_json::{Value, json};
use std::io;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc;

const VALUE: &str = "s3cr3t-VALUE-9f2c";
const VALUE_B64: &str = "czNjcjN0LVZBTFVFLTlmMmM=";
const J: &str = "application/json";

struct Fake;

impl Runtime for Fake {
    fn name(&self) -> &str {
        "fake"
    }

    async fn list(&self) -> io::Result<Vec<ContainerInfo>> {
        Ok(Vec::new())
    }

    async fn inspect(&self, _: &mut ContainerInfo) -> io::Result<()> {
        Ok(())
    }

    async fn logs(&self, _: &ContainerInfo, _: &LogOpts) -> io::Result<mpsc::Receiver<Bytes>> {
        Ok(mpsc::channel(1).1)
    }
}

fn tmp(name: &str) -> PathBuf {
    static N: AtomicUsize = AtomicUsize::new(0);
    let d = std::env::temp_dir().join(format!(
        "krab-crypt-{name}-{}-{}",
        std::process::id(),
        N.fetch_add(1, Ordering::Relaxed)
    ));
    let _ = std::fs::remove_dir_all(&d);
    std::fs::create_dir_all(&d).unwrap();
    d
}

fn keyfile(dir: &Path, name: &str) -> PathBuf {
    let p = dir.join(name);
    Keyring::generate_file(&p, "key1").unwrap();
    p
}

fn open(db: &Path, key: Option<&Path>) -> Arc<MemStore> {
    let s = MemStore::open(db, 1 << 20, 64).unwrap();
    if let Some(k) = key {
        assert!(s.set_codec(Box::new(SecretCodec::new(Some(
            Keyring::from_file(k).unwrap()
        )))));
    }
    s
}

fn put_secret(s: &MemStore, name: &str) -> u64 {
    s.put(&format!("secrets/default/{name}"), |rev| {
        Bytes::from(
            json!({"apiVersion": "v1", "kind": "Secret",
                "metadata": {"name": name, "namespace": "default", "resourceVersion": rev.to_string()},
                "data": {"password": VALUE_B64}})
            .to_string(),
        )
    })
}

async fn start(store: Arc<MemStore>) -> SocketAddr {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let cfg = Config {
        listen: addr.to_string(),
        poll_interval: Duration::from_millis(50),
        ..Default::default()
    };
    tokio::spawn(serve(App::new(cfg, Fake, store), listener));
    addr
}

type Resp = hyper::Response<hyper::body::Incoming>;

async fn send(addr: SocketAddr, method: &str, path: &str, ctype: &str, body: &str) -> Resp {
    let stream = TcpStream::connect(addr).await.unwrap();
    let (mut tx, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
        .await
        .unwrap();
    tokio::spawn(conn);
    let mut b = Request::builder()
        .method(method)
        .uri(path)
        .header("host", "x");
    if !ctype.is_empty() {
        b = b.header("content-type", ctype);
    }
    tx.send_request(b.body(Full::new(Bytes::from(body.to_string()))).unwrap())
        .await
        .unwrap()
}

async fn call(
    addr: SocketAddr,
    method: &str,
    path: &str,
    ctype: &str,
    body: &str,
) -> (u16, String) {
    let r = send(addr, method, path, ctype, body).await;
    let code = r.status().as_u16();
    let b = r.into_body().collect().await.unwrap().to_bytes();
    (code, String::from_utf8_lossy(&b).into_owned())
}

fn contains(hay: &[u8], needle: &str) -> bool {
    hay.windows(needle.len()).any(|w| w == needle.as_bytes())
}

async fn read_until(r: Resp, needle: &str) -> String {
    let mut body = r.into_body();
    let mut buf = String::new();
    let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
    while !buf.contains(needle) {
        let f = tokio::time::timeout_at(deadline, body.frame())
            .await
            .expect("watch timed out");
        let Some(Ok(f)) = f else { break };
        if let Ok(d) = f.into_data() {
            buf.push_str(&String::from_utf8_lossy(&d));
        }
    }
    buf
}

#[tokio::test]
async fn roundtrip_watch_and_file_has_no_plaintext() {
    let dir = tmp("roundtrip");
    let db = dir.join("store.redb");
    let store = open(&db, Some(&keyfile(&dir, "key")));
    let addr = start(store).await;
    let (_, l) = call(addr, "GET", "/api/v1/namespaces/default/secrets", "", "").await;
    let rv: Value = serde_json::from_str(&l).unwrap();
    let rv = rv["metadata"]["resourceVersion"]
        .as_str()
        .unwrap()
        .to_string();
    let w0 = send(
        addr,
        "GET",
        "/api/v1/namespaces/default/secrets?watch=1",
        "",
        "",
    )
    .await;
    let w1 = send(
        addr,
        "GET",
        &format!("/api/v1/namespaces/default/secrets?watch=1&resourceVersion={rv}"),
        "",
        "",
    )
    .await;
    let (c, b) = call(
        addr,
        "POST",
        "/api/v1/namespaces/default/secrets",
        J,
        &json!({"apiVersion": "v1", "kind": "Secret", "metadata": {"name": "app"}, "stringData": {"password": VALUE}}).to_string(),
    )
    .await;
    assert_eq!(c, 201, "{b}");
    assert!(b.contains(VALUE_B64));
    let (c, _) = call(
        addr,
        "POST",
        "/api/v1/namespaces/default/configmaps",
        J,
        r#"{"metadata":{"name":"cm"},"data":{"k":"cm-plain-marker"}}"#,
    )
    .await;
    assert_eq!(c, 201);
    let (c, b) = call(
        addr,
        "GET",
        "/api/v1/namespaces/default/secrets/app",
        "",
        "",
    )
    .await;
    assert_eq!(c, 200);
    assert!(b.contains(VALUE_B64));
    let (c, b) = call(addr, "GET", "/api/v1/namespaces/default/secrets", "", "").await;
    assert_eq!(c, 200);
    assert!(b.contains(VALUE_B64));
    let (c, b) = call(
        addr,
        "PATCH",
        "/api/v1/namespaces/default/secrets/app",
        "application/merge-patch+json",
        r#"{"metadata":{"labels":{"x":"y"}}}"#,
    )
    .await;
    assert_eq!(c, 200, "{b}");
    assert!(b.contains(VALUE_B64) && b.contains("\"x\":\"y\""));
    assert!(read_until(w0, VALUE_B64).await.contains("ADDED"));
    assert!(read_until(w1, VALUE_B64).await.contains("ADDED"));
    let raw = std::fs::read(&db).unwrap();
    assert!(contains(&raw, "cm-plain-marker"));
    assert!(!contains(&raw, VALUE));
    assert!(!contains(&raw, VALUE_B64));
}

#[tokio::test]
async fn startup_migration_encrypts_plaintext() {
    let dir = tmp("migrate");
    let db = dir.join("store.redb");
    let key = keyfile(&dir, "key");
    let rev = {
        let s = open(&db, None);
        put_secret(&s, "old");
        s.put("configmaps/default/cm", |_| Bytes::from_static(b"{}"));
        s.rev()
    };
    {
        let s = open(&db, Some(&key));
        let r = s.reseal(false).unwrap();
        assert_eq!((r.rewritten, r.unreadable), (1, 0));
        assert_eq!(s.reseal(false).unwrap().rewritten, 0);
        assert_eq!(s.rev(), rev);
    }
    {
        let s = open(&db, None);
        assert_eq!(s.rev(), rev);
        assert!(krab_crypt::is_encrypted(
            &s.get("secrets/default/old").unwrap()
        ));
        assert_eq!(s.get("configmaps/default/cm").unwrap().as_ref(), b"{}");
    }
    let addr = start(open(&db, Some(&key))).await;
    let (c, b) = call(
        addr,
        "GET",
        "/api/v1/namespaces/default/secrets/old",
        "",
        "",
    )
    .await;
    assert_eq!(c, 200);
    assert!(b.contains(VALUE_B64));
}

#[tokio::test]
async fn rekey_uses_first_key() {
    let dir = tmp("rekey");
    let db = dir.join("store.redb");
    let old = keyfile(&dir, "old");
    {
        let s = open(&db, Some(&old));
        put_secret(&s, "a");
    }
    let both = dir.join("both");
    Keyring::generate_file(&both, "key2").unwrap();
    let mut text = std::fs::read_to_string(&both).unwrap();
    text.push_str(&std::fs::read_to_string(&old).unwrap());
    std::fs::write(&both, text).unwrap();
    {
        let s = open(&db, Some(&both));
        let r = s.reseal(true).unwrap();
        assert_eq!((r.rewritten, r.unreadable), (1, 0));
    }
    let s = open(&db, Some(&old));
    assert_eq!(s.get("secrets/default/a").unwrap().len(), 0);
    drop(s);
    let s = open(&db, Some(&both));
    assert!(contains(&s.get("secrets/default/a").unwrap(), VALUE_B64));
}

#[tokio::test]
async fn wrong_key_or_aad_returns_500_without_data() {
    let dir = tmp("wrong");
    let db = dir.join("store.redb");
    let key = keyfile(&dir, "key");
    {
        let s = open(&db, Some(&key));
        put_secret(&s, "a");
    }
    {
        let s = open(&db, None);
        let raw = s.get("secrets/default/a").unwrap();
        s.put("secrets/default/moved", |_| raw.clone());
    }
    {
        let addr = start(open(&db, Some(&key))).await;
        let (c, b) = call(addr, "GET", "/api/v1/namespaces/default/secrets/a", "", "").await;
        assert_eq!(c, 200);
        assert!(b.contains(VALUE_B64));
        let (c, b) = call(
            addr,
            "GET",
            "/api/v1/namespaces/default/secrets/moved",
            "",
            "",
        )
        .await;
        assert_eq!(c, 500);
        assert!(!b.contains(VALUE_B64) && b.contains("InternalError"));
    }
}

#[tokio::test]
async fn other_key_returns_500() {
    let dir = tmp("other");
    let db = dir.join("store.redb");
    {
        let s = open(&db, Some(&keyfile(&dir, "a")));
        put_secret(&s, "a");
    }
    let addr = start(open(&db, Some(&keyfile(&dir, "b")))).await;
    for path in [
        "/api/v1/namespaces/default/secrets/a",
        "/api/v1/namespaces/default/secrets",
    ] {
        let (c, b) = call(addr, "GET", path, "", "").await;
        assert_eq!(c, 500);
        assert!(!b.contains(VALUE_B64));
    }
    let (c, b) = call(
        addr,
        "PATCH",
        "/api/v1/namespaces/default/secrets/a",
        "application/merge-patch+json",
        r#"{"metadata":{"labels":{"x":"y"}}}"#,
    )
    .await;
    assert_eq!(c, 500);
    assert!(!b.contains(VALUE_B64));
}

#[test]
fn insecure_or_corrupt_key_file_is_rejected() {
    use std::os::unix::fs::PermissionsExt;
    let dir = tmp("perm");
    let p = keyfile(&dir, "key");
    std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o644)).unwrap();
    let e = Keyring::from_file(&p).err().unwrap().to_string();
    assert!(e.contains("0600"), "{e}");
    let bad = dir.join("bad");
    std::fs::write(&bad, "key1:not-base64\n").unwrap();
    std::fs::set_permissions(&bad, std::fs::Permissions::from_mode(0o600)).unwrap();
    assert!(Keyring::from_file(&bad).is_err());
}