rust-template-foundation 0.10.0

Shared infrastructure for projects spawned from rust-template.
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
//! Integration tests for the foundation server infrastructure.
//!
//! Uses `Server::into_test_router()` + `tower::ServiceExt::oneshot`
//! to drive requests without binding a real listener.

#![cfg(feature = "auth")]
// Helpers (test_router_*, request body extraction, etc.) sit outside
// `#[test]` functions, so `allow-unwrap-in-tests` does not cover them
// — opt the whole file in explicitly.
#![allow(clippy::unwrap_used, clippy::expect_used)]

mod helpers;

use axum::{
  body::Body,
  http::{Request, StatusCode},
};
use rust_template_foundation::server::health::HealthRegistry;
use rust_template_foundation::server::runner::{
  BaseServerState, Server, ServerRunConfig,
};
use std::sync::Arc;
use tower::ServiceExt;

// ── helpers ─────────────────────────────────────────────────────────────────

fn base_state_no_auth() -> BaseServerState {
  let registry = prometheus::Registry::new();
  let request_counter = prometheus::IntCounterVec::new(
    prometheus::Opts::new(
      "http_requests_total",
      "Total HTTP requests by method and status",
    ),
    &["method", "status"],
  )
  .expect("counter creation");
  registry
    .register(Box::new(request_counter.clone()))
    .expect("counter registration");

  BaseServerState {
    health_registry: HealthRegistry::default(),
    metrics_registry: Arc::new(registry),
    request_counter,
    oidc_client: None,
    frontend_path: None,
  }
}

fn base_state_with_auth() -> BaseServerState {
  let mut state = base_state_no_auth();
  state.oidc_client = Some(helpers::stub_oidc_client());
  state
}

fn test_config(app_name: &str) -> ServerRunConfig {
  ServerRunConfig {
    app_name: app_name.to_string(),
    listen_address: "127.0.0.1:0".parse().unwrap(),
    frontend_path: None,
    base_url: "https://example.com".to_string(),
    oidc: None,
  }
}

fn server_no_auth() -> Server {
  Server::new(base_state_no_auth(), test_config("test-app"))
}

fn server_with_auth() -> Server {
  Server::new(base_state_with_auth(), test_config("test-app"))
}

async fn body_string(body: Body) -> String {
  let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
  String::from_utf8(bytes.to_vec()).unwrap()
}

// ── healthz ─────────────────────────────────────────────────────────────────

