manta-server 2.0.0-beta.62

Manta HTTP server — single API that proxies to CSM / Ochami backends.
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! SAT-file HTTP handlers.
//!
//! Per-element endpoints. The CLI's `apply_sat_file` plan builder
//! (in `manta-cli`, not reachable as an intra-doc link from here)
//! produces a typed sequence of elements; its dispatcher walks the
//! plan and POSTs each element to the section-specific endpoint here.
//!
//! Configuration + session-template entries take one call each:
//!
//! - `POST /api/v1/sat-file/configurations` →
//!   [`post_sat_configuration`] — Body: [`PostSatConfigurationRequest`];
//!   response: a `CfsConfigurationResponse` as JSON.
//! - `POST /api/v1/sat-file/session-templates` →
//!   [`post_sat_session_template`] — Body:
//!   [`PostSatSessionTemplateRequest`]; response:
//!   [`PostSatSessionTemplateResponse`].
//!
//! Image entries are split across three calls so the CLI can monitor
//! the build instead of blocking on one long server round-trip:
//!
//! - `POST /api/v1/sat-file/images/cfs-session` →
//!   [`post_sat_image_cfs_session`] — translate one `images[]` entry
//!   into a CFS session payload and create it. Body:
//!   [`CreateImageCfsSessionRequest`]; response: the freshly-created
//!   [`CfsSessionGetResponse`] (still pending/running).
//! - Monitor via the existing `GET /sessions?name=…` or
//!   `GET /sessions/{name}/logs` (SSE) endpoints — the CLI picks
//!   which based on `--watch-logs`.
//! - `POST /api/v1/sat-file/images/stamp` → [`post_sat_image_stamp`] —
//!   once the session is terminal-complete, the server fetches it,
//!   derives `manta.image_session.{base,groups,configuration}`, and
//!   PATCHes them onto the produced IMS image. Body:
//!   [`StampImageFromSessionRequest`]; response: the patched [`Image`].
//!   Fails fast with 400 when the session produced no `result_id`.
//!
//! The CLI deserialises each response and pretty-prints the assembled
//! four-list summary, so any rename of a field on either side of the
//! wire is user-visible. The wire-format-lock tests at the bottom of
//! this module catch that drift; mirror them when you add a new field.
//!
//! Each handler calls the matching function in
//! `crate::service::sat_file`, which enforces the CLAUDE.md boundary
//! rule (handlers → service → backend).

use axum::{Json, http::StatusCode, response::IntoResponse};
use manta_backend_dispatcher::types::bos::session::{
  BosSession, Operation as BosOperation,
};
use manta_backend_dispatcher::types::cfs::session::CfsSessionGetResponse;
use manta_backend_dispatcher::types::ims::Image;

use crate::service::authorization::validate_user_group_vec_access;

use super::{
  ErrorResponse, RequestCtx, SiteHeader, require_k8s_url, require_vault,
  to_handler_error,
};

// ---------------------------------------------------------------------------
// POST /api/v1/sat-file/configurations — Apply one SAT configuration entry
// ---------------------------------------------------------------------------

pub use manta_shared::types::api::sat_file::{
  CreateImageCfsSessionRequest, PostSatConfigurationRequest,
  PostSatSessionTemplateRequest, PostSatSessionTemplateResponse,
  StampImageFromSessionRequest,
};

