heldar-kernel 0.2.0

Heldar kernel — media/DVR control plane, perception ingest + sampler, zone engine, auth, and the worker SDK contract. The open, domain-agnostic platform that domain apps build on.
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
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! Backup subsystem API: destinations, scheduled policies, the job ledger, and on-demand archive
//! export.
//!
//! Destinations + policies are managed by manager+; their listings (with destination credentials
//! MASKED) and the job/export ledger are readable by any authenticated principal. The actual
//! transfers run in the background backup service ([`crate::services::backup`]). All mutations are
//! written to the immutable audit log.

use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::Deserialize;
use serde_json::json;
use sqlx::types::Json as SqlxJson;
use uuid::Uuid;

use crate::auth::{self, Principal};
use crate::error::{AppError, AppResult};
use crate::models::{
    ArchiveExportRequest, BackupDestination, BackupDestinationCreate, BackupDestinationUpdate,
    BackupDestinationView, BackupJob, BackupPolicy, BackupPolicyCreate, BackupPolicyUpdate,
    BackupTestResult, BACKUP_SECRET_KEYS,
};
use crate::services::backup;
use crate::state::AppState;
use crate::util;
use chrono::{DateTime, Utc};

pub fn router() -> Router<AppState> {
    Router::new()
        .route(
            "/api/v1/backup/destinations",
            get(list_destinations).post(create_destination),
        )
        .route(
            "/api/v1/backup/destinations/{id}",
            axum::routing::patch(update_destination).delete(delete_destination),
        )
        .route(
            "/api/v1/backup/destinations/{id}/test",
            post(test_destination),
        )
        .route(
            "/api/v1/backup/policies",
            get(list_policies).post(create_policy),
        )
        .route(
            "/api/v1/backup/policies/{id}",
            axum::routing::patch(update_policy).delete(delete_policy),
        )
        .route("/api/v1/backup/policies/{id}/trigger", post(trigger_policy))
        .route("/api/v1/backup/jobs", get(list_jobs))
        .route("/api/v1/backup/jobs/{id}", get(get_job).delete(delete_job))
        .route("/api/v1/archive/export", post(archive_export))
        .route("/api/v1/archive/exports", get(list_archive_exports))
}

const VALID_KINDS: &[&str] = &["local", "sftp", "ftp", "s3"];

fn valid_kind(kind: &str) -> bool {
    VALID_KINDS.contains(&kind)
}

async fn load_destination(pool: &sqlx::SqlitePool, id: &str) -> AppResult<BackupDestination> {
    sqlx::query_as::<_, BackupDestination>("SELECT * FROM backup_destinations WHERE id = ?")
        .bind(id)
        .fetch_optional(pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("backup destination {id} not found")))
}

async fn load_policy(pool: &sqlx::SqlitePool, id: &str) -> AppResult<BackupPolicy> {
    sqlx::query_as::<_, BackupPolicy>("SELECT * FROM backup_policies WHERE id = ?")
        .bind(id)
        .fetch_optional(pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("backup policy {id} not found")))
}

async fn load_job(pool: &sqlx::SqlitePool, id: &str) -> AppResult<BackupJob> {
    sqlx::query_as::<_, BackupJob>("SELECT * FROM backup_jobs WHERE id = ?")
        .bind(id)
        .fetch_optional(pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("backup job {id} not found")))
}

/// Merge a new config over the existing one: any secret value the client sent back as the `***`
/// placeholder is replaced with the stored secret (so editing other fields never wipes credentials).
fn merge_secret_config(old: &serde_json::Value, mut new: serde_json::Value) -> serde_json::Value {
    if let (Some(old_obj), Some(new_obj)) = (old.as_object(), new.as_object_mut()) {
        for key in BACKUP_SECRET_KEYS {
            if new_obj.get(*key).and_then(|v| v.as_str()) == Some("***") {
                match old_obj.get(*key) {
                    Some(prev) => {
                        new_obj.insert((*key).to_string(), prev.clone());
                    }
                    None => {
                        new_obj.remove(*key);
                    }
                }
            }
        }
    }
    new
}