#[tokio::test]
async fn healthz_returns_ok() {
  let app = server_no_auth().into_test_router();
  let resp = app
    .oneshot(
      Request::builder()
        .uri("/healthz")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();

  assert_eq!(resp.status(), StatusCode::OK);
  let body = body_string(resp.into_body()).await;
  assert!(body.contains("healthy"));
}

// ── metrics ─────────────────────────────────────────────────────────────────

#[tokio::test]
async fn metrics_returns_prometheus_text() {
  let app = server_no_auth().into_test_router();
  let resp = app
    .oneshot(
      Request::builder()
        .uri("/metrics")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();

  assert_eq!(resp.status(), StatusCode::OK);
  // IntCounterVec only appears in output after at least one label
  // combination is observed.  The request-counting middleware has not
  // fired here, so the counter is absent — we just verify the
  // endpoint returns 200 with a valid (possibly empty) response.
}

// ── OpenAPI ─────────────────────────────────────────────────────────────────

#[tokio::test]
async fn openapi_documents_healthz_and_metrics() {
  let app = server_no_auth().into_test_router();
  let resp = app
    .oneshot(
      Request::builder()
        .uri("/api-docs/openapi.json")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();

  assert_eq!(resp.status(), StatusCode::OK);
  let body = body_string(resp.into_body()).await;
  assert!(body.contains("openapi"), "should be an OpenAPI spec");
  assert!(body.contains("/healthz"), "spec should document /healthz");
  assert!(body.contains("/metrics"), "spec should document /metrics");
}

// ── Scalar UI ───────────────────────────────────────────────────────────────

#[tokio::test]
async fn scalar_ui_serves_html() {
  let app = server_no_auth().into_test_router();
  let resp = app
    .oneshot(
      Request::builder()
        .uri("/scalar")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();

  assert_eq!(resp.status(), StatusCode::OK);
  let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
    .await
    .unwrap();
  assert!(
    body.starts_with(b"<!doctype html>")
      || body.starts_with(b"<!DOCTYPE html>"),
    "Scalar endpoint should return HTML"
  );
}

// ── /me endpoint ────────────────────────────────────────────────────────────

#[tokio::test]
async fn me_returns_admin_when_no_oidc() {
  let app = server_no_auth().into_test_router();
  let resp = app
    .oneshot(Request::builder().uri("/me").body(Body::empty()).unwrap())
    .await
    .unwrap();

  assert_eq!(resp.status(), StatusCode::OK);
  let body = body_string(resp.into_body()).await;
  let json: serde_json::Value = serde_json::from_str(&body).unwrap();
  assert_eq!(json["name"], "admin");
  assert_eq!(json["auth_enabled"], false);
}

#[tokio::test]
async fn me_returns_anonymous_with_oidc_no_session() {
  let app = server_with_auth().into_test_router();
  let resp = app
    .oneshot(Request::builder().uri("/me").body(Body::empty()).unwrap())
    .await
    .unwrap();

  assert_eq!(resp.status(), StatusCode::OK);
  let body = body_string(resp.into_body()).await;
  let json: serde_json::Value = serde_json::from_str(&body).unwrap();
  assert_eq!(json["name"], "anonymous");
  assert_eq!(json["auth_enabled"], true);
}

// ── auth routes ─────────────────────────────────────────────────────────────

#[tokio::test]
async fn auth_routes_return_404_without_oidc() {
  let app = server_no_auth().into_test_router();

  for path in ["/auth/login", "/auth/logout"] {
    let resp = app
      .clone()
      .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
      .await
      .unwrap();
    assert_eq!(
      resp.status(),
      StatusCode::NOT_FOUND,
      "expected 404 for {path} without OIDC"
    );
  }

  let resp = app
    .oneshot(
      Request::builder()
        .uri("/auth/callback?code=x&state=y")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn auth_login_redirects_with_oidc() {
  let app = server_with_auth().into_test_router();
  let resp = app
    .oneshot(
      Request::builder()
        .uri("/auth/login")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();

  assert_eq!(resp.status(), StatusCode::SEE_OTHER);
  let location = resp
    .headers()
    .get("location")
    .expect("redirect should have Location header")
    .to_str()
    .unwrap();
  assert!(
    location.contains("stub.invalid"),
    "redirect should point at the stub OIDC provider"
  );
}

// ── SPA fallback ────────────────────────────────────────────────────────────

#[tokio::test]
async fn spa_fallback_serves_index_html() {
  let frontend_dir = tempfile::tempdir().unwrap();
  std::fs::write(
    frontend_dir.path().join("index.html"),
    b"<!doctype html><title>test</title>",
  )
  .unwrap();

  let mut base = base_state_no_auth();
  base.frontend_path = Some(frontend_dir.path().to_path_buf());

  let mut config = test_config("test-spa");
  config.frontend_path = Some(frontend_dir.path().to_path_buf());

  let app = Server::new(base, config).into_test_router();

  for path in ["/some-page", "/nested/route", "/unknown"] {
    let resp = app
      .clone()
      .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
      .await
      .unwrap();
    assert_eq!(
      resp.status(),
      StatusCode::OK,
      "expected 200 for SPA path {path}"
    );
  }
}

#[tokio::test]
async fn no_spa_when_frontend_path_none() {
  let app = server_no_auth().into_test_router();
  let resp = app
    .oneshot(
      Request::builder()
        .uri("/nonexistent-path")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();

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

// ── with_state transform ────────────────────────────────────────────────────

#[tokio::test]
async fn with_state_transforms_server() {
  #[derive(Clone)]
  struct CustomState {
    base: BaseServerState,
    #[allow(dead_code)]
    custom_field: String,
  }

  rust_template_foundation::impl_server_state!(CustomState, base);

  let server = server_no_auth().with_state(|base| CustomState {
    base,
    custom_field: "test".to_string(),
  });

  let app = server.into_test_router();
  let resp = app
    .oneshot(
      Request::builder()
        .uri("/healthz")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();

  assert_eq!(resp.status(), StatusCode::OK);
}

// ── custom routes in OpenAPI ────────────────────────────────────────────────

#[tokio::test]
async fn custom_routes_appear_in_openapi() {
  use aide::axum::routing::get_with;
  use aide::transform::TransformOperation;
  use axum::Json;

  async fn custom_handler() -> Json<serde_json::Value> {
    Json(serde_json::json!({"hello": "world"}))
  }

  let server = server_no_auth().api_route(
    "/api/custom",
    get_with(custom_handler, |op: TransformOperation| {
      op.description("Custom endpoint.")
    }),
  );

  let app = server.into_test_router();

  // Verify the custom route works.
  let resp = app
    .clone()
    .oneshot(
      Request::builder()
        .uri("/api/custom")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::OK);

  // Verify it appears in OpenAPI spec.
  let resp = app
    .oneshot(
      Request::builder()
        .uri("/api-docs/openapi.json")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  let body = body_string(resp.into_body()).await;
  assert!(
    body.contains("/api/custom"),
    "OpenAPI spec should document /api/custom"
  );
}

// ── request counting ──────────────────────────────────────────────────────

#[tokio::test]
async fn request_counter_increments_with_labels() {
  let base = base_state_no_auth();
  let counter = base.request_counter.clone();
  let server = Server::new(base, test_config("test-app"));
  let app = server.into_test_router();

  // Issue a GET to /healthz.
  let resp = app
    .oneshot(
      Request::builder()
        .uri("/healthz")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::OK);

  // The counter should have been incremented for GET 200.
  let value = counter.with_label_values(&["GET", "200"]).get();
  assert_eq!(value, 1, "expected 1 request counted for GET 200, got {value}");
}

#[tokio::test]
async fn request_counter_appears_in_metrics_output() {
  let base = base_state_no_auth();
  let server = Server::new(base.clone(), test_config("test-app"));
  let app = server.into_test_router();

  // Issue a request to generate counter data.
  let resp = app
    .oneshot(
      Request::builder()
        .uri("/healthz")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  let _ = body_string(resp.into_body()).await;

  // Build a fresh router sharing the same base state (oneshot
  // consumes the service, but the registry is Arc-backed).
  let server2 = Server::new(base, test_config("test-app"));
  let app2 = server2.into_test_router();

  let resp = app2
    .oneshot(
      Request::builder()
        .uri("/metrics")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();

  let body = body_string(resp.into_body()).await;
  assert!(
    body.contains("http_requests_total"),
    "metrics should contain http_requests_total"
  );
}