#[utoipa::path(post, path = "/sat-file/configurations", tag = "sat-file",
  params(SiteHeader),
  request_body = PostSatConfigurationRequest,
  security(("bearerAuth" = [])),
  responses(
    // CfsConfigurationResponse lives in manta-backend-dispatcher (third-party,
    // no ToSchema)kept as Value until upstream derives it.
    (status = 200, description = "Configuration applied",       body = serde_json::Value),
    (status = 401, description = "Unauthorized",                body = ErrorResponse),
    (status = 500, description = "Internal error",              body = ErrorResponse),
    (status = 501, description = "Vault or k8s not configured", body = ErrorResponse),
  )
)]
/// `POST /api/v1/sat-file/configurations` — apply a single SAT
/// configuration entry. Returns the created `CfsConfigurationResponse`.
#[tracing::instrument(skip_all)]
pub async fn post_sat_configuration(
  ctx: RequestCtx,
  Json(body): Json<PostSatConfigurationRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
  tracing::info!("post_sat_configuration dry_run={}", body.dry_run);
  let infra = ctx.infra();

  let vault_base_url = require_vault(infra.vault_base_url)?;
  let k8s_api_url = require_k8s_url(infra.k8s_api_url)?;

  let gitea_token =
    crate::server::common::vault::http_client::get_shasta_vcs_token(
      &ctx.token,
      vault_base_url,
      infra.site_name,
    )
    .await
    .map_err(to_handler_error)?;

  // CFS configurations are not HSM-group-scoped — the SAT
  // `configurations[]` entry only carries name + layers (git URL,
  // branch, playbook), with no group field. Access control here
  // relies on the backend's RBAC layer (CSM/OCHAMI), matching the
  // convention used for other non-group-scoped handlers (see
  // ARCHITECTURE.md "Security model").
  let cfg = crate::service::sat_file::apply_configuration(
    &infra,
    &ctx.token,
    vault_base_url,
    k8s_api_url,
    &gitea_token,
    body.configuration,
    body.dry_run,
    body.overwrite,
  )
  .await
  .map_err(to_handler_error)?;

  Ok(Json(cfg))
}

// ---------------------------------------------------------------------------
// POST /api/v1/sat-file/images/cfs-session — Create the CFS session that
// will build the image, but do not wait for it or stamp the result. The
// CLI drives the monitor + stamp steps via the existing session endpoints
// and the companion `/sat-file/images/stamp` endpoint below.
// ---------------------------------------------------------------------------

#[utoipa::path(post, path = "/sat-file/images/cfs-session", tag = "sat-file",
  params(SiteHeader),
  request_body = CreateImageCfsSessionRequest,
  security(("bearerAuth" = [])),
  responses(
    // CfsSessionGetResponse lives in manta-backend-dispatcher (third-party,
    // no ToSchema)kept as Value until upstream derives it.
    (status = 201, description = "CFS session created",         body = serde_json::Value),
    (status = 401, description = "Unauthorized",                body = ErrorResponse),
    (status = 500, description = "Internal error",              body = ErrorResponse),
    (status = 501, description = "Vault or k8s not configured", body = ErrorResponse),
  )
)]
/// `POST /api/v1/sat-file/images/cfs-session` — translate one SAT
/// `images[]` entry into a CFS session payload and create it. Returns
/// the freshly-created [`CfsSessionGetResponse`] so the CLI can drive
/// the monitor + stamp steps itself.
#[tracing::instrument(skip_all)]
pub async fn post_sat_image_cfs_session(
  ctx: RequestCtx,
  Json(body): Json<CreateImageCfsSessionRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
  tracing::info!("post_sat_image_cfs_session dry_run={}", body.dry_run);
  let infra = ctx.infra();

  let vault_base_url = require_vault(infra.vault_base_url)?;
  let k8s_api_url = require_k8s_url(infra.k8s_api_url)?;

  let target_groups =
    crate::service::sat_groups::extract_image_groups(&body.image);

  validate_user_group_vec_access(&infra, &ctx.token, &target_groups)
    .await
    .map_err(to_handler_error)?;

  let session = crate::service::sat_file::create_image_cfs_session(
    &infra,
    &ctx.token,
    vault_base_url,
    k8s_api_url,
    body.image,
    body.ref_lookup,
    body.ansible_verbosity,
    body.ansible_passthrough.as_deref(),
    body.dry_run,
  )
  .await
  .map_err(to_handler_error)?;

  Ok((StatusCode::CREATED, Json::<CfsSessionGetResponse>(session)))
}

// ---------------------------------------------------------------------------
// POST /api/v1/sat-file/images/stamp — Given a (terminal-complete) CFS
// session name, fetch it, derive `manta.image_session.{base,groups,
// configuration}` from it, and PATCH them onto the IMS image the session
// produced. Fails fast when the session has no result image.
// ---------------------------------------------------------------------------

