lenso-api 0.1.4

HTTP API host crate for the Lenso backend framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use axum::body::{Body, to_bytes};
use axum::http::{Request, StatusCode};
use lenso_api::{build_router, openapi_document};
use platform_core::{
    AppConfig, AppContext, LoggingEventPublisher, ModuleConfig, ModuleSourcesConfig,
};
use platform_module::{ModuleHttpMethod, ModuleManifest, ModuleSource};
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, OnceLock};
use tower::ServiceExt;

fn app_config_with_default_modules() -> AppConfig {
    let mut config = AppConfig::from_env();
    // ponytail: route/profile tests assert built-in module state, not local .env toggles.
    config.module_sources = ModuleSourcesConfig::default();
    config.modules.clear();
    config
}

#[test]
fn openapi_contains_auth_dev_session_contract() {
    let document = openapi_document();
    let value = serde_json::to_value(&document).expect("OpenAPI document should serialize");

    let operation = &value["paths"]["/v1/auth/dev/sessions"]["post"];
    assert_eq!(operation["operationId"], "auth_create_dev_session");
    assert_eq!(
        operation["requestBody"]["content"]["application/json"]["schema"]["$ref"],
        "#/components/schemas/CreateDevSessionRequest"
    );
    assert_eq!(
        operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"],
        "#/components/schemas/CreateDevSessionResponse"
    );

    for status in ["400", "403", "500"] {
        assert_eq!(
            operation["responses"][status]["content"]["application/json"]["schema"]["$ref"],
            "#/components/schemas/ErrorResponse"
        );
    }

    let revoke = &value["paths"]["/v1/auth/sessions/revoke"]["post"];
    assert_eq!(revoke["operationId"], "auth_revoke_session");
    assert_eq!(
        revoke["responses"]["200"]["content"]["application/json"]["schema"]["$ref"],
        "#/components/schemas/RevokeSessionResponse"
    );

    for status in ["401", "500"] {
        assert_eq!(
            revoke["responses"][status]["content"]["application/json"]["schema"]["$ref"],
            "#/components/schemas/ErrorResponse"
        );
    }
}

#[test]
fn openapi_contains_auth_password_contract() {
    let document = openapi_document();
    let value = serde_json::to_value(&document).expect("OpenAPI document should serialize");

    let register = &value["paths"]["/v1/auth/password/register"]["post"];
    assert_eq!(register["operationId"], "auth_password_register");
    assert_eq!(
        register["requestBody"]["content"]["application/json"]["schema"]["$ref"],
        "#/components/schemas/PasswordRegisterRequest"
    );
    assert_eq!(
        register["responses"]["200"]["content"]["application/json"]["schema"]["$ref"],
        "#/components/schemas/PasswordSessionResponse"
    );

    for status in ["400", "409", "500"] {
        assert_eq!(
            register["responses"][status]["content"]["application/json"]["schema"]["$ref"],
            "#/components/schemas/ErrorResponse"
        );
    }

    let login = &value["paths"]["/v1/auth/password/login"]["post"];
    assert_eq!(login["operationId"], "auth_password_login");
    assert_eq!(
        login["requestBody"]["content"]["application/json"]["schema"]["$ref"],
        "#/components/schemas/PasswordLoginRequest"
    );
    assert_eq!(
        login["responses"]["200"]["content"]["application/json"]["schema"]["$ref"],
        "#/components/schemas/PasswordSessionResponse"
    );

    for status in ["400", "401", "500"] {
        assert_eq!(
            login["responses"][status]["content"]["application/json"]["schema"]["$ref"],
            "#/components/schemas/ErrorResponse"
        );
    }
}

#[test]
fn committed_openapi_artifact_matches_rust_source() {
    let generated =
        serde_json::to_value(openapi_document()).expect("OpenAPI document should serialize");
    let committed: serde_json::Value =
        serde_yaml::from_str(include_str!("../../../contracts/openapi/app-api.v1.yaml"))
            .expect("committed OpenAPI artifact should parse");

    assert_eq!(committed, generated);
}

