kcode-k1-http-ese-testkit 0.1.0

Signed HTTP conformance suite for K1 external subsystems
Documentation
use async_trait::async_trait;
use axum::{
    Router,
    body::{Body, Bytes, to_bytes},
    http::{
        Method, Request, StatusCode,
        header::{CONTENT_TYPE, HOST},
    },
    routing::{get, post},
};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use ed25519_dalek::{Signer, SigningKey};
use kcode_k1_http::{CanonicalUsername, Config, Identity, IdentityError, IdentityProvider, K1Http};
use kcode_k1_http_replay::{ReplayConfig, ReplayWindow};
use kcode_k1_http_signature::{RequestBinding, encode};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{path::Path, sync::Arc, time::Duration};
use tokio::time::{sleep, timeout};
use tower::ServiceExt;

const SERVER: &str = "ese-test";
const ORIGIN: &str = "https://k1.test";
const HOST_VALUE: &str = "k1.test";

pub trait Candidate: Send + Sync {
    fn authenticated_routes(&self, root: &Path) -> Result<Router<()>, String>;
}

#[derive(Clone)]
struct Provider {
    values: Arc<Vec<(CanonicalUsername, Identity)>>,
}
#[async_trait]
impl IdentityProvider for Provider {
    async fn lookup(
        &self,
        username: &CanonicalUsername,
    ) -> Result<Option<Identity>, IdentityError> {
        Ok(self
            .values
            .iter()
            .find(|(name, _)| name == username)
            .map(|(_, value)| *value))
    }
}

struct Response {
    status: StatusCode,
    body: Bytes,
}
impl Response {
    fn json(&self) -> Result<Value, String> {
        serde_json::from_slice(&self.body).map_err(|_| "HTTP ESE response is not JSON".to_owned())
    }
    fn error(&self, status: StatusCode, code: &str) -> Result<(), String> {
        let value = self.json()?;
        if self.status == status && value.get("error") == Some(&Value::String(code.to_owned())) {
            Ok(())
        } else {
            Err(format!(
                "unexpected HTTP ESE error: {} {value}",
                self.status
            ))
        }
    }
}

struct Live {
    router: Router,
    epoch: u64,
    alice: SigningKey,
}
impl Live {
    fn request(&self, nonce: u8, target: &str, value: Value) -> Result<Request<Body>, String> {
        let body = serde_json::to_vec(&value).map_err(|_| "request JSON unavailable".to_owned())?;
        signed(&self.alice, self.epoch, nonce, target, body)
    }
    async fn issue(&self, request: Request<Body>) -> Result<Response, String> {
        issue(self.router.clone(), request).await
    }
}