#[utoipa::path(post, path = "/sat-file/images/stamp", tag = "sat-file",
  params(SiteHeader),
  request_body = StampImageFromSessionRequest,
  security(("bearerAuth" = [])),
  responses(
    // Image (IMS) lives in manta-backend-dispatcher (third-party,
    // no ToSchema) — kept as Value until upstream derives it.
    (status = 200, description = "Image stamped",               body = serde_json::Value),
    (status = 400, description = "Session not complete / no image", body = ErrorResponse),
    (status = 401, description = "Unauthorized",                body = ErrorResponse),
    (status = 500, description = "Internal error",              body = ErrorResponse),
  )
)]
/// `POST /api/v1/sat-file/images/stamp` — fetch the named CFS session,
/// derive the provenance stamp, and PATCH the produced IMS image.
///
/// Performs two boundary checks before delegating to the backend:
/// the caller must have access to every HSM group the session
/// targets, and the session must have produced a result image. See
/// [`crate::service::session::validate_session_access`] +
/// [`crate::service::session::require_result_image`].
#[tracing::instrument(skip_all)]
pub async fn post_sat_image_stamp(
  ctx: RequestCtx,
  Json(body): Json<StampImageFromSessionRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
  tracing::info!("post_sat_image_stamp cfs_session={}", body.cfs_session_name);
  let infra = ctx.infra();

  let session = crate::service::session::validate_session_access(
    &infra,
    &ctx.token,
    &body.cfs_session_name,
  )
  .await
  .map_err(to_handler_error)?;

  crate::service::session::require_result_image(&session)
    .map_err(to_handler_error)?;

  let image = crate::service::sat_file::stamp_image_from_session(
    &infra,
    &ctx.token,
    &body.cfs_session_name,
  )
  .await
  .map_err(to_handler_error)?;

  Ok(Json::<Image>(image))
}

// ---------------------------------------------------------------------------
// POST /api/v1/sat-file/session-templates — Apply one SAT session_template
// ---------------------------------------------------------------------------

#[utoipa::path(post, path = "/sat-file/session-templates", tag = "sat-file",
  params(SiteHeader),
  request_body = PostSatSessionTemplateRequest,
  security(("bearerAuth" = [])),
  responses(
    (status = 200, description = "Session template applied", body = PostSatSessionTemplateResponse),
    (status = 401, description = "Unauthorized",             body = ErrorResponse),
    (status = 500, description = "Internal error",           body = ErrorResponse),
  )
)]
/// `POST /api/v1/sat-file/session-templates` — apply a single SAT
/// session_template entry. Returns the created BOS session template
/// and (if `create_bos_session` was set and we're not in dry-run) the
/// BOS session that was created from the new template to boot the
/// targeted nodes through it.
#[tracing::instrument(skip_all)]
pub async fn post_sat_session_template(
  ctx: RequestCtx,
  Json(body): Json<PostSatSessionTemplateRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
  tracing::info!(
    "post_sat_session_template dry_run={} create_bos_session={}",
    body.dry_run,
    body.create_bos_session
  );
  let infra = ctx.infra();

  let target_groups =
    crate::service::sat_groups::extract_session_template_groups(
      &body.session_template,
    );

  // Group access validation and the backend call are consolidated in
  // the service function: it fetches the available-group list once,
  // validates inline (non-admin callers), and forwards the list to the
  // backend — eliminating the duplicate get_group_name_available fetch
  // that previously appeared here.
  let (template, session) = crate::service::sat_file::apply_session_template(
    &infra,
    &ctx.token,
    body.session_template,
    body.ref_lookup,
    &target_groups,
    body.create_bos_session,
    body.dry_run,
  )
  .await
  .map_err(to_handler_error)?;

  // Dry-run + create_bos_session: the backend has returned a mock
  // template but no session (it never actually created one). Synthesise
  // a mock session so the client can review the BOS session that *would*
  // have been kicked off. The mock has no status — it never ran — and
  // its name is prefixed with "dry-run-" to make accidental confusion
  // with a real persisted session impossible.
  let session = match session {
    Some(s) => {
      tracing::debug!(
        "backend returned a session (dry_run={}, create_bos_session={})",
        body.dry_run,
        body.create_bos_session
      );
      Some(s)
    }
    None if body.dry_run && body.create_bos_session => {
      let mock = mock_bos_session_for_template(&template);
      tracing::info!(
        "Synthesising mock BOS session for dry-run preview (name={:?}, template={})",
        mock.name,
        mock.template_name
      );
      Some(mock)
    }
    None => {
      tracing::debug!(
        "no session returned (backend=None, dry_run={}, create_bos_session={})",
        body.dry_run,
        body.create_bos_session
      );
      None
    }
  };

  Ok(Json(PostSatSessionTemplateResponse { template, session }))
}

