use actix_web::{web, HttpResponse, Responder};
const OPENAPI_YAML: &str = include_str!("../../openapi.yaml");
#[cfg(test)]
const OPENAPI_YAML_DOCS_COPY: &str = include_str!("../../docs/assets/openapi.yaml");
#[cfg(test)]
const MCP_DOC: &str = include_str!("../../../docs/api/mcp.md");
pub async fn openapi_yaml() -> impl Responder {
HttpResponse::Ok()
.content_type("application/yaml")
.body(OPENAPI_YAML)
}
pub async fn openapi_json() -> impl Responder {
match serde_yaml_to_json(OPENAPI_YAML) {
Ok(json) => HttpResponse::Ok()
.content_type("application/json")
.body(json),
Err(e) => HttpResponse::InternalServerError().body(format!("Error: {}", e)),
}
}
pub async fn swagger_ui() -> impl Responder {
HttpResponse::Ok()
.content_type("text/html")
.body(SWAGGER_UI_HTML)
}
fn serde_yaml_to_json(yaml: &str) -> Result<String, String> {
let value: serde_json::Value =
serde_yaml::from_str(yaml).map_err(|e| format!("YAML parse error: {}", e))?;
serde_json::to_string_pretty(&value).map_err(|e| format!("JSON serialize error: {}", e))
}
pub fn configure_docs_routes(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/docs")
.route("", web::get().to(swagger_ui))
.route("/", web::get().to(swagger_ui))
.route("/openapi.yaml", web::get().to(openapi_yaml))
.route("/openapi.json", web::get().to(openapi_json)),
);
}
const SWAGGER_UI_HTML: &str = r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IronBridge API Documentation</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css">
<style>
body {
margin: 0;
padding: 0;
}
.swagger-ui .topbar {
display: none;
}
.swagger-ui .info {
margin: 20px 0;
}
.swagger-ui .info .title {
color: #3b4151;
}
.swagger-ui .info hgroup.main {
margin: 0;
}
.custom-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px 40px;
display: flex;
align-items: center;
gap: 20px;
}
.custom-header h1 {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 24px;
font-weight: 600;
}
.custom-header .version {
background: rgba(255,255,255,0.2);
padding: 4px 12px;
border-radius: 12px;
font-size: 14px;
}
.custom-header a {
color: white;
text-decoration: none;
margin-left: auto;
opacity: 0.9;
}
.custom-header a:hover {
opacity: 1;
}
</style>
</head>
<body>
<div class="custom-header">
<h1>🔗 IronBridge API</h1>
<span class="version">v2.0.0</span>
<a href="https://github.com/nervosys/IronBridge" target="_blank">GitHub →</a>
</div>
<div id="swagger-ui"></div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script>
window.onload = function() {
SwaggerUIBundle({
url: "/docs/openapi.yaml",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "BaseLayout",
defaultModelsExpandDepth: 1,
docExpansion: "list",
filter: true,
showExtensions: true,
showCommonExtensions: true,
syntaxHighlight: {
theme: "monokai"
}
});
};
</script>
</body>
</html>
"#;
#[cfg(test)]
mod tests {
use super::*;
use actix_web::{http::StatusCode, test, App};
const UNROUTED: StatusCode = StatusCode::IM_A_TEAPOT;
fn spec() -> serde_json::Value {
serde_yaml::from_str(OPENAPI_YAML).expect("openapi.yaml must parse")
}
#[test]
fn spec_parses_as_yaml_and_converts_to_json() {
let json = serde_yaml_to_json(OPENAPI_YAML).expect("spec must convert to JSON");
assert!(json.contains("\"openapi\""));
}
#[test]
fn published_docs_copy_matches_the_served_spec() {
assert_eq!(
OPENAPI_YAML, OPENAPI_YAML_DOCS_COPY,
"docs/assets/openapi.yaml has drifted from openapi.yaml; \
copy the root spec over it so the published docs match the server"
);
}
#[test]
fn every_ref_in_the_spec_resolves() {
let spec = spec();
let mut refs = Vec::new();
collect_refs(&spec, &mut refs);
assert!(!refs.is_empty(), "expected the spec to use $ref");
for r in refs {
let pointer = r.trim_start_matches('#');
assert!(
spec.pointer(pointer).is_some(),
"dangling $ref in openapi.yaml: {r}"
);
}
}
fn collect_refs(value: &serde_json::Value, out: &mut Vec<String>) {
match value {
serde_json::Value::Object(map) => {
for (k, v) in map {
if k == "$ref" {
if let Some(s) = v.as_str() {
out.push(s.to_string());
}
} else {
collect_refs(v, out);
}
}
}
serde_json::Value::Array(items) => items.iter().for_each(|v| collect_refs(v, out)),
_ => {}
}
}
#[test]
fn the_mcp_reference_documents_exactly_the_tools_that_exist() {
let registered: std::collections::BTreeSet<String> = crate::mcp::tools::list_tools()
.into_iter()
.map(|t| t.name)
.collect();
assert!(
!registered.is_empty(),
"expected the server to register tools"
);
let documented: std::collections::BTreeSet<String> = MCP_DOC
.lines()
.filter_map(|line| line.trim().strip_prefix("#### `"))
.filter_map(|rest| rest.strip_suffix("`"))
.map(str::to_string)
.collect();
let undocumented: Vec<_> = registered.difference(&documented).cloned().collect();
let invented: Vec<_> = documented.difference(®istered).cloned().collect();
assert!(
undocumented.is_empty() && invented.is_empty(),
"docs/api/mcp.md and the tool registry disagree.\n \
registered but undocumented: {undocumented:?}\n \
documented but not registered: {invented:?}"
);
}
#[test]
fn the_mcp_reference_names_the_binary_that_exists() {
assert!(
MCP_DOC.contains("ironbridge-mcp"),
"docs/api/mcp.md should name the ironbridge-mcp binary"
);
for line in MCP_DOC.lines() {
let trimmed = line.trim();
if trimmed.contains("ironbridge mcp") && !trimmed.contains("There is no") {
assert!(
trimmed.contains("no `ironbridge mcp`") || trimmed.contains("`ironbridge mcp serve`"),
"docs/api/mcp.md still instructs `ironbridge mcp`, which is not a subcommand: {trimmed}"
);
}
}
}
#[test]
fn every_tag_an_operation_uses_is_declared() {
let spec = spec();
let declared: std::collections::BTreeSet<String> = spec["tags"]
.as_array()
.map(|tags| {
tags.iter()
.filter_map(|t| t["name"].as_str().map(str::to_string))
.collect()
})
.unwrap_or_default();
assert!(!declared.is_empty(), "expected the spec to declare tags");
let mut used = std::collections::BTreeSet::new();
for (_, item) in spec["paths"].as_object().expect("paths") {
for (_, operation) in item.as_object().expect("path item") {
if let Some(tags) = operation.get("tags").and_then(|t| t.as_array()) {
used.extend(tags.iter().filter_map(|t| t.as_str().map(str::to_string)));
}
}
}
let undeclared: Vec<_> = used.difference(&declared).cloned().collect();
assert!(
undeclared.is_empty(),
"these tags are used by operations but not declared in the top-level `tags` list of openapi.yaml: {undeclared:?}"
);
}
#[tokio::test]
async fn every_documented_path_is_actually_routed() {
use crate::api::{
configure_catalog_routes, configure_dataset_routes, configure_document_routes,
configure_download_routes, configure_inbox_routes, configure_notes_routes,
configure_research_routes, configure_training_routes, AppState,
};
use crate::ChatDatabase;
use actix_web::web::Data;
let dir = tempfile::tempdir().expect("tempdir");
let db_path = dir.path().join("spec-routes.db");
let db = ChatDatabase::open(&db_path).expect("open db");
let state = Data::new(AppState::new(db, db_path));
let sync_state = Data::new(super::super::create_sync_state());
let recording_state = Data::new(super::super::create_recording_state());
let webhook_state = Data::new(std::sync::Arc::new(super::super::WebhookState::new()));
#[cfg(feature = "enterprise")]
let enterprise = super::super::EnterpriseServices::open(
&dir.path().join("spec-routes-enterprise.db"),
"http://127.0.0.1:8787",
)
.expect("open enterprise store");
let app = test::init_service(
App::new()
.app_data(state)
.app_data(sync_state)
.app_data(recording_state)
.configure(configure_inbox_routes)
.configure(configure_document_routes)
.configure(configure_dataset_routes)
.configure(configure_catalog_routes)
.configure(configure_download_routes)
.configure(configure_training_routes)
.configure(configure_research_routes)
.configure(configure_notes_routes)
.configure(super::super::configure_routes)
.configure(super::super::configure_sync_routes)
.configure(super::super::configure_auth_routes)
.configure(super::super::configure_recording_routes)
.configure(move |cfg| {
super::super::configure_webhook_routes(cfg, webhook_state.clone())
})
.configure({
#[cfg(feature = "enterprise")]
let enterprise = enterprise.clone();
move |cfg: &mut actix_web::web::ServiceConfig| {
#[cfg(feature = "enterprise")]
enterprise.configure(cfg);
#[cfg(not(feature = "enterprise"))]
let _ = cfg;
}
})
.default_service(web::to(|| async { HttpResponse::ImATeapot().finish() })),
)
.await;
let spec = spec();
let paths = spec["paths"].as_object().expect("spec has paths");
assert!(!paths.is_empty());
const TOO_EXPENSIVE_TO_PROBE: &[(&str, &str)] = &[("post", "/harvest")];
let mut unrouted = Vec::new();
let mut skipped = Vec::new();
let mut gated = Vec::new();
for (path, item) in paths {
if gated_out(item) {
gated.push(path.clone());
continue;
}
let concrete = substitute_params(path);
let prefix = mount_prefix(item);
let methods = item.as_object().expect("path item is a map");
for method in methods.keys() {
if TOO_EXPENSIVE_TO_PROBE
.iter()
.any(|(m, p)| *m == method && *p == path)
{
skipped.push(format!("{} {}", method.to_uppercase(), path));
continue;
}
let req = match method.as_str() {
"get" => test::TestRequest::get(),
"post" => test::TestRequest::post(),
"put" => test::TestRequest::put(),
"delete" => test::TestRequest::delete(),
"patch" => test::TestRequest::patch(),
_ => continue,
};
let uri = format!("{prefix}{concrete}");
let resp = test::call_service(&app, req.uri(&uri).to_request()).await;
if resp.status() == UNROUTED {
unrouted.push(format!("{} {}", method.to_uppercase(), uri));
}
}
}
assert!(
unrouted.is_empty(),
"openapi.yaml documents paths the server does not route: {unrouted:#?}\n\
Either implement them or remove them from the spec."
);
assert_eq!(
skipped.len(),
TOO_EXPENSIVE_TO_PROBE.len(),
"the skip list is stale -- it names operations the spec no longer \
documents. Skipped: {skipped:?}"
);
for (method, path) in TOO_EXPENSIVE_TO_PROBE {
assert!(
registered_in_write_routes(method, path),
"{} {path} is skipped by the probe but not registered either",
method.to_uppercase()
);
}
if cfg!(feature = "enterprise") {
assert!(
gated.is_empty(),
"enterprise is enabled, so nothing should be gated out: {gated:?}"
);
} else {
assert!(
gated.iter().all(|p| {
p.starts_with("/audit")
|| p.starts_with("/retention")
|| p.starts_with("/sso")
|| p.starts_with("/oidc")
}),
"a path outside the enterprise scopes is marked enterprise-gated: {gated:?}"
);
eprintln!(
"[spec] {} enterprise paths unprobed on this build; \
run with --features enterprise to cover them",
gated.len()
);
}
}
fn registered_in_write_routes(method: &str, path: &str) -> bool {
const SOURCE: &str = include_str!("handlers_write.rs");
let needle = format!("\"{path}\", web::{method}()");
SOURCE.contains(&needle)
}
fn gated_out(item: &serde_json::Value) -> bool {
item.get("x-ironbridge-feature").and_then(|f| f.as_str()) == Some("enterprise")
&& !cfg!(feature = "enterprise")
}
fn mount_prefix(item: &serde_json::Value) -> &'static str {
if item.get("servers").is_some() {
""
} else {
"/api"
}
}
fn substitute_params(path: &str) -> String {
let mut out = String::with_capacity(path.len());
let mut in_param = false;
for c in path.chars() {
match c {
'{' => {
in_param = true;
out.push_str("spec-probe");
}
'}' => in_param = false,
_ if in_param => {}
_ => out.push(c),
}
}
out
}
#[tokio::test]
async fn documented_response_bodies_match_what_the_server_sends() {
use crate::api::{
configure_catalog_routes, configure_dataset_routes, configure_document_routes,
configure_download_routes, configure_inbox_routes, configure_notes_routes,
configure_research_routes, configure_training_routes, AppState,
};
use crate::ChatDatabase;
use actix_web::web::Data;
let dir = tempfile::tempdir().expect("tempdir");
let db_path = dir.path().join("shapes.db");
crate::commands::create_harvest_database(&db_path).expect("harvest schema");
{
let conn = rusqlite::Connection::open(&db_path).expect("open conn");
super::super::inbox::init_inbox_tables(&conn).expect("inbox tables");
super::super::handlers_swe::init_swe_tables(&conn).expect("swe tables");
}
let db = ChatDatabase::open(&db_path).expect("open");
let state = Data::new(AppState::new(db, db_path));
let sync_state = Data::new(super::super::create_sync_state());
let recording_state = Data::new(super::super::create_recording_state());
let webhook_state = Data::new(std::sync::Arc::new(super::super::WebhookState::new()));
#[cfg(feature = "enterprise")]
let enterprise = super::super::EnterpriseServices::open(
&dir.path().join("spec-bodies-enterprise.db"),
"http://127.0.0.1:8787",
)
.expect("open enterprise store");
let app = test::init_service(
App::new()
.app_data(state)
.app_data(sync_state)
.app_data(recording_state)
.configure(configure_inbox_routes)
.configure(configure_document_routes)
.configure(configure_dataset_routes)
.configure(configure_catalog_routes)
.configure(configure_download_routes)
.configure(configure_training_routes)
.configure(configure_research_routes)
.configure(configure_notes_routes)
.configure(super::super::configure_routes)
.configure(super::super::configure_sync_routes)
.configure(super::super::configure_auth_routes)
.configure(super::super::configure_recording_routes)
.configure(move |cfg| {
super::super::configure_webhook_routes(cfg, webhook_state.clone())
})
.configure({
#[cfg(feature = "enterprise")]
let enterprise = enterprise.clone();
move |cfg: &mut actix_web::web::ServiceConfig| {
#[cfg(feature = "enterprise")]
enterprise.configure(cfg);
#[cfg(not(feature = "enterprise"))]
let _ = cfg;
}
}),
)
.await;
let spec = spec();
let paths = spec["paths"].as_object().expect("paths");
let mut problems = Vec::new();
for (path, item) in paths {
if path.contains('{') || gated_out(item) {
continue;
}
let Some(op) = item.get("get") else { continue };
let Some(schema) = op.pointer("/responses/200/content/application~1json/schema") else {
continue;
};
let uri = format!("{}{path}{}", mount_prefix(item), required_query_string(op));
let resp =
test::call_service(&app, test::TestRequest::get().uri(&uri).to_request()).await;
if resp.status() == StatusCode::UNAUTHORIZED && op.pointer("/responses/401").is_some() {
continue;
}
if resp.status() == StatusCode::SERVICE_UNAVAILABLE
&& op.pointer("/responses/503").is_some()
{
continue;
}
if op.get("x-ironbridge-probe").and_then(|v| v.as_str()) == Some("needs-network") {
continue;
}
if op.get("x-ironbridge-probe").and_then(|v| v.as_str()) == Some("needs-prior-state") {
let documented = format!("/responses/{}", resp.status().as_u16());
assert!(
op.pointer(&documented).is_some(),
"GET {uri} is marked needs-prior-state but answered {} , \
which the spec does not document",
resp.status()
);
continue;
}
if resp.status() != StatusCode::OK {
problems.push(format!("GET {uri} answered {}", resp.status()));
continue;
}
let body: serde_json::Value = match serde_json::from_slice(&test::read_body(resp).await)
{
Ok(v) => v,
Err(e) => {
problems.push(format!("GET {uri} returned unparseable JSON: {e}"));
continue;
}
};
let spec_enveloped = declares_envelope(&spec, schema);
let real_enveloped = body.get("success").is_some() && body.get("data").is_some();
if spec_enveloped != real_enveloped {
problems.push(format!(
"GET {uri}: spec says {}, server sends {}",
if spec_enveloped { "enveloped" } else { "bare" },
if real_enveloped { "enveloped" } else { "bare" },
));
continue;
}
let payload = if real_enveloped { &body["data"] } else { &body };
let documented = declared_properties(&spec, schema, spec_enveloped);
let (Some(documented), Some(actual)) = (documented, object_keys(payload)) else {
continue; };
if documented != actual {
problems.push(format!(
"GET {uri}\n spec: {}\n real: {}",
documented.join(","),
actual.join(",")
));
}
}
assert!(
problems.is_empty(),
"openapi.yaml does not describe the responses the server sends:\n {}\n\n\
A client generated from this spec fails to deserialize these.",
problems.join("\n ")
);
}
fn required_query_string(op: &serde_json::Value) -> String {
let Some(params) = op.get("parameters").and_then(|p| p.as_array()) else {
return String::new();
};
let names: Vec<&str> = params
.iter()
.filter(|p| {
p.get("in").and_then(|i| i.as_str()) == Some("query")
&& p.get("required").and_then(|r| r.as_bool()) == Some(true)
})
.filter_map(|p| p.get("name").and_then(|n| n.as_str()))
.collect();
if names.is_empty() {
return String::new();
}
format!(
"?{}",
names
.iter()
.map(|n| format!("{n}=x"))
.collect::<Vec<_>>()
.join("&")
)
}
fn object_keys(value: &serde_json::Value) -> Option<Vec<String>> {
let map = value.as_object()?;
let mut keys: Vec<String> = map.keys().cloned().collect();
keys.sort();
Some(keys)
}
fn deref<'a>(
spec: &'a serde_json::Value,
schema: &'a serde_json::Value,
) -> &'a serde_json::Value {
let mut current = schema;
for _ in 0..8 {
let Some(r) = current.get("$ref").and_then(|r| r.as_str()) else {
break;
};
match spec.pointer(r.trim_start_matches('#')) {
Some(next) => current = next,
None => break,
}
}
current
}
fn declares_envelope(spec: &serde_json::Value, schema: &serde_json::Value) -> bool {
let resolved = deref(spec, schema);
if let Some(all_of) = resolved.get("allOf").and_then(|a| a.as_array()) {
return all_of.iter().any(|s| declares_envelope(spec, s));
}
resolved
.get("properties")
.and_then(|p| p.as_object())
.is_some_and(|p| p.contains_key("success") && p.contains_key("data"))
}
fn declared_properties(
spec: &serde_json::Value,
schema: &serde_json::Value,
enveloped: bool,
) -> Option<Vec<String>> {
let resolved = deref(spec, schema);
if let Some(all_of) = resolved.get("allOf").and_then(|a| a.as_array()) {
let mut merged = serde_json::Map::new();
for member in all_of {
if let Some(props) = deref(spec, member)
.get("properties")
.and_then(|p| p.as_object())
{
for (k, v) in props {
merged.insert(k.clone(), v.clone());
}
}
}
let combined = serde_json::Value::Object(
[("properties".to_string(), serde_json::Value::Object(merged))]
.into_iter()
.collect(),
);
return declared_properties(spec, &combined, enveloped);
}
let props = resolved.get("properties")?.as_object()?;
if enveloped {
let data = props.get("data")?;
let inner = deref(spec, data);
if inner.get("type").and_then(|t| t.as_str()) == Some("array") {
return None;
}
let inner_props = inner.get("properties")?.as_object()?;
let mut keys: Vec<String> = inner_props.keys().cloned().collect();
keys.sort();
return Some(keys);
}
let mut keys: Vec<String> = props.keys().cloned().collect();
keys.sort();
Some(keys)
}
}