// ---- Destinations ----

async fn list_destinations(
    State(st): State<AppState>,
    principal: Principal,
) -> AppResult<Json<Vec<BackupDestinationView>>> {
    principal.require(principal.can_view(), "view backup destinations")?;
    let rows = sqlx::query_as::<_, BackupDestination>(
        "SELECT * FROM backup_destinations ORDER BY created_at ASC",
    )
    .fetch_all(&st.pool)
    .await?;
    Ok(Json(
        rows.into_iter().map(BackupDestinationView::from).collect(),
    ))
}

async fn create_destination(
    State(st): State<AppState>,
    principal: Principal,
    Json(body): Json<BackupDestinationCreate>,
) -> AppResult<(StatusCode, Json<BackupDestinationView>)> {
    principal.require(
        principal.can_manage_registry(),
        "create backup destinations",
    )?;
    let name = body.name.trim();
    if name.is_empty() {
        return Err(AppError::BadRequest("`name` is required".into()));
    }
    if !valid_kind(&body.kind) {
        return Err(AppError::BadRequest(
            "`kind` must be local|sftp|ftp|s3".into(),
        ));
    }
    let config = body.config.unwrap_or_else(|| json!({}));
    if !config.is_object() {
        return Err(AppError::BadRequest(
            "`config` must be a JSON object".into(),
        ));
    }
    let enabled = body.enabled.unwrap_or(true);
    let id = format!("bkd_{}", Uuid::new_v4().simple());
    let now = Utc::now();
    sqlx::query(
        "INSERT INTO backup_destinations (id, name, kind, config, enabled, created_at, updated_at)
         VALUES (?, ?, ?, ?, ?, ?, ?)",
    )
    .bind(&id)
    .bind(name)
    .bind(&body.kind)
    .bind(SqlxJson(config))
    .bind(enabled)
    .bind(now)
    .bind(now)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "create_backup_destination",
        "backup_destination",
        &id,
        json!({ "kind": &body.kind, "name": name }),
    )
    .await;
    let dest = load_destination(&st.pool, &id).await?;
    Ok((StatusCode::CREATED, Json(BackupDestinationView::from(dest))))
}

async fn update_destination(
    State(st): State<AppState>,
    Path(id): Path<String>,
    principal: Principal,
    Json(body): Json<BackupDestinationUpdate>,
) -> AppResult<Json<BackupDestinationView>> {
    principal.require(
        principal.can_manage_registry(),
        "update backup destinations",
    )?;
    let cur = load_destination(&st.pool, &id).await?;

    let name = body
        .name
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| cur.name.clone());
    let kind = body.kind.unwrap_or_else(|| cur.kind.clone());
    if !valid_kind(&kind) {
        return Err(AppError::BadRequest(
            "`kind` must be local|sftp|ftp|s3".into(),
        ));
    }
    let config = match body.config {
        Some(new) => {
            if !new.is_object() {
                return Err(AppError::BadRequest(
                    "`config` must be a JSON object".into(),
                ));
            }
            merge_secret_config(&cur.config.0, new)
        }
        None => cur.config.0.clone(),
    };
    let enabled = body.enabled.unwrap_or(cur.enabled);

    sqlx::query(
        "UPDATE backup_destinations SET name = ?, kind = ?, config = ?, enabled = ?, updated_at = ? WHERE id = ?",
    )
    .bind(&name)
    .bind(&kind)
    .bind(SqlxJson(config))
    .bind(enabled)
    .bind(Utc::now())
    .bind(&id)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "update_backup_destination",
        "backup_destination",
        &id,
        json!({ "kind": &kind, "enabled": enabled }),
    )
    .await;
    let dest = load_destination(&st.pool, &id).await?;
    Ok(Json(BackupDestinationView::from(dest)))
}