/// Build a `BosSession` that mirrors what a real session created from
/// `template` would look like, for dry-run preview only. The session
/// carries no `Status` (it never ran), and its `name` is prefixed with
/// `"dry-run-"` so a consumer can't mistake it for a persisted CSM
/// session.
fn mock_bos_session_for_template(
  template: &manta_backend_dispatcher::types::bos::session_template::BosSessionTemplate,
) -> BosSession {
  let template_name = template
    .name
    .clone()
    .unwrap_or_else(|| "<unnamed>".to_string());
  BosSession {
    name: Some(format!("dry-run-{template_name}")),
    tenant: None,
    operation: Some(BosOperation::Reboot),
    template_name,
    limit: None,
    stage: None,
    components: None,
    include_disabled: None,
    status: None,
  }
}

#[cfg(test)]
mod tests {
  //! Locks the JSON wire format of the per-element request/response
  //! types. The CLI builds the request JSON literally and pretty-prints
  //! each response verbatim, so renames or reordering here would break
  //! the wire boundary.

  use super::{
    CreateImageCfsSessionRequest, PostSatConfigurationRequest,
    PostSatSessionTemplateRequest, PostSatSessionTemplateResponse,
    StampImageFromSessionRequest,
  };

  /// Lock the shape of the CLI's POST /sat-file/configurations body.
  /// Catches renames on either side of the wire.
  #[test]
  fn cli_configuration_body_deserialises() {
    let cli_body = serde_json::json!({
      "configuration": { "name": "cfg-v1", "layers": [] },
      "overwrite": true,
      "dry_run": false,
    });
    let req: PostSatConfigurationRequest =
      serde_json::from_value(cli_body).unwrap();
    assert_eq!(req.configuration["name"].as_str(), Some("cfg-v1"));
    assert!(req.overwrite);
    assert!(!req.dry_run);
  }

  /// Minimal configuration body — only `configuration` is required; the
  /// two booleans default to `false`.
  #[test]
  fn cli_configuration_body_with_defaults_deserialises() {
    let cli_body = serde_json::json!({
      "configuration": { "name": "cfg-v1" },
    });
    let req: PostSatConfigurationRequest =
      serde_json::from_value(cli_body).unwrap();
    assert!(!req.overwrite);
    assert!(!req.dry_run);
  }

  /// Lock the shape of the CLI's POST /sat-file/images/cfs-session body.
  #[test]
  fn cli_create_image_cfs_session_body_deserialises() {
    let cli_body = serde_json::json!({
      "image": { "name": "img-v1", "ref_name": "base", "configuration": "cfg-v1" },
      "ref_lookup": { "earlier-ref": "abc-123" },
      "ansible_verbosity": 3,
      "ansible_passthrough": "--check",
      "dry_run": false,
    });
    let req: CreateImageCfsSessionRequest =
      serde_json::from_value(cli_body).unwrap();
    assert_eq!(req.image["name"].as_str(), Some("img-v1"));
    assert_eq!(
      req.ref_lookup.get("earlier-ref").map(String::as_str),
      Some("abc-123")
    );
    assert_eq!(req.ansible_verbosity, Some(3));
    assert_eq!(req.ansible_passthrough.as_deref(), Some("--check"));
    assert!(!req.dry_run);
  }