#[test]
fn openapi_document_does_not_replace_default_admin_catalogs() {
    let _guard = catalog_test_lock()
        .lock()
        .expect("catalog test lock poisoned");
    platform_admin::reset_catalogs_for_test();
    platform_admin::install_default_runtime_function_declarations(vec![runtime_declaration(
        "openapi.default.sentinel",
    )]);

    let _ = openapi_document();

    assert!(
        platform_admin::runtime_function_declaration_catalog_snapshot()
            .iter()
            .any(|declaration| declaration.name == "openapi.default.sentinel")
    );
}

#[test]
fn openapi_document_does_not_replace_runtime_admin_catalogs() {
    let _guard = catalog_test_lock()
        .lock()
        .expect("catalog test lock poisoned");
    platform_admin::reset_catalogs_for_test();
    platform_admin::install_runtime_function_declarations(vec![runtime_declaration(
        "openapi.runtime.sentinel",
    )]);

    let _ = openapi_document();

    assert!(
        platform_admin::runtime_function_declaration_catalog_snapshot()
            .iter()
            .any(|declaration| declaration.name == "openapi.runtime.sentinel")
    );
}

#[test]
fn linked_module_http_routes_are_registered_in_openapi() {
    let document = openapi_document();
    let value = serde_json::to_value(&document).expect("OpenAPI document should serialize");
    let paths = value["paths"].as_object().expect("OpenAPI paths object");

    for manifest in lenso_bootstrap::module_manifests() {
        for route in manifest.http_routes {
            let path = paths.get(&route.path).unwrap_or_else(|| {
                panic!(
                    "linked module `{}` declares HTTP route `{}` but OpenAPI has no matching path",
                    manifest.name, route.path
                )
            });
            let method = openapi_method(route.method);
            assert!(
                path.get(method).is_some(),
                "linked module `{}` declares HTTP route `{} {}` but OpenAPI has no matching operation",
                manifest.name,
                method.to_uppercase(),
                route.path
            );
        }
    }
}

#[test]
fn linked_module_openapi_routes_are_declared_in_manifest() {
    let document = openapi_document();
    let value = serde_json::to_value(&document).expect("OpenAPI document should serialize");
    let paths = value["paths"].as_object().expect("OpenAPI paths object");
    let manifests = lenso_bootstrap::module_manifests();

    for owner in lenso_bootstrap::linked_http_route_owners() {
        let manifest = manifests
            .iter()
            .find(|manifest| manifest.name == owner.module_name)
            .unwrap_or_else(|| {
                panic!(
                    "linked HTTP route owner `{}` has no matching ModuleManifest",
                    owner.module_name
                )
            });
        for (path, operations) in paths {
            if !owner
                .public_prefixes
                .iter()
                .any(|prefix| path.starts_with(prefix))
            {
                continue;
            }
            for method in operations
                .as_object()
                .expect("OpenAPI path item should be an object")
                .keys()
                .filter_map(|method| module_http_method(method))
            {
                assert_manifest_declares_route(manifest, path, method);
            }
        }
    }
}