async fn delete_destination(
    State(st): State<AppState>,
    Path(id): Path<String>,
    principal: Principal,
) -> AppResult<StatusCode> {
    principal.require(
        principal.can_manage_registry(),
        "delete backup destinations",
    )?;
    let res = sqlx::query("DELETE FROM backup_destinations WHERE id = ?")
        .bind(&id)
        .execute(&st.pool)
        .await?;
    if res.rows_affected() == 0 {
        return Err(AppError::NotFound(format!(
            "backup destination {id} not found"
        )));
    }
    auth::audit(
        &st.pool,
        &principal,
        "delete_backup_destination",
        "backup_destination",
        &id,
        json!({}),
    )
    .await;
    Ok(StatusCode::NO_CONTENT)
}

async fn test_destination(
    State(st): State<AppState>,
    Path(id): Path<String>,
    principal: Principal,
) -> AppResult<Json<BackupTestResult>> {
    principal.require(principal.can_manage_registry(), "test backup destinations")?;
    let dest = load_destination(&st.pool, &id).await?;
    let result = backup::test_destination(&st, &dest).await;
    auth::audit(
        &st.pool,
        &principal,
        "test_backup_destination",
        "backup_destination",
        &id,
        json!({ "ok": result.ok }),
    )
    .await;
    Ok(Json(result))
}

// ---- Policies ----

async fn list_policies(
    State(st): State<AppState>,
    principal: Principal,
) -> AppResult<Json<Vec<BackupPolicy>>> {
    principal.require(principal.can_view(), "view backup policies")?;
    let rows =
        sqlx::query_as::<_, BackupPolicy>("SELECT * FROM backup_policies ORDER BY created_at ASC")
            .fetch_all(&st.pool)
            .await?;
    Ok(Json(rows))
}

async fn create_policy(
    State(st): State<AppState>,
    principal: Principal,
    Json(body): Json<BackupPolicyCreate>,
) -> AppResult<(StatusCode, Json<BackupPolicy>)> {
    principal.require(principal.can_manage_registry(), "create backup policies")?;
    let name = body.name.trim();
    if name.is_empty() {
        return Err(AppError::BadRequest("`name` is required".into()));
    }
    // The destination must exist (FK would also reject, but a clean 404 is friendlier).
    let _ = load_destination(&st.pool, &body.destination_id).await?;
    let camera_ids = body.camera_ids.unwrap_or_else(|| json!([]));
    if !camera_ids.is_array() {
        return Err(AppError::BadRequest(
            "`camera_ids` must be a JSON array of camera ids".into(),
        ));
    }
    let incident_lock_only = body.incident_lock_only.unwrap_or(false);
    let schedule_interval_s = body.schedule_interval_s.unwrap_or(86_400).max(60);
    let lookback_hours = body.lookback_hours.unwrap_or(0).max(0);
    let enabled = body.enabled.unwrap_or(true);
    let id = format!("bkp_{}", Uuid::new_v4().simple());
    let now = Utc::now();
    sqlx::query(
        "INSERT INTO backup_policies
           (id, name, destination_id, camera_ids, incident_lock_only, schedule_interval_s,
            lookback_hours, last_run_at, last_job_id, enabled, created_at, updated_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?)",
    )
    .bind(&id)
    .bind(name)
    .bind(&body.destination_id)
    .bind(SqlxJson(camera_ids))
    .bind(incident_lock_only)
    .bind(schedule_interval_s)
    .bind(lookback_hours)
    .bind(enabled)
    .bind(now)
    .bind(now)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "create_backup_policy",
        "backup_policy",
        &id,
        json!({ "destination_id": &body.destination_id, "name": name }),
    )
    .await;
    let policy = load_policy(&st.pool, &id).await?;
    Ok((StatusCode::CREATED, Json(policy)))
}