  /// Minimal create-session body — only `image` is required.
  #[test]
  fn cli_create_image_cfs_session_body_with_defaults_deserialises() {
    let cli_body = serde_json::json!({ "image": { "name": "img-v1" } });
    let req: CreateImageCfsSessionRequest =
      serde_json::from_value(cli_body).unwrap();
    assert!(req.ref_lookup.is_empty());
    assert_eq!(req.ansible_verbosity, None);
    assert_eq!(req.ansible_passthrough, None);
    assert!(!req.dry_run);
  }

  /// Lock the shape of the CLI's POST /sat-file/images/stamp body —
  /// just the CFS session name.
  #[test]
  fn cli_stamp_image_body_deserialises() {
    let cli_body = serde_json::json!({ "cfs_session_name": "sat-img-v1" });
    let req: StampImageFromSessionRequest =
      serde_json::from_value(cli_body).unwrap();
    assert_eq!(req.cfs_session_name, "sat-img-v1");
  }

  /// Lock the shape of the CLI's POST /sat-file/session-templates body.
  #[test]
  fn cli_session_template_body_deserialises() {
    let cli_body = serde_json::json!({
      "session_template": { "name": "st-1", "image": { "image_ref": "base" }, "configuration": "cfg-v1" },
      "ref_lookup": { "base": "image-xyz" },
      "create_bos_session": true,
      "dry_run": false,
    });
    let req: PostSatSessionTemplateRequest =
      serde_json::from_value(cli_body).unwrap();
    assert_eq!(req.session_template["name"].as_str(), Some("st-1"));
    assert_eq!(
      req.ref_lookup.get("base").map(String::as_str),
      Some("image-xyz")
    );
    assert!(req.create_bos_session);
    assert!(!req.dry_run);
  }

  /// Lock the shape of the session_template response body —
  /// `{ template, session? }`. The CLI's dispatcher reads these
  /// two fields by name.
  #[test]
  fn session_template_response_serialises_with_template_and_optional_session() {
    use manta_backend_dispatcher::types::bos::session_template::BosSessionTemplate;

    let body = PostSatSessionTemplateResponse {
      template: BosSessionTemplate {
        name: Some("st-1".to_string()),
        tenant: None,
        description: None,
        enable_cfs: Some(true),
        cfs: None,
        boot_sets: None,
        links: None,
      },
      session: None,
    };
    let v: serde_json::Value = serde_json::to_value(&body).unwrap();
    let obj = v.as_object().expect("object");
    assert!(obj.contains_key("template"));
    assert!(obj.contains_key("session"));
    assert_eq!(obj["template"]["name"].as_str(), Some("st-1"));
    assert!(obj["session"].is_null());
  }

  /// Mock BOS session for dry-run + create_bos_session: name carries
  /// the `dry-run-` prefix, the operation is Reboot, the template_name
  /// follows the template, and no Status is attached (the session
  /// never ran).
  #[test]
  fn dry_run_mock_bos_session_for_template_shape() {
    use manta_backend_dispatcher::types::bos::session_template::BosSessionTemplate;

    let template = BosSessionTemplate {
      name: Some("st-42".to_string()),
      tenant: None,
      description: None,
      enable_cfs: None,
      cfs: None,
      boot_sets: None,
      links: None,
    };
    let session = super::mock_bos_session_for_template(&template);
    assert_eq!(session.name.as_deref(), Some("dry-run-st-42"));
    assert_eq!(session.template_name, "st-42");
    assert!(session.status.is_none());
    assert!(matches!(
      session.operation,
      Some(super::BosOperation::Reboot)
    ));
  }

  /// Template with no name → mock falls back to `<unnamed>` so the
  /// session shape is still valid (template_name is required on
  /// BosSession).
  #[test]
  fn dry_run_mock_handles_unnamed_template() {
    use manta_backend_dispatcher::types::bos::session_template::BosSessionTemplate;

    let template = BosSessionTemplate {
      name: None,
      tenant: None,
      description: None,
      enable_cfs: None,
      cfs: None,
      boot_sets: None,
      links: None,
    };
    let session = super::mock_bos_session_for_template(&template);
    assert_eq!(session.template_name, "<unnamed>");
    assert_eq!(session.name.as_deref(), Some("dry-run-<unnamed>"));
  }
}