1use axum::{
2 Json,
3 http::{HeaderMap, HeaderValue, StatusCode, header},
4 response::{IntoResponse, Response},
5};
6use kcode_k1_access_types::{AccessId, ProfileId, TxId};
7use serde::{Deserialize, Serialize};
8
9const PROFILE_UNAVAILABLE: &str = "profile is unavailable";
10const NODE_UNAVAILABLE: &str = "node unavailable";
11
12#[derive(Debug)]
13pub struct ApiError(ErrorKind);
14
15#[derive(Debug)]
16enum ErrorKind {
17 Fixed {
18 status: StatusCode,
19 code: &'static str,
20 message: &'static str,
21 },
22 Unavailable(String),
23}
24
25impl ApiError {
26 pub fn status(&self) -> StatusCode {
27 match self.0 {
28 ErrorKind::Fixed { status, .. } => status,
29 ErrorKind::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE,
30 }
31 }
32
33 pub fn code(&self) -> &'static str {
34 match self.0 {
35 ErrorKind::Fixed { code, .. } => code,
36 ErrorKind::Unavailable(_) => "kmap_creation_unavailable",
37 }
38 }
39
40 pub fn message(&self) -> &str {
41 match &self.0 {
42 ErrorKind::Fixed { message, .. } => message,
43 ErrorKind::Unavailable(message) => message,
44 }
45 }
46}
47
48impl IntoResponse for ApiError {
49 fn into_response(self) -> Response {
50 let status = self.status();
51 let code = self.code();
52 let message = self.message().to_owned();
53 json_response(
54 status,
55 ErrorBody {
56 error: code,
57 message,
58 },
59 )
60 }
61}
62
63fn fixed(status: StatusCode, code: &'static str, message: &'static str) -> ApiError {
64 ApiError(ErrorKind::Fixed {
65 status,
66 code,
67 message,
68 })
69}
70
71fn unavailable(operation: &str, safe_child: impl AsRef<str>) -> ApiError {
72 ApiError(ErrorKind::Unavailable(format!(
73 "{operation}: {}",
74 safe_child.as_ref()
75 )))
76}
77
78pub fn malformed_input() -> ApiError {
79 fixed(
80 StatusCode::BAD_REQUEST,
81 "invalid_json",
82 "request JSON is invalid",
83 )
84}
85
86pub fn unsupported_media_type() -> ApiError {
87 fixed(
88 StatusCode::UNSUPPORTED_MEDIA_TYPE,
89 "unsupported_media_type",
90 "content type must be application/json",
91 )
92}
93
94pub fn invalid_authority_filter() -> ApiError {
95 fixed(
96 StatusCode::BAD_REQUEST,
97 "invalid_authority_filter_id",
98 "authority filter ID is invalid",
99 )
100}
101
102pub fn authority_filter_not_found() -> ApiError {
103 fixed(
104 StatusCode::NOT_FOUND,
105 "authority_filter_not_found",
106 "authority filter is not available",
107 )
108}
109
110pub fn access_context_dependency_error(safe_child: impl AsRef<str>) -> ApiError {
111 unavailable("access context resolution failed", safe_child)
112}
113
114pub fn blocking_task_failure() -> ApiError {
115 ApiError(ErrorKind::Unavailable(
116 "Kmap node creation blocking task failed".to_owned(),
117 ))
118}
119
120pub fn profile_resolution_error(safe_child: impl AsRef<str>) -> ApiError {
121 if safe_child.as_ref() == PROFILE_UNAVAILABLE {
122 fixed(
123 StatusCode::NOT_FOUND,
124 "profile_not_found",
125 "profile is not available",
126 )
127 } else {
128 unavailable("Kmap profile resolution failed", safe_child)
129 }
130}
131
132pub fn creation_error(safe_child: impl AsRef<str>) -> ApiError {
133 match safe_child.as_ref() {
134 PROFILE_UNAVAILABLE => fixed(
135 StatusCode::NOT_FOUND,
136 "profile_not_found",
137 "profile is not available",
138 ),
139 NODE_UNAVAILABLE => fixed(
140 StatusCode::NOT_FOUND,
141 "node_not_found",
142 "node is not available",
143 ),
144 _ => unavailable("Kmap node creation failed", safe_child),
145 }
146}
147
148#[derive(Clone, Debug, Eq, PartialEq)]
149pub struct CreateNode {
150 title: String,
151 navigation_hint: String,
152 narrative: String,
153 connections: Vec<AccessId>,
154}
155
156impl CreateNode {
157 pub fn title(&self) -> &str {
158 &self.title
159 }
160
161 pub fn navigation_hint(&self) -> &str {
162 &self.navigation_hint
163 }
164
165 pub fn narrative(&self) -> &str {
166 &self.narrative
167 }
168
169 pub fn connections(&self) -> &[AccessId] {
170 &self.connections
171 }
172
173 pub fn into_parts(self) -> (String, String, String, Vec<AccessId>) {
174 (
175 self.title,
176 self.navigation_hint,
177 self.narrative,
178 self.connections,
179 )
180 }
181}
182
183#[derive(Deserialize)]
184#[serde(deny_unknown_fields)]
185struct CreateWire {
186 title: String,
187 navigation_hint: String,
188 narrative: String,
189 connections: Vec<String>,
190}
191
192#[derive(Serialize)]
193struct CreatedBody {
194 node_id: String,
195}
196
197#[derive(Serialize)]
198struct ErrorBody {
199 error: &'static str,
200 message: String,
201}
202
203pub fn parse_profile_id(value: &str) -> Result<ProfileId, ApiError> {
204 parse_tx(value).map(ProfileId::new).ok_or_else(|| {
205 fixed(
206 StatusCode::BAD_REQUEST,
207 "invalid_profile_id",
208 "profile ID must be lowercase hexadecimal",
209 )
210 })
211}
212
213pub fn decode_create(headers: &HeaderMap, body: &[u8]) -> Result<CreateNode, ApiError> {
214 require_json(headers)?;
215 let wire: CreateWire = serde_json::from_slice(body).map_err(|_| malformed_input())?;
216 let connections = wire
217 .connections
218 .into_iter()
219 .map(|value| {
220 parse_tx(&value)
221 .map(AccessId::new)
222 .ok_or_else(malformed_input)
223 })
224 .collect::<Result<Vec<_>, _>>()?;
225 Ok(CreateNode {
226 title: wire.title,
227 navigation_hint: wire.navigation_hint,
228 narrative: wire.narrative,
229 connections,
230 })
231}
232
233pub fn created_response(node: AccessId) -> Response {
234 json_response(
235 StatusCode::CREATED,
236 CreatedBody {
237 node_id: node.txid().to_string(),
238 },
239 )
240}
241
242fn require_json(headers: &HeaderMap) -> Result<(), ApiError> {
243 let mut values = headers.get_all(header::CONTENT_TYPE).iter();
244 let Some(value) = values.next() else {
245 return Err(unsupported_media_type());
246 };
247 let valid = values.next().is_none()
248 && value
249 .to_str()
250 .ok()
251 .and_then(|raw| raw.split(';').next())
252 .is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json"));
253 if valid {
254 Ok(())
255 } else {
256 Err(unsupported_media_type())
257 }
258}
259
260fn parse_tx(value: &str) -> Option<TxId> {
261 if value.len() != 24
262 || !value
263 .bytes()
264 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
265 {
266 return None;
267 }
268 let mut bytes = [0; 12];
269 for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
270 bytes[index] = nibble(pair[0])? << 4 | nibble(pair[1])?;
271 }
272 Some(TxId::from_bytes(bytes))
273}
274
275fn nibble(byte: u8) -> Option<u8> {
276 match byte {
277 b'0'..=b'9' => Some(byte - b'0'),
278 b'a'..=b'f' => Some(byte - b'a' + 10),
279 _ => None,
280 }
281}
282
283fn json_response<T: Serialize>(status: StatusCode, value: T) -> Response {
284 let mut response = (status, Json(value)).into_response();
285 response
286 .headers_mut()
287 .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
288 response
289}
290
291#[cfg(test)]
292mod tests {
293 use axum::{
294 body::to_bytes,
295 http::{HeaderMap, HeaderValue, StatusCode, header},
296 response::{IntoResponse, Response},
297 };
298
299 use super::*;
300
301 const FIRST: &str = "00112233445566778899aabb";
302 const SECOND: &str = "ffeeddccbbaa998877665544";
303
304 fn headers(values: &[&'static str]) -> HeaderMap {
305 let mut headers = HeaderMap::new();
306 for value in values {
307 headers.append(header::CONTENT_TYPE, HeaderValue::from_static(value));
308 }
309 headers
310 }
311
312 fn body(title: &str, connections: &[&str]) -> Vec<u8> {
313 serde_json::to_vec(&serde_json::json!({
314 "title": title,
315 "navigation_hint": " keep hint ",
316 "narrative": "\nkeep narrative\n",
317 "connections": connections,
318 }))
319 .unwrap()
320 }
321
322 async fn assert_response(response: Response, status: StatusCode, expected: &str) {
323 assert_eq!(response.status(), status);
324 assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
325 assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json");
326 let bytes = to_bytes(response.into_body(), 4096).await.unwrap();
327 assert_eq!(std::str::from_utf8(&bytes).unwrap(), expected);
328 }
329
330 #[test]
331 fn profile_and_connection_ids_are_canonical() {
332 assert_eq!(
333 parse_profile_id(FIRST)
334 .ok()
335 .map(|id| id.txid().to_string())
336 .as_deref(),
337 Some(FIRST)
338 );
339 for invalid in [
340 "00112233445566778899aabB",
341 "00112233445566778899aab",
342 "00112233445566778899aabb0",
343 "00112233445566778899aabg",
344 ] {
345 assert!(parse_profile_id(invalid).is_err());
346 assert!(
347 decode_create(&headers(&["application/json"]), &body("x", &[invalid])).is_err()
348 );
349 }
350 }
351
352 #[test]
353 fn content_type_requires_one_json_media_type() {
354 let valid_body = body("x", &[]);
355 for value in [
356 "application/json",
357 "Application/JSON",
358 "application/json; charset=utf-8",
359 " APPLICATION/JSON ; q=anything",
360 ] {
361 assert!(decode_create(&headers(&[value]), &valid_body).is_ok());
362 }
363 for values in [
364 Vec::<&'static str>::new(),
365 vec!["text/json"],
366 vec!["application/jsonx"],
367 vec!["application/json", "application/json"],
368 ] {
369 let error = decode_create(&headers(&values), &valid_body).unwrap_err();
370 assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
371 }
372 }
373
374 #[test]
375 fn json_shape_is_strict_and_text_and_connections_are_preserved() {
376 let json = headers(&["application/json"]);
377 for invalid in [
378 br#"{}"#.as_slice(),
379 br#"{"title":"x","navigation_hint":"y","narrative":"z"}"#,
380 br#"{"title":"x","navigation_hint":"y","narrative":"z","connections":[],"extra":1}"#,
381 br#"{"title":"x","title":"y","navigation_hint":"z","narrative":"n","connections":[]}"#,
382 br#"{"title":"x","navigation_hint":"y","narrative":"z","connections":[]} trailing"#,
383 br#"{"title":1,"navigation_hint":"y","narrative":"z","connections":[]}"#,
384 ] {
385 let error = decode_create(&json, invalid).unwrap_err();
386 assert_eq!(error.status(), StatusCode::BAD_REQUEST);
387 }
388 let long = format!(" {} ", "界".repeat(2000));
389 let decoded = decode_create(&json, &body(&long, &[SECOND, FIRST, SECOND])).unwrap();
390 assert_eq!(decoded.title(), long);
391 assert_eq!(decoded.navigation_hint(), " keep hint ");
392 assert_eq!(decoded.narrative(), "\nkeep narrative\n");
393 assert_eq!(
394 decoded
395 .connections()
396 .iter()
397 .map(|id| id.txid().to_string())
398 .collect::<Vec<_>>(),
399 [SECOND, FIRST, SECOND]
400 );
401 let (title, hint, narrative, connections) = decoded.into_parts();
402 assert_eq!(title, long);
403 assert_eq!(hint, " keep hint ");
404 assert_eq!(narrative, "\nkeep narrative\n");
405 assert_eq!(connections.len(), 3);
406 }
407
408 #[tokio::test]
409 async fn created_response_is_exact() {
410 let node = AccessId::new(parse_profile_id(FIRST).unwrap().txid());
411 assert_response(
412 created_response(node),
413 StatusCode::CREATED,
414 r#"{"node_id":"00112233445566778899aabb"}"#,
415 )
416 .await;
417 }
418
419 #[tokio::test]
420 async fn every_error_mapping_is_exact_and_no_store() {
421 let cases = vec![
422 (
423 parse_profile_id("x").unwrap_err(),
424 StatusCode::BAD_REQUEST,
425 r#"{"error":"invalid_profile_id","message":"profile ID must be lowercase hexadecimal"}"#,
426 ),
427 (
428 malformed_input(),
429 StatusCode::BAD_REQUEST,
430 r#"{"error":"invalid_json","message":"request JSON is invalid"}"#,
431 ),
432 (
433 invalid_authority_filter(),
434 StatusCode::BAD_REQUEST,
435 r#"{"error":"invalid_authority_filter_id","message":"authority filter ID is invalid"}"#,
436 ),
437 (
438 authority_filter_not_found(),
439 StatusCode::NOT_FOUND,
440 r#"{"error":"authority_filter_not_found","message":"authority filter is not available"}"#,
441 ),
442 (
443 unsupported_media_type(),
444 StatusCode::UNSUPPORTED_MEDIA_TYPE,
445 r#"{"error":"unsupported_media_type","message":"content type must be application/json"}"#,
446 ),
447 (
448 access_context_dependency_error("filter store: unavailable"),
449 StatusCode::SERVICE_UNAVAILABLE,
450 r#"{"error":"kmap_creation_unavailable","message":"access context resolution failed: filter store: unavailable"}"#,
451 ),
452 (
453 blocking_task_failure(),
454 StatusCode::SERVICE_UNAVAILABLE,
455 r#"{"error":"kmap_creation_unavailable","message":"Kmap node creation blocking task failed"}"#,
456 ),
457 (
458 creation_error("storage unavailable"),
459 StatusCode::SERVICE_UNAVAILABLE,
460 r#"{"error":"kmap_creation_unavailable","message":"Kmap node creation failed: storage unavailable"}"#,
461 ),
462 ];
463 for (error, status, expected) in cases {
464 assert_response(error.into_response(), status, expected).await;
465 }
466 }
467
468 #[tokio::test]
469 async fn concealment_matches_only_complete_child_leaves() {
470 let exact = [
471 (
472 profile_resolution_error(PROFILE_UNAVAILABLE),
473 r#"{"error":"profile_not_found","message":"profile is not available"}"#,
474 ),
475 (
476 creation_error(PROFILE_UNAVAILABLE),
477 r#"{"error":"profile_not_found","message":"profile is not available"}"#,
478 ),
479 (
480 creation_error(NODE_UNAVAILABLE),
481 r#"{"error":"node_not_found","message":"node is not available"}"#,
482 ),
483 ];
484 for (error, expected) in exact {
485 assert_response(error.into_response(), StatusCode::NOT_FOUND, expected).await;
486 }
487 let wrapped = [
488 profile_resolution_error("outer: profile is unavailable"),
489 creation_error("outer: profile is unavailable"),
490 creation_error("outer: node unavailable"),
491 ];
492 for error in wrapped {
493 assert_eq!(error.status(), StatusCode::SERVICE_UNAVAILABLE);
494 let response = error.into_response();
495 assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
496 }
497 }
498
499 #[test]
500 fn complete_package_stays_below_the_managed_limit() {
501 let files = [
502 include_str!("../Cargo.toml"),
503 include_str!("../Documentation.md"),
504 include_str!("lib.rs"),
505 ];
506 let count = files
507 .iter()
508 .flat_map(|file| file.lines())
509 .filter(|line| !line.trim().is_empty())
510 .count();
511 assert!(count < 500, "complete package has {count} nonblank lines");
512 }
513}