async fn update_policy(
    State(st): State<AppState>,
    Path(id): Path<String>,
    principal: Principal,
    Json(body): Json<BackupPolicyUpdate>,
) -> AppResult<Json<BackupPolicy>> {
    principal.require(principal.can_manage_registry(), "update backup policies")?;
    let cur = load_policy(&st.pool, &id).await?;

    let name = body
        .name
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| cur.name.clone());
    let destination_id = body
        .destination_id
        .unwrap_or_else(|| cur.destination_id.clone());
    let _ = load_destination(&st.pool, &destination_id).await?;
    let camera_ids = match body.camera_ids {
        Some(v) => {
            if !v.is_array() {
                return Err(AppError::BadRequest(
                    "`camera_ids` must be a JSON array of camera ids".into(),
                ));
            }
            v
        }
        None => cur.camera_ids.0.clone(),
    };
    let incident_lock_only = body.incident_lock_only.unwrap_or(cur.incident_lock_only);
    let schedule_interval_s = body
        .schedule_interval_s
        .map(|v| v.max(60))
        .unwrap_or(cur.schedule_interval_s);
    let lookback_hours = body
        .lookback_hours
        .map(|v| v.max(0))
        .unwrap_or(cur.lookback_hours);
    let enabled = body.enabled.unwrap_or(cur.enabled);

    sqlx::query(
        "UPDATE backup_policies SET name = ?, destination_id = ?, camera_ids = ?,
            incident_lock_only = ?, schedule_interval_s = ?, lookback_hours = ?, enabled = ?, updated_at = ?
         WHERE id = ?",
    )
    .bind(&name)
    .bind(&destination_id)
    .bind(SqlxJson(camera_ids))
    .bind(incident_lock_only)
    .bind(schedule_interval_s)
    .bind(lookback_hours)
    .bind(enabled)
    .bind(Utc::now())
    .bind(&id)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "update_backup_policy",
        "backup_policy",
        &id,
        json!({ "enabled": enabled }),
    )
    .await;
    let policy = load_policy(&st.pool, &id).await?;
    Ok(Json(policy))
}

async fn delete_policy(
    State(st): State<AppState>,
    Path(id): Path<String>,
    principal: Principal,
) -> AppResult<StatusCode> {
    principal.require(principal.can_manage_registry(), "delete backup policies")?;
    let res = sqlx::query("DELETE FROM backup_policies WHERE id = ?")
        .bind(&id)
        .execute(&st.pool)
        .await?;
    if res.rows_affected() == 0 {
        return Err(AppError::NotFound(format!("backup policy {id} not found")));
    }
    auth::audit(
        &st.pool,
        &principal,
        "delete_backup_policy",
        "backup_policy",
        &id,
        json!({}),
    )
    .await;
    Ok(StatusCode::NO_CONTENT)
}

async fn trigger_policy(
    State(st): State<AppState>,
    Path(id): Path<String>,
    principal: Principal,
) -> AppResult<(StatusCode, Json<BackupJob>)> {
    principal.require(principal.can_manage_registry(), "trigger backup policies")?;
    let policy = load_policy(&st.pool, &id).await?;
    let job_id = backup::trigger_policy(&st, &policy)
        .await
        .map_err(AppError::Other)?;
    auth::audit(
        &st.pool,
        &principal,
        "trigger_backup_policy",
        "backup_policy",
        &id,
        json!({ "job_id": &job_id }),
    )
    .await;
    let job = load_job(&st.pool, &job_id).await?;
    Ok((StatusCode::ACCEPTED, Json(job)))
}

// ---- Jobs ----

#[derive(Debug, Deserialize)]
struct JobQuery {
    policy_id: Option<String>,
    status: Option<String>,
    limit: Option<i64>,
}

