Skip to main content

kcode_k1_http_ese_testkit/
lib.rs

1use async_trait::async_trait;
2use axum::{
3    Router,
4    body::{Body, Bytes, to_bytes},
5    http::{
6        Method, Request, StatusCode,
7        header::{CONTENT_TYPE, HOST},
8    },
9    routing::{get, post},
10};
11use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
12use ed25519_dalek::{Signer, SigningKey};
13use kcode_k1_http::{CanonicalUsername, Config, Identity, IdentityError, IdentityProvider, K1Http};
14use kcode_k1_http_replay::{ReplayConfig, ReplayWindow};
15use kcode_k1_http_signature::{RequestBinding, encode};
16use serde_json::{Value, json};
17use sha2::{Digest, Sha256};
18use std::{path::Path, sync::Arc, time::Duration};
19use tokio::time::{sleep, timeout};
20use tower::ServiceExt;
21
22const SERVER: &str = "ese-test";
23const ORIGIN: &str = "https://k1.test";
24const HOST_VALUE: &str = "k1.test";
25
26pub trait Candidate: Send + Sync {
27    fn authenticated_routes(&self, root: &Path) -> Result<Router<()>, String>;
28}
29
30#[derive(Clone)]
31struct Provider {
32    values: Arc<Vec<(CanonicalUsername, Identity)>>,
33}
34#[async_trait]
35impl IdentityProvider for Provider {
36    async fn lookup(
37        &self,
38        username: &CanonicalUsername,
39    ) -> Result<Option<Identity>, IdentityError> {
40        Ok(self
41            .values
42            .iter()
43            .find(|(name, _)| name == username)
44            .map(|(_, value)| *value))
45    }
46}
47
48struct Response {
49    status: StatusCode,
50    body: Bytes,
51}
52impl Response {
53    fn json(&self) -> Result<Value, String> {
54        serde_json::from_slice(&self.body).map_err(|_| "HTTP ESE response is not JSON".to_owned())
55    }
56    fn error(&self, status: StatusCode, code: &str) -> Result<(), String> {
57        let value = self.json()?;
58        if self.status == status && value.get("error") == Some(&Value::String(code.to_owned())) {
59            Ok(())
60        } else {
61            Err(format!(
62                "unexpected HTTP ESE error: {} {value}",
63                self.status
64            ))
65        }
66    }
67}
68
69struct Live {
70    router: Router,
71    epoch: u64,
72    alice: SigningKey,
73}
74impl Live {
75    fn request(&self, nonce: u8, target: &str, value: Value) -> Result<Request<Body>, String> {
76        let body = serde_json::to_vec(&value).map_err(|_| "request JSON unavailable".to_owned())?;
77        signed(&self.alice, self.epoch, nonce, target, body)
78    }
79    async fn issue(&self, request: Request<Body>) -> Result<Response, String> {
80        issue(self.router.clone(), request).await
81    }
82}
83
84pub async fn verify(candidate: &dyn Candidate) -> Result<(), String> {
85    let root = tempfile::tempdir().map_err(|error| error.to_string())?;
86    let alice = SigningKey::from_bytes(&[11; 32]);
87    let bob = SigningKey::from_bytes(&[12; 32]);
88    let names = [
89        ("alice", [1; 12], alice.verifying_key().to_bytes()),
90        ("bob", [2; 12], bob.verifying_key().to_bytes()),
91    ];
92    let values = names
93        .into_iter()
94        .map(|(name, id, key)| {
95            CanonicalUsername::parse(name)
96                .map(|name| (name, Identity::new(id, key)))
97                .map_err(|_| "fixture username invalid".to_owned())
98        })
99        .collect::<Result<Vec<_>, _>>()?;
100    let replay = ReplayWindow::open(ReplayConfig {
101        epoch_file: root.path().join("epoch"),
102        max_nonces_per_epoch: 128,
103    })
104    .await
105    .map_err(|_| "HTTP replay unavailable".to_owned())?;
106    let epoch = replay
107        .current_epoch()
108        .await
109        .map_err(|_| "HTTP epoch unavailable".to_owned())?;
110    let routes = candidate.authenticated_routes(&root.path().join("candidate"))?;
111    let http = K1Http::new(
112        Config {
113            server_id: SERVER.to_owned(),
114            public_origin: ORIGIN.to_owned(),
115            max_body_bytes: usize::MAX,
116        },
117        replay,
118        Arc::new(Provider {
119            values: Arc::new(values),
120        }),
121    )
122    .map_err(|_| "HTTP configuration invalid".to_owned())?;
123    let router = http.router(post(|| async {}), get(|| async {}), routes);
124    let live = Live {
125        router,
126        epoch,
127        alice,
128    };
129    let authority = json!({"kind":"user","id":b64(&[1;12])});
130    let other = json!({"kind":"user","id":b64(&[2;12])});
131    let stream = json!({"authority":authority,"name":"titles"});
132
133    let registered = live
134        .issue(live.request(1, "/api/external-subsystems/register", stream.clone())?)
135        .await?;
136    require(registered.status == StatusCode::OK, "register failed")?;
137
138    let submit = json!({"authority":authority,"name":"titles","operation_id":b64(&[3;32]),"payload":b64(b"one")});
139    let first = live
140        .issue(live.request(2, "/api/external-subsystems/submit", submit.clone())?)
141        .await?;
142    require(first.status == StatusCode::OK, "submit failed")?;
143    let first_json = first.json()?;
144    require(
145        first_json.get("duplicate") == Some(&Value::Bool(false)),
146        "first submit was duplicate",
147    )?;
148    let progress = first_json
149        .get("progress")
150        .and_then(Value::as_str)
151        .ok_or_else(|| "submit progress missing".to_owned())?
152        .to_owned();
153
154    let duplicate = live
155        .issue(live.request(3, "/api/external-subsystems/submit", submit.clone())?)
156        .await?;
157    require(
158        duplicate.json()?.get("duplicate") == Some(&Value::Bool(true)),
159        "retry was not duplicate",
160    )?;
161    let conflict = json!({"authority":authority,"name":"titles","operation_id":b64(&[3;32]),"payload":b64(b"other")});
162    live.issue(live.request(4, "/api/external-subsystems/submit", conflict)?)
163        .await?
164        .error(
165            StatusCode::CONFLICT,
166            "external_subsystem_operation_conflict",
167        )?;
168
169    let history = json!({"authority":authority,"name":"titles","after":null});
170    let response = live
171        .issue(live.request(5, "/api/external-subsystems/history", history.clone())?)
172        .await?;
173    require(
174        response.status == StatusCode::OK
175            && response.json()?["updates"]
176                .as_array()
177                .is_some_and(|items| items.len() == 1),
178        "history was incorrect",
179    )?;
180    let invalid = json!({"authority":authority,"name":"titles","after":b64(&[99;12])});
181    live.issue(live.request(6, "/api/external-subsystems/history", invalid)?)
182        .await?
183        .error(
184            StatusCode::BAD_REQUEST,
185            "invalid_external_subsystem_progress",
186        )?;
187    let concealed = json!({"authority":other,"name":"hidden"});
188    live.issue(live.request(7, "/api/external-subsystems/register", concealed)?)
189        .await?
190        .error(StatusCode::NOT_FOUND, "external_subsystem_unavailable")?;
191    let malformed = signed(
192        &live.alice,
193        live.epoch,
194        8,
195        "/api/external-subsystems/register",
196        b"{}".to_vec(),
197    )?;
198    live.issue(malformed).await?.error(
199        StatusCode::BAD_REQUEST,
200        "invalid_external_subsystem_request",
201    )?;
202
203    let subscribe_value = json!({"authority":authority,"name":"titles","after":progress});
204    let subscribe = live.request(9, "/api/external-subsystems/subscribe", subscribe_value)?;
205    let waiting = tokio::spawn(issue(live.router.clone(), subscribe));
206    sleep(Duration::from_millis(20)).await;
207    let wake = json!({"authority":authority,"name":"titles","operation_id":b64(&[4;32]),"payload":b64(b"wake")});
208    require(
209        live.issue(live.request(10, "/api/external-subsystems/submit", wake)?)
210            .await?
211            .status
212            == StatusCode::OK,
213        "wake submit failed",
214    )?;
215    let wake_response = timeout(Duration::from_secs(5), waiting)
216        .await
217        .map_err(|_| "subscribe did not wake".to_owned())?
218        .map_err(|_| "subscribe task failed".to_owned())??;
219    require(
220        wake_response.status == StatusCode::OK
221            && wake_response.json()?["updates"]
222                .as_array()
223                .is_some_and(|items| items.len() == 1),
224        "subscribe returned wrong updates",
225    )?;
226
227    let replay_one = live.request(11, "/api/external-subsystems/history", history.clone())?;
228    let replay_two = live.request(11, "/api/external-subsystems/history", history)?;
229    require(
230        live.issue(replay_one).await?.status == StatusCode::OK,
231        "replay fixture request failed",
232    )?;
233    live.issue(replay_two)
234        .await?
235        .error(StatusCode::CONFLICT, "replay")?;
236    Ok(())
237}
238
239fn require(condition: bool, message: &str) -> Result<(), String> {
240    if condition {
241        Ok(())
242    } else {
243        Err(message.to_owned())
244    }
245}
246fn b64(bytes: &[u8]) -> String {
247    URL_SAFE_NO_PAD.encode(bytes)
248}
249fn signed(
250    key: &SigningKey,
251    epoch: u64,
252    nonce: u8,
253    target: &str,
254    body: Vec<u8>,
255) -> Result<Request<Body>, String> {
256    let username =
257        CanonicalUsername::parse("alice").map_err(|_| "fixture username invalid".to_owned())?;
258    let digest: [u8; 32] = Sha256::digest(&body).into();
259    let nonce = [nonce; 16];
260    let binding = encode(&RequestBinding {
261        server_id: SERVER,
262        public_origin: ORIGIN,
263        username: &username,
264        epoch,
265        nonce,
266        method: Method::POST.as_str(),
267        target,
268        content_type: "application/json",
269        body_sha256: digest,
270    });
271    let signature = key.sign(&binding).to_bytes();
272    Request::builder()
273        .method(Method::POST)
274        .uri(target)
275        .header(HOST, HOST_VALUE)
276        .header(CONTENT_TYPE, "application/json")
277        .header("k1-username", username.as_str())
278        .header("k1-epoch", epoch.to_string())
279        .header("k1-nonce", b64(&nonce))
280        .header("k1-body-sha256", b64(&digest))
281        .header("k1-signature", b64(&signature))
282        .body(Body::from(body))
283        .map_err(|_| "request construction failed".to_owned())
284}
285async fn issue(router: Router, request: Request<Body>) -> Result<Response, String> {
286    let response = router
287        .oneshot(request)
288        .await
289        .map_err(|_| "router unavailable".to_owned())?;
290    let status = response.status();
291    let body = to_bytes(response.into_body(), usize::MAX)
292        .await
293        .map_err(|_| "response body unavailable".to_owned())?;
294    Ok(Response { status, body })
295}
296
297#[cfg(test)]
298mod tests {
299    #[test]
300    fn package_is_bounded() {
301        let files = [
302            include_str!("../Cargo.toml"),
303            include_str!("../Documentation.md"),
304            include_str!("lib.rs"),
305        ];
306        assert!(
307            files
308                .iter()
309                .flat_map(|file| file.lines())
310                .filter(|line| !line.trim().is_empty())
311                .count()
312                < 500
313        );
314    }
315}