use axum::{
Json,
http::{HeaderMap, HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
};
use kcode_k1_access_types::{AccessId, ProfileId, TxId};
use serde::{Deserialize, Serialize};
const PROFILE_UNAVAILABLE: &str = "profile is unavailable";
const NODE_UNAVAILABLE: &str = "node unavailable";
#[derive(Debug)]
pub struct ApiError(ErrorKind);
#[derive(Debug)]
enum ErrorKind {
Fixed {
status: StatusCode,
code: &'static str,
message: &'static str,
},
Unavailable(String),
}
impl ApiError {
pub fn status(&self) -> StatusCode {
match self.0 {
ErrorKind::Fixed { status, .. } => status,
ErrorKind::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE,
}
}
pub fn code(&self) -> &'static str {
match self.0 {
ErrorKind::Fixed { code, .. } => code,
ErrorKind::Unavailable(_) => "kmap_creation_unavailable",
}
}
pub fn message(&self) -> &str {
match &self.0 {
ErrorKind::Fixed { message, .. } => message,
ErrorKind::Unavailable(message) => message,
}
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let status = self.status();
let code = self.code();
let message = self.message().to_owned();
json_response(
status,
ErrorBody {
error: code,
message,
},
)
}
}
fn fixed(status: StatusCode, code: &'static str, message: &'static str) -> ApiError {
ApiError(ErrorKind::Fixed {
status,
code,
message,
})
}
fn unavailable(operation: &str, safe_child: impl AsRef<str>) -> ApiError {
ApiError(ErrorKind::Unavailable(format!(
"{operation}: {}",
safe_child.as_ref()
)))
}
pub fn malformed_input() -> ApiError {
fixed(
StatusCode::BAD_REQUEST,
"invalid_json",
"request JSON is invalid",
)
}
pub fn unsupported_media_type() -> ApiError {
fixed(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"unsupported_media_type",
"content type must be application/json",
)
}
pub fn invalid_authority_filter() -> ApiError {
fixed(
StatusCode::BAD_REQUEST,
"invalid_authority_filter_id",
"authority filter ID is invalid",
)
}
pub fn authority_filter_not_found() -> ApiError {
fixed(
StatusCode::NOT_FOUND,
"authority_filter_not_found",
"authority filter is not available",
)
}
pub fn access_context_dependency_error(safe_child: impl AsRef<str>) -> ApiError {
unavailable("access context resolution failed", safe_child)
}
pub fn blocking_task_failure() -> ApiError {
ApiError(ErrorKind::Unavailable(
"Kmap node creation blocking task failed".to_owned(),
))
}
pub fn profile_resolution_error(safe_child: impl AsRef<str>) -> ApiError {
if safe_child.as_ref() == PROFILE_UNAVAILABLE {
fixed(
StatusCode::NOT_FOUND,
"profile_not_found",
"profile is not available",
)
} else {
unavailable("Kmap profile resolution failed", safe_child)
}
}
pub fn creation_error(safe_child: impl AsRef<str>) -> ApiError {
match safe_child.as_ref() {
PROFILE_UNAVAILABLE => fixed(
StatusCode::NOT_FOUND,
"profile_not_found",
"profile is not available",
),
NODE_UNAVAILABLE => fixed(
StatusCode::NOT_FOUND,
"node_not_found",
"node is not available",
),
_ => unavailable("Kmap node creation failed", safe_child),
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CreateNode {
title: String,
navigation_hint: String,
narrative: String,
connections: Vec<AccessId>,
}
impl CreateNode {
pub fn title(&self) -> &str {
&self.title
}
pub fn navigation_hint(&self) -> &str {
&self.navigation_hint
}
pub fn narrative(&self) -> &str {
&self.narrative
}
pub fn connections(&self) -> &[AccessId] {
&self.connections
}
pub fn into_parts(self) -> (String, String, String, Vec<AccessId>) {
(
self.title,
self.navigation_hint,
self.narrative,
self.connections,
)
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CreateWire {
title: String,
navigation_hint: String,
narrative: String,
connections: Vec<String>,
}
#[derive(Serialize)]
struct CreatedBody {
node_id: String,
}
#[derive(Serialize)]
struct ErrorBody {
error: &'static str,
message: String,
}
pub fn parse_profile_id(value: &str) -> Result<ProfileId, ApiError> {
parse_tx(value).map(ProfileId::new).ok_or_else(|| {
fixed(
StatusCode::BAD_REQUEST,
"invalid_profile_id",
"profile ID must be lowercase hexadecimal",
)
})
}
pub fn decode_create(headers: &HeaderMap, body: &[u8]) -> Result<CreateNode, ApiError> {
require_json(headers)?;
let wire: CreateWire = serde_json::from_slice(body).map_err(|_| malformed_input())?;
let connections = wire
.connections
.into_iter()
.map(|value| {
parse_tx(&value)
.map(AccessId::new)
.ok_or_else(malformed_input)
})
.collect::<Result<Vec<_>, _>>()?;
Ok(CreateNode {
title: wire.title,
navigation_hint: wire.navigation_hint,
narrative: wire.narrative,
connections,
})
}
pub fn created_response(node: AccessId) -> Response {
json_response(
StatusCode::CREATED,
CreatedBody {
node_id: node.txid().to_string(),
},
)
}
fn require_json(headers: &HeaderMap) -> Result<(), ApiError> {
let mut values = headers.get_all(header::CONTENT_TYPE).iter();
let Some(value) = values.next() else {
return Err(unsupported_media_type());
};
let valid = values.next().is_none()
&& value
.to_str()
.ok()
.and_then(|raw| raw.split(';').next())
.is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json"));
if valid {
Ok(())
} else {
Err(unsupported_media_type())
}
}
fn parse_tx(value: &str) -> Option<TxId> {
if value.len() != 24
|| !value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
{
return None;
}
let mut bytes = [0; 12];
for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
bytes[index] = nibble(pair[0])? << 4 | nibble(pair[1])?;
}
Some(TxId::from_bytes(bytes))
}
fn nibble(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
_ => None,
}
}
fn json_response<T: Serialize>(status: StatusCode, value: T) -> Response {
let mut response = (status, Json(value)).into_response();
response
.headers_mut()
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
response
}
#[cfg(test)]
mod tests {
use axum::{
body::to_bytes,
http::{HeaderMap, HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
};
use super::*;
const FIRST: &str = "00112233445566778899aabb";
const SECOND: &str = "ffeeddccbbaa998877665544";
fn headers(values: &[&'static str]) -> HeaderMap {
let mut headers = HeaderMap::new();
for value in values {
headers.append(header::CONTENT_TYPE, HeaderValue::from_static(value));
}
headers
}
fn body(title: &str, connections: &[&str]) -> Vec<u8> {
serde_json::to_vec(&serde_json::json!({
"title": title,
"navigation_hint": " keep hint ",
"narrative": "\nkeep narrative\n",
"connections": connections,
}))
.unwrap()
}
async fn assert_response(response: Response, status: StatusCode, expected: &str) {
assert_eq!(response.status(), status);
assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json");
let bytes = to_bytes(response.into_body(), 4096).await.unwrap();
assert_eq!(std::str::from_utf8(&bytes).unwrap(), expected);
}
#[test]
fn profile_and_connection_ids_are_canonical() {
assert_eq!(
parse_profile_id(FIRST)
.ok()
.map(|id| id.txid().to_string())
.as_deref(),
Some(FIRST)
);
for invalid in [
"00112233445566778899aabB",
"00112233445566778899aab",
"00112233445566778899aabb0",
"00112233445566778899aabg",
] {
assert!(parse_profile_id(invalid).is_err());
assert!(
decode_create(&headers(&["application/json"]), &body("x", &[invalid])).is_err()
);
}
}
#[test]
fn content_type_requires_one_json_media_type() {
let valid_body = body("x", &[]);
for value in [
"application/json",
"Application/JSON",
"application/json; charset=utf-8",
" APPLICATION/JSON ; q=anything",
] {
assert!(decode_create(&headers(&[value]), &valid_body).is_ok());
}
for values in [
Vec::<&'static str>::new(),
vec!["text/json"],
vec!["application/jsonx"],
vec!["application/json", "application/json"],
] {
let error = decode_create(&headers(&values), &valid_body).unwrap_err();
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
}
}
#[test]
fn json_shape_is_strict_and_text_and_connections_are_preserved() {
let json = headers(&["application/json"]);
for invalid in [
br#"{}"#.as_slice(),
br#"{"title":"x","navigation_hint":"y","narrative":"z"}"#,
br#"{"title":"x","navigation_hint":"y","narrative":"z","connections":[],"extra":1}"#,
br#"{"title":"x","title":"y","navigation_hint":"z","narrative":"n","connections":[]}"#,
br#"{"title":"x","navigation_hint":"y","narrative":"z","connections":[]} trailing"#,
br#"{"title":1,"navigation_hint":"y","narrative":"z","connections":[]}"#,
] {
let error = decode_create(&json, invalid).unwrap_err();
assert_eq!(error.status(), StatusCode::BAD_REQUEST);
}
let long = format!(" {} ", "界".repeat(2000));
let decoded = decode_create(&json, &body(&long, &[SECOND, FIRST, SECOND])).unwrap();
assert_eq!(decoded.title(), long);
assert_eq!(decoded.navigation_hint(), " keep hint ");
assert_eq!(decoded.narrative(), "\nkeep narrative\n");
assert_eq!(
decoded
.connections()
.iter()
.map(|id| id.txid().to_string())
.collect::<Vec<_>>(),
[SECOND, FIRST, SECOND]
);
let (title, hint, narrative, connections) = decoded.into_parts();
assert_eq!(title, long);
assert_eq!(hint, " keep hint ");
assert_eq!(narrative, "\nkeep narrative\n");
assert_eq!(connections.len(), 3);
}
#[tokio::test]
async fn created_response_is_exact() {
let node = AccessId::new(parse_profile_id(FIRST).unwrap().txid());
assert_response(
created_response(node),
StatusCode::CREATED,
r#"{"node_id":"00112233445566778899aabb"}"#,
)
.await;
}
#[tokio::test]
async fn every_error_mapping_is_exact_and_no_store() {
let cases = vec![
(
parse_profile_id("x").unwrap_err(),
StatusCode::BAD_REQUEST,
r#"{"error":"invalid_profile_id","message":"profile ID must be lowercase hexadecimal"}"#,
),
(
malformed_input(),
StatusCode::BAD_REQUEST,
r#"{"error":"invalid_json","message":"request JSON is invalid"}"#,
),
(
invalid_authority_filter(),
StatusCode::BAD_REQUEST,
r#"{"error":"invalid_authority_filter_id","message":"authority filter ID is invalid"}"#,
),
(
authority_filter_not_found(),
StatusCode::NOT_FOUND,
r#"{"error":"authority_filter_not_found","message":"authority filter is not available"}"#,
),
(
unsupported_media_type(),
StatusCode::UNSUPPORTED_MEDIA_TYPE,
r#"{"error":"unsupported_media_type","message":"content type must be application/json"}"#,
),
(
access_context_dependency_error("filter store: unavailable"),
StatusCode::SERVICE_UNAVAILABLE,
r#"{"error":"kmap_creation_unavailable","message":"access context resolution failed: filter store: unavailable"}"#,
),
(
blocking_task_failure(),
StatusCode::SERVICE_UNAVAILABLE,
r#"{"error":"kmap_creation_unavailable","message":"Kmap node creation blocking task failed"}"#,
),
(
creation_error("storage unavailable"),
StatusCode::SERVICE_UNAVAILABLE,
r#"{"error":"kmap_creation_unavailable","message":"Kmap node creation failed: storage unavailable"}"#,
),
];
for (error, status, expected) in cases {
assert_response(error.into_response(), status, expected).await;
}
}
#[tokio::test]
async fn concealment_matches_only_complete_child_leaves() {
let exact = [
(
profile_resolution_error(PROFILE_UNAVAILABLE),
r#"{"error":"profile_not_found","message":"profile is not available"}"#,
),
(
creation_error(PROFILE_UNAVAILABLE),
r#"{"error":"profile_not_found","message":"profile is not available"}"#,
),
(
creation_error(NODE_UNAVAILABLE),
r#"{"error":"node_not_found","message":"node is not available"}"#,
),
];
for (error, expected) in exact {
assert_response(error.into_response(), StatusCode::NOT_FOUND, expected).await;
}
let wrapped = [
profile_resolution_error("outer: profile is unavailable"),
creation_error("outer: profile is unavailable"),
creation_error("outer: node unavailable"),
];
for error in wrapped {
assert_eq!(error.status(), StatusCode::SERVICE_UNAVAILABLE);
let response = error.into_response();
assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
}
}
#[test]
fn complete_package_stays_below_the_managed_limit() {
let files = [
include_str!("../Cargo.toml"),
include_str!("../Documentation.md"),
include_str!("lib.rs"),
];
let count = files
.iter()
.flat_map(|file| file.lines())
.filter(|line| !line.trim().is_empty())
.count();
assert!(count < 500, "complete package has {count} nonblank lines");
}
}