pub async fn verify(candidate: &dyn Candidate) -> Result<(), String> {
    let root = tempfile::tempdir().map_err(|error| error.to_string())?;
    let alice = SigningKey::from_bytes(&[11; 32]);
    let bob = SigningKey::from_bytes(&[12; 32]);
    let names = [
        ("alice", [1; 12], alice.verifying_key().to_bytes()),
        ("bob", [2; 12], bob.verifying_key().to_bytes()),
    ];
    let values = names
        .into_iter()
        .map(|(name, id, key)| {
            CanonicalUsername::parse(name)
                .map(|name| (name, Identity::new(id, key)))
                .map_err(|_| "fixture username invalid".to_owned())
        })
        .collect::<Result<Vec<_>, _>>()?;
    let replay = ReplayWindow::open(ReplayConfig {
        epoch_file: root.path().join("epoch"),
        max_nonces_per_epoch: 128,
    })
    .await
    .map_err(|_| "HTTP replay unavailable".to_owned())?;
    let epoch = replay
        .current_epoch()
        .await
        .map_err(|_| "HTTP epoch unavailable".to_owned())?;
    let routes = candidate.authenticated_routes(&root.path().join("candidate"))?;
    let http = K1Http::new(
        Config {
            server_id: SERVER.to_owned(),
            public_origin: ORIGIN.to_owned(),
            max_body_bytes: usize::MAX,
        },
        replay,
        Arc::new(Provider {
            values: Arc::new(values),
        }),
    )
    .map_err(|_| "HTTP configuration invalid".to_owned())?;
    let router = http.router(post(|| async {}), get(|| async {}), routes);
    let live = Live {
        router,
        epoch,
        alice,
    };
    let authority = json!({"kind":"user","id":b64(&[1;12])});
    let other = json!({"kind":"user","id":b64(&[2;12])});
    let stream = json!({"authority":authority,"name":"titles"});

    let registered = live
        .issue(live.request(1, "/api/external-subsystems/register", stream.clone())?)
        .await?;
    require(registered.status == StatusCode::OK, "register failed")?;

    let submit = json!({"authority":authority,"name":"titles","operation_id":b64(&[3;32]),"payload":b64(b"one")});
    let first = live
        .issue(live.request(2, "/api/external-subsystems/submit", submit.clone())?)
        .await?;
    require(first.status == StatusCode::OK, "submit failed")?;
    let first_json = first.json()?;
    require(
        first_json.get("duplicate") == Some(&Value::Bool(false)),
        "first submit was duplicate",
    )?;
    let progress = first_json
        .get("progress")
        .and_then(Value::as_str)
        .ok_or_else(|| "submit progress missing".to_owned())?
        .to_owned();

    let duplicate = live
        .issue(live.request(3, "/api/external-subsystems/submit", submit.clone())?)
        .await?;
    require(
        duplicate.json()?.get("duplicate") == Some(&Value::Bool(true)),
        "retry was not duplicate",
    )?;
    let conflict = json!({"authority":authority,"name":"titles","operation_id":b64(&[3;32]),"payload":b64(b"other")});
    live.issue(live.request(4, "/api/external-subsystems/submit", conflict)?)
        .await?
        .error(
            StatusCode::CONFLICT,
            "external_subsystem_operation_conflict",
        )?;

    let history = json!({"authority":authority,"name":"titles","after":null});
    let response = live
        .issue(live.request(5, "/api/external-subsystems/history", history.clone())?)
        .await?;
    require(
        response.status == StatusCode::OK
            && response.json()?["updates"]
                .as_array()
                .is_some_and(|items| items.len() == 1),
        "history was incorrect",
    )?;
    let invalid = json!({"authority":authority,"name":"titles","after":b64(&[99;12])});
    live.issue(live.request(6, "/api/external-subsystems/history", invalid)?)
        .await?
        .error(
            StatusCode::BAD_REQUEST,
            "invalid_external_subsystem_progress",
        )?;
    let concealed = json!({"authority":other,"name":"hidden"});
    live.issue(live.request(7, "/api/external-subsystems/register", concealed)?)
        .await?
        .error(StatusCode::NOT_FOUND, "external_subsystem_unavailable")?;
    let malformed = signed(
        &live.alice,
        live.epoch,
        8,
        "/api/external-subsystems/register",
        b"{}".to_vec(),
    )?;
    live.issue(malformed).await?.error(
        StatusCode::BAD_REQUEST,
        "invalid_external_subsystem_request",
    )?;

    let subscribe_value = json!({"authority":authority,"name":"titles","after":progress});
    let subscribe = live.request(9, "/api/external-subsystems/subscribe", subscribe_value)?;
    let waiting = tokio::spawn(issue(live.router.clone(), subscribe));
    sleep(Duration::from_millis(20)).await;
    let wake = json!({"authority":authority,"name":"titles","operation_id":b64(&[4;32]),"payload":b64(b"wake")});
    require(
        live.issue(live.request(10, "/api/external-subsystems/submit", wake)?)
            .await?
            .status
            == StatusCode::OK,
        "wake submit failed",
    )?;
    let wake_response = timeout(Duration::from_secs(5), waiting)
        .await
        .map_err(|_| "subscribe did not wake".to_owned())?
        .map_err(|_| "subscribe task failed".to_owned())??;
    require(
        wake_response.status == StatusCode::OK
            && wake_response.json()?["updates"]
                .as_array()
                .is_some_and(|items| items.len() == 1),
        "subscribe returned wrong updates",
    )?;

    let replay_one = live.request(11, "/api/external-subsystems/history", history.clone())?;
    let replay_two = live.request(11, "/api/external-subsystems/history", history)?;
    require(
        live.issue(replay_one).await?.status == StatusCode::OK,
        "replay fixture request failed",
    )?;
    live.issue(replay_two)
        .await?
        .error(StatusCode::CONFLICT, "replay")?;
    Ok(())
}

fn require(condition: bool, message: &str) -> Result<(), String> {
    if condition {
        Ok(())
    } else {
        Err(message.to_owned())
    }
}
fn b64(bytes: &[u8]) -> String {
    URL_SAFE_NO_PAD.encode(bytes)
}
fn signed(
    key: &SigningKey,
    epoch: u64,
    nonce: u8,
    target: &str,
    body: Vec<u8>,
) -> Result<Request<Body>, String> {
    let username =
        CanonicalUsername::parse("alice").map_err(|_| "fixture username invalid".to_owned())?;
    let digest: [u8; 32] = Sha256::digest(&body).into();
    let nonce = [nonce; 16];
    let binding = encode(&RequestBinding {
        server_id: SERVER,
        public_origin: ORIGIN,
        username: &username,
        epoch,
        nonce,
        method: Method::POST.as_str(),
        target,
        content_type: "application/json",
        body_sha256: digest,
    });
    let signature = key.sign(&binding).to_bytes();
    Request::builder()
        .method(Method::POST)
        .uri(target)
        .header(HOST, HOST_VALUE)
        .header(CONTENT_TYPE, "application/json")
        .header("k1-username", username.as_str())
        .header("k1-epoch", epoch.to_string())
        .header("k1-nonce", b64(&nonce))
        .header("k1-body-sha256", b64(&digest))
        .header("k1-signature", b64(&signature))
        .body(Body::from(body))
        .map_err(|_| "request construction failed".to_owned())
}
async fn issue(router: Router, request: Request<Body>) -> Result<Response, String> {
    let response = router
        .oneshot(request)
        .await
        .map_err(|_| "router unavailable".to_owned())?;
    let status = response.status();
    let body = to_bytes(response.into_body(), usize::MAX)
        .await
        .map_err(|_| "response body unavailable".to_owned())?;
    Ok(Response { status, body })
}

#[cfg(test)]
mod tests {
    #[test]
    fn package_is_bounded() {
        let files = [
            include_str!("../Cargo.toml"),
            include_str!("../Documentation.md"),
            include_str!("lib.rs"),
        ];
        assert!(
            files
                .iter()
                .flat_map(|file| file.lines())
                .filter(|line| !line.trim().is_empty())
                .count()
                < 500
        );
    }
}