#[tokio::test]
async fn disabled_story_module_router_does_not_mount_story_routes() {
    let _guard = catalog_test_lock()
        .lock()
        .expect("catalog test lock poisoned");
    let _ = openapi_document();

    let mut config = app_config_with_default_modules();
    config.modules.insert(
        "platform-story".to_owned(),
        ModuleConfig {
            enabled: Some(false),
            values: BTreeMap::new(),
        },
    );
    let ctx = AppContext::new(
        config,
        platform_core::DbPool::connect_lazy("postgres://localhost/lenso_test")
            .expect("lazy pool should build"),
        Arc::new(LoggingEventPublisher),
    );
    let app = lenso_api::try_build_router(ctx).expect("demo profile router should build");

    let response = app
        .oneshot(
            Request::builder()
                .uri("/admin/runtime/stories")
                .method("GET")
                .body(Body::empty())
                .expect("request should build"),
        )
        .await
        .expect("request should complete");

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn served_openapi_omits_disabled_story_module_routes() {
    let _guard = catalog_test_lock()
        .lock()
        .expect("catalog test lock poisoned");
    let _ = openapi_document();

    let mut config = app_config_with_default_modules();
    config.modules.insert(
        "platform-story".to_owned(),
        ModuleConfig {
            enabled: Some(false),
            values: BTreeMap::new(),
        },
    );
    let ctx = AppContext::new(
        config,
        platform_core::DbPool::connect_lazy("postgres://localhost/lenso_test")
            .expect("lazy pool should build"),
        Arc::new(LoggingEventPublisher),
    );
    let app = lenso_api::try_build_router(ctx).expect("demo profile router should build");

    let response = app
        .oneshot(
            Request::builder()
                .uri("/openapi.json")
                .body(Body::empty())
                .expect("request should build"),
        )
        .await
        .expect("request should complete");

    assert_eq!(response.status(), StatusCode::OK);

    let bytes = to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("body should read");
    let document: serde_json::Value =
        serde_json::from_slice(&bytes).expect("served OpenAPI should be JSON");
    let paths = document["paths"]
        .as_object()
        .expect("OpenAPI paths should be an object");

    assert!(!paths.contains_key("/admin/runtime/stories"));
    assert!(!paths.contains_key("/admin/runtime/stories/{correlation_id}"));
    assert!(!paths.contains_key("/admin/runtime/stories/{correlation_id}/heatmap"));
    assert!(!paths.contains_key("/admin/runtime/stories/{correlation_id}/technical-operations"));
}

#[tokio::test]
async fn served_core_profile_openapi_omits_demo_auth_paths_after_demo_document_assembly() {
    let _guard = catalog_test_lock()
        .lock()
        .expect("catalog test lock poisoned");
    let _ = openapi_document();

    let mut config = app_config_with_default_modules();
    config.module_sources.linked_profile = "core".to_owned();
    let ctx = AppContext::new(
        config,
        platform_core::DbPool::connect_lazy("postgres://localhost/lenso_test")
            .expect("lazy pool should build"),
        Arc::new(LoggingEventPublisher),
    );
    let app = lenso_api::try_build_router(ctx).expect("core profile router should build");

    let response = app
        .oneshot(
            Request::builder()
                .uri("/openapi.json")
                .body(Body::empty())
                .expect("request should build"),
        )
        .await
        .expect("request should complete");

    assert_eq!(response.status(), StatusCode::OK);

    let bytes = to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("body should read");
    let document: serde_json::Value =
        serde_json::from_slice(&bytes).expect("served OpenAPI should be JSON");
    let paths = document["paths"]
        .as_object()
        .expect("OpenAPI paths should be an object");
    let tags = document["tags"]
        .as_array()
        .expect("OpenAPI tags should be an array");

    assert!(!paths.contains_key("/v1/auth/dev/sessions"));
    assert!(!paths.contains_key("/v1/auth/password/register"));
    assert!(!tags.iter().any(|tag| tag["name"] == "auth"));
}

#[tokio::test]
async fn served_core_profile_openapi_keeps_composed_auth_routes() {
    let _guard = catalog_test_lock()
        .lock()
        .expect("catalog test lock poisoned");
    let _ = openapi_document();

    let mut config = app_config_with_default_modules();
    config.module_sources.linked_profile = "core".to_owned();
    let ctx = AppContext::new(
        config,
        platform_core::DbPool::connect_lazy("postgres://localhost/lenso_test")
            .expect("lazy pool should build"),
        Arc::new(LoggingEventPublisher),
    );
    let composition = lenso_bootstrap::HostComposition::new()
        .with_linked_module(lenso_bootstrap::auth_linked_module())
        .with_linked_module(lenso_bootstrap::auth_password_linked_module());
    let app = lenso_api::try_build_router_with_composition(ctx, &composition)
        .expect("core profile auth composition router should build");

    let response = app
        .oneshot(
            Request::builder()
                .uri("/openapi.json")
                .body(Body::empty())
                .expect("request should build"),
        )
        .await
        .expect("request should complete");

    assert_eq!(response.status(), StatusCode::OK);

    let bytes = to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("body should read");
    let document: serde_json::Value =
        serde_json::from_slice(&bytes).expect("served OpenAPI should be JSON");
    let paths = document["paths"]
        .as_object()
        .expect("OpenAPI paths should be an object");
    let tags = document["tags"]
        .as_array()
        .expect("OpenAPI tags should be an array");

    assert!(paths.contains_key("/v1/auth/dev/sessions"));
    assert!(paths.contains_key("/v1/auth/password/register"));
    assert!(tags.iter().any(|tag| tag["name"] == "auth"));
}

fn assert_manifest_declares_route(manifest: &ModuleManifest, path: &str, method: ModuleHttpMethod) {
    assert!(
        manifest
            .http_routes
            .iter()
            .any(|route| route.path == path && route.method == method),
        "OpenAPI route `{} {}` belongs to linked module `{}` but is missing from ModuleManifest::http_routes",
        openapi_method(method).to_uppercase(),
        path,
        manifest.name
    );
}

fn openapi_method(method: ModuleHttpMethod) -> &'static str {
    match method {
        ModuleHttpMethod::Get => "get",
        ModuleHttpMethod::Post => "post",
        ModuleHttpMethod::Put => "put",
        ModuleHttpMethod::Patch => "patch",
        ModuleHttpMethod::Delete => "delete",
        _ => panic!("unsupported module HTTP method in OpenAPI guard"),
    }
}