async fn list_jobs(
    State(st): State<AppState>,
    principal: Principal,
    Query(q): Query<JobQuery>,
) -> AppResult<Json<Vec<BackupJob>>> {
    principal.require(principal.can_view(), "view backup jobs")?;
    let limit = q.limit.unwrap_or(100).clamp(1, 2000);
    let rows = sqlx::query_as::<_, BackupJob>(
        "SELECT * FROM backup_jobs
         WHERE (? IS NULL OR policy_id = ?)
           AND (? IS NULL OR status = ?)
         ORDER BY created_at DESC LIMIT ?",
    )
    .bind(&q.policy_id)
    .bind(&q.policy_id)
    .bind(&q.status)
    .bind(&q.status)
    .bind(limit)
    .fetch_all(&st.pool)
    .await?;
    Ok(Json(rows))
}

async fn get_job(
    State(st): State<AppState>,
    Path(id): Path<String>,
    principal: Principal,
) -> AppResult<Json<BackupJob>> {
    principal.require(principal.can_view(), "view backup jobs")?;
    let job = load_job(&st.pool, &id).await?;
    Ok(Json(job))
}

async fn delete_job(
    State(st): State<AppState>,
    Path(id): Path<String>,
    principal: Principal,
) -> AppResult<StatusCode> {
    principal.require(principal.can_manage_registry(), "delete backup jobs")?;
    let job = load_job(&st.pool, &id).await?;
    // Remove the produced archive artifact, if any, before dropping the row.
    if let Some(path) = &job.output_path {
        let _ = tokio::fs::remove_file(path).await;
    }
    sqlx::query("DELETE FROM backup_jobs WHERE id = ?")
        .bind(&id)
        .execute(&st.pool)
        .await?;
    auth::audit(
        &st.pool,
        &principal,
        "delete_backup_job",
        "backup_job",
        &id,
        json!({}),
    )
    .await;
    Ok(StatusCode::NO_CONTENT)
}

// ---- On-demand archive export ----

fn parse_opt_ts(s: &Option<String>, field: &str) -> AppResult<Option<DateTime<Utc>>> {
    match s {
        Some(v) => util::parse_rfc3339(v)
            .map(Some)
            .ok_or_else(|| AppError::BadRequest(format!("invalid `{field}` timestamp"))),
        None => Ok(None),
    }
}

async fn archive_export(
    State(st): State<AppState>,
    principal: Principal,
    Json(body): Json<ArchiveExportRequest>,
) -> AppResult<(StatusCode, Json<BackupJob>)> {
    principal.require(principal.can_manage_registry(), "export archives")?;
    let from = parse_opt_ts(&body.from, "from")?;
    let to = parse_opt_ts(&body.to, "to")?;
    if let (Some(f), Some(t)) = (from, to) {
        if f > t {
            return Err(AppError::BadRequest("`from` must be <= `to`".into()));
        }
    }
    let camera_ids = body.camera_ids;
    let incident_lock_only = body.incident_lock_only.unwrap_or(false);
    let trim = body.trim.unwrap_or(false);
    let job =
        backup::create_archive(&st, camera_ids.clone(), from, to, incident_lock_only, trim).await?;
    auth::audit(
        &st.pool,
        &principal,
        "create_archive_export",
        "backup_job",
        &job.id,
        json!({ "camera_ids": camera_ids, "incident_lock_only": incident_lock_only, "trim": trim }),
    )
    .await;
    Ok((StatusCode::CREATED, Json(job)))
}

#[derive(Debug, Deserialize)]
struct LimitQuery {
    limit: Option<i64>,
}