fn module_http_method(method: &str) -> Option<ModuleHttpMethod> {
    match method {
        "get" => Some(ModuleHttpMethod::Get),
        "post" => Some(ModuleHttpMethod::Post),
        "put" => Some(ModuleHttpMethod::Put),
        "patch" => Some(ModuleHttpMethod::Patch),
        "delete" => Some(ModuleHttpMethod::Delete),
        _ => None,
    }
}

fn runtime_declaration(name: &str) -> platform_admin::AdminRuntimeFunctionDeclarationMetadata {
    platform_admin::AdminRuntimeFunctionDeclarationMetadata {
        module_name: "openapi-contract-test".to_owned(),
        module_source: ModuleSource::Linked,
        name: name.to_owned(),
        version: 1,
        queue: "openapi-contract-test".to_owned(),
        input_schema: None,
        retry_policy: None,
    }
}

fn catalog_test_lock() -> &'static Mutex<()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
}

#[tokio::test]
async fn scalar_docs_route_serves_openapi_reference() {
    let _guard = catalog_test_lock()
        .lock()
        .expect("catalog test lock poisoned");
    let ctx = AppContext::new(
        AppConfig::from_env(),
        platform_core::DbPool::connect_lazy("postgres://localhost/lenso_test")
            .expect("lazy pool should build"),
        Arc::new(LoggingEventPublisher),
    );
    let app = build_router(ctx);

    let response = app
        .oneshot(
            Request::builder()
                .uri("/docs")
                .body(Body::empty())
                .expect("request should build"),
        )
        .await
        .expect("request should complete");

    assert_eq!(response.status(), StatusCode::OK);

    let content_type = response
        .headers()
        .get(axum::http::header::CONTENT_TYPE)
        .expect("docs response should include content type")
        .to_str()
        .expect("content type should be valid");
    assert!(content_type.starts_with("text/html"));

    let bytes = to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("body should read");
    let body = String::from_utf8(bytes.to_vec()).expect("body should be utf-8");

    assert!(body.contains("@scalar/api-reference"));
    assert!(body.contains("url: \"/openapi.json\""));
}