async fn list_archive_exports(
    State(st): State<AppState>,
    principal: Principal,
    Query(q): Query<LimitQuery>,
) -> AppResult<Json<Vec<BackupJob>>> {
    principal.require(principal.can_view(), "view archive exports")?;
    let limit = q.limit.unwrap_or(100).clamp(1, 2000);
    let rows = sqlx::query_as::<_, BackupJob>(
        "SELECT * FROM backup_jobs WHERE kind = 'on_demand_archive' ORDER BY created_at DESC LIMIT ?",
    )
    .bind(limit)
    .fetch_all(&st.pool)
    .await?;
    Ok(Json(rows))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn valid_kind_accepts_known_and_rejects_others() {
        assert!(valid_kind("local"));
        assert!(valid_kind("sftp"));
        assert!(valid_kind("ftp"));
        assert!(valid_kind("s3"));
        // Unknown, empty, and wrong-case are all rejected (case-sensitive match).
        assert!(!valid_kind("gcs"));
        assert!(!valid_kind(""));
        assert!(!valid_kind("Local"));
        assert!(!valid_kind("S3"));
    }

    #[test]
    fn valid_kinds_list_is_exact() {
        assert_eq!(VALID_KINDS, &["local", "sftp", "ftp", "s3"]);
    }

    #[test]
    fn merge_secret_config_restores_placeholder_from_old() {
        let old = json!({ "password": "hunter2", "host": "old.example" });
        let new = json!({ "password": "***", "host": "new.example" });
        let merged = merge_secret_config(&old, new);
        // The *** placeholder is replaced with the stored secret...
        assert_eq!(merged["password"], json!("hunter2"));
        // ...while non-secret fields take the newly submitted value.
        assert_eq!(merged["host"], json!("new.example"));
    }

    #[test]
    fn merge_secret_config_drops_placeholder_when_no_stored_secret() {
        let old = json!({ "host": "h" });
        let new = json!({ "secret": "***", "host": "h2" });
        let merged = merge_secret_config(&old, new);
        // No previously-stored `secret`, so the placeholder key is removed entirely.
        assert!(merged.as_object().unwrap().get("secret").is_none());
        assert_eq!(merged["host"], json!("h2"));
    }

    #[test]
    fn merge_secret_config_keeps_new_non_placeholder_secret() {
        let old = json!({ "password": "old" });
        let new = json!({ "password": "brandnew" });
        let merged = merge_secret_config(&old, new);
        // A real new value (not the placeholder) is preserved, overwriting the old secret.
        assert_eq!(merged["password"], json!("brandnew"));
    }

    #[test]
    fn merge_secret_config_handles_all_secret_keys() {
        let old = json!({ "pass": "a", "password": "b", "secret_key": "c", "secret": "d" });
        let new = json!({ "pass": "***", "password": "***", "secret_key": "***", "secret": "***" });
        let merged = merge_secret_config(&old, new);
        assert_eq!(merged["pass"], json!("a"));
        assert_eq!(merged["password"], json!("b"));
        assert_eq!(merged["secret_key"], json!("c"));
        assert_eq!(merged["secret"], json!("d"));
    }

    #[test]
    fn merge_secret_config_passthrough_for_non_objects() {
        // When either side is not a JSON object, the new value is returned unchanged.
        let old = json!("not-an-object");
        let new = json!([1, 2, 3]);
        let merged = merge_secret_config(&old, new.clone());
        assert_eq!(merged, new);
    }

    #[test]
    fn parse_opt_ts_none_valid_and_invalid() {
        // None input yields Ok(None).
        assert!(parse_opt_ts(&None, "from").unwrap().is_none());

        // A valid RFC3339 timestamp (trailing Z accepted) parses to Some.
        let ok = parse_opt_ts(&Some("2024-01-02T03:04:05Z".to_string()), "from").unwrap();
        assert!(ok.is_some());

        // An invalid timestamp surfaces a BadRequest mentioning the field name.
        let err = parse_opt_ts(&Some("not-a-timestamp".to_string()), "to").unwrap_err();
        match err {
            AppError::BadRequest(msg) => {
                assert!(msg.contains("to"));
                assert!(msg.contains("invalid"));
            }
            other => panic!("expected BadRequest, got {other:?}"),
        }
    }
}