ironflow-api 2.35.6

REST API for ironflow run management and observability
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
//! Server configuration with startup validation.
//!
//! Loads configuration from environment variables and validates that all
//! required values are present **at startup**, not at first use.
//!
//! # Environment Variables
//!
//! | Variable | Required | Default | Description |
//! |----------|----------|---------|-------------|
//! | `DATABASE_URL` | **prod** | - | PostgreSQL connection string |
//! | `JWT_SECRET` | **prod** | dev default | JWT signing secret |
//! | `WORKER_TOKEN` | **prod** | dev default | Worker-to-API auth token |
//! | `PORT` | no | `3000` | HTTP listen port |
//! | `ALLOWED_ORIGINS` | no | same-origin | Comma-separated CORS origins |
//! | `DASHBOARD_DIR` | no | embedded | Filesystem path to dashboard assets |
//! | `WEBHOOK_URL` | no | - | Outbound webhook URL for notifications |
//! | `IRONFLOW_ENV` | no | `development` | `production` or `development` |
//! | `RATE_LIMIT_AUTH` | no | `10` | Auth rate limit (req/min/IP). `0` = disabled |
//! | `RATE_LIMIT_GENERAL` | no | `60` | General rate limit (req/min/IP). `0` = disabled |
//! | `ARTIFACTS_DIR` | no | - | Filesystem root for artifact blobs. Unset disables artifacts |
//! | `ARTIFACT_MAX_BYTES` | no | `104857600` | Maximum size of a single artifact |
//! | `PURGE_MAX_AGE_DAYS` | no | `90` | Runs older than this are purged |
//! | `PURGE_MAX_RUNS_PER_WORKFLOW` | no | `1000` | Max terminal runs kept per workflow |
//! | `PURGE_DRY_RUN` | no | `false` | Log what would be purged without deleting |
//! | `PURGE_INTERVAL_SECS` | no | `86400` | Seconds between purge ticks (min 60) |
//! | `ARTIFACT_BACKEND` | no | `local` | Blob storage backend: `local` or `s3` |
//! | `ARTIFACT_S3_BUCKET` | **if s3** | - | S3 bucket name |
//! | `ARTIFACT_S3_REGION` | no | `eu-west-1` | S3 region |
//! | `ARTIFACT_S3_ENDPOINT` | no | - | Custom S3 endpoint (MinIO, R2) |
//! | `ARTIFACT_S3_PREFIX` | no | - | Key prefix within the bucket |
//! | `ARTIFACT_GC_INTERVAL_SECS` | no | `86400` | Seconds between GC ticks (min 60) |
//! | `ARTIFACT_GC_GRACE_DAYS` | no | `7` | Days before an orphan blob is deleted |
//! | `ARTIFACT_GC_DRY_RUN` | no | `false` | Log what would be GC'd without deleting |
//!
//! # Examples
//!
//! ```no_run
//! use ironflow_api::config::ServerConfig;
//!
//! # fn example() -> Result<(), ironflow_api::config::ConfigError> {
//! let config = ServerConfig::from_env()?;
//! println!("Listening on port {}", config.port);
//! # Ok(())
//! # }
//! ```

use std::env;
use std::fmt;
use std::path::PathBuf;

use ironflow_artifacts::local::DEFAULT_MAX_ARTIFACT_BYTES;
use tracing::warn;

/// Server configuration loaded from environment variables.
///
/// Use [`ServerConfig::from_env`] to load and validate at startup.
///
/// # Examples
///
/// ```no_run
/// use ironflow_api::config::ServerConfig;
///
/// # fn example() -> Result<(), ironflow_api::config::ConfigError> {
/// let config = ServerConfig::from_env()?;
/// assert!(config.port > 0);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct ServerConfig {
    /// PostgreSQL connection string. Required in production.
    pub database_url: Option<String>,
    /// JWT signing secret.
    pub jwt_secret: String,
    /// Worker-to-API authentication token.
    pub worker_token: String,
    /// HTTP listen port.
    pub port: u16,
    /// Comma-separated list of allowed CORS origins.
    pub allowed_origins: Option<String>,
    /// Filesystem path to dashboard assets (overrides embedded).
    pub dashboard_dir: Option<PathBuf>,
    /// Outbound webhook URL for event notifications.
    pub webhook_url: Option<String>,
    /// Filesystem root for artifact blobs.
    ///
    /// `None` leaves artifacts disabled: the artifact routes answer `501` and
    /// a step that declares one fails explicitly. Every other endpoint is
    /// unaffected, so an existing deployment upgrades without changes.
    ///
    /// Read from `ARTIFACTS_DIR`.
    pub artifacts_dir: Option<PathBuf>,
    /// Maximum size of a single artifact, in bytes.
    ///
    /// Read from `ARTIFACT_MAX_BYTES`, defaulting to 100 MiB.
    pub artifact_max_bytes: u64,
    /// Maximum age of a run before it becomes eligible for purging, in days.
    ///
    /// Read from `PURGE_MAX_AGE_DAYS`, defaulting to 90.
    pub purge_max_age_days: u32,
    /// Maximum number of terminal runs to keep per workflow.
    ///
    /// Read from `PURGE_MAX_RUNS_PER_WORKFLOW`, defaulting to 1000.
    pub purge_max_runs_per_workflow: u32,
    /// When `true`, the purger logs what would be deleted but does not delete.
    ///
    /// Read from `PURGE_DRY_RUN`, defaulting to `false`.
    pub purge_dry_run: bool,
    /// Interval between purge ticks, in seconds.
    ///
    /// Read from `PURGE_INTERVAL_SECS`, defaulting to 86400 (once per day).
    pub purge_interval_secs: u64,
    /// Whether the server is running in production mode.
    pub is_production: bool,
    /// Rate limit for auth credential routes (sign-in, sign-up) in requests
    /// per minute per IP. `None` disables rate limiting on these routes.
    pub rate_limit_auth: Option<u32>,
    /// Rate limit for general public API routes in requests per minute per IP.
    /// `None` disables rate limiting on these routes.
    pub rate_limit_general: Option<u32>,
    /// Blob storage backend: `local` or `s3`.
    pub artifact_backend: String,
    /// S3 bucket name (required when `artifact_backend` is `s3`).
    pub artifact_s3_bucket: Option<String>,
    /// S3 region, defaults to `eu-west-1`.
    pub artifact_s3_region: String,
    /// Custom S3 endpoint for MinIO, R2, or GCS S3-compat.
    pub artifact_s3_endpoint: Option<String>,
    /// Key prefix within the S3 bucket.
    pub artifact_s3_prefix: Option<String>,
    /// Seconds between GC ticks, defaults to 86400 (once per day).
    pub artifact_gc_interval_secs: u64,
    /// Days before an orphan blob is eligible for deletion, defaults to 7.
    pub artifact_gc_grace_days: u32,
    /// When `true`, the GC logs what would be deleted without deleting.
    pub artifact_gc_dry_run: bool,
}

/// Configuration validation error.
///
/// Collects all missing/invalid values so the operator sees every problem
/// in a single error message, not one at a time.
///
/// # Examples
///
/// ```
/// use ironflow_api::config::ConfigError;
///
/// let err = ConfigError::new(vec!["JWT_SECRET is required in production".to_string()]);
/// assert!(err.to_string().contains("JWT_SECRET"));
/// ```
#[derive(Debug, Clone)]
pub struct ConfigError {
    /// Individual validation failure messages.
    pub errors: Vec<String>,
}

impl ConfigError {
    /// Create a new `ConfigError` from a list of validation messages.
    pub fn new(errors: Vec<String>) -> Self {
        Self { errors }
    }
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "configuration errors:")?;
        for error in &self.errors {
            writeln!(f, "  - {error}")?;
        }
        Ok(())
    }
}

impl std::error::Error for ConfigError {}

const DEV_JWT_SECRET: &str = "ironflow-dev-secret";
const DEV_WORKER_TOKEN: &str = "ironflow-dev-worker-token";

/// Prefix shared by every known development secret default. In production a
/// secret carrying this prefix is refused outright, so a fresh deploy that
/// copied the setup template verbatim cannot boot with a value published in
/// the repository.
const DEV_SECRET_PREFIX: &str = "ironflow-dev-";

/// Minimum accepted length, in bytes, for a production secret. A value shorter
/// than this is trivially brute-forced against an HS256 signature.
const MIN_PROD_SECRET_BYTES: usize = 32;

/// Reject a production secret that is a known development default or too short.
///
/// Pushes at most one message to `errors` (a known default is reported as such,
/// not also as "too short"), so the collect-all pattern lists each faulty
/// secret exactly once. Called only in production and only for a secret that
/// was explicitly set; an unset secret is handled by the "required" check.
fn reject_insecure_secret(name: &str, value: &str, errors: &mut Vec<String>) {
    if value.starts_with(DEV_SECRET_PREFIX) {
        errors.push(format!(
            "{name} must not use a known development default in production"
        ));
    } else if value.len() < MIN_PROD_SECRET_BYTES {
        errors.push(format!(
            "{name} must be at least {MIN_PROD_SECRET_BYTES} bytes in production, got {}",
            value.len()
        ));
    }
}

/// Parse an optional u32 env var. Returns `Some(default)` if unset,
/// `Some(value)` if set to a positive number, `None` if set to `0`
/// (meaning disabled). Pushes to `errors` if the value is not a valid u32.
fn parse_optional_u32(name: &str, default: u32, errors: &mut Vec<String>) -> Option<u32> {
    match env::var(name).ok() {
        Some(raw) => match raw.parse::<u32>() {
            Ok(0) => None,
            Ok(v) => Some(v),
            Err(_) => {
                errors.push(format!(
                    "{name} must be a valid u32 (0 to disable), got: {raw}"
                ));
                Some(default)
            }
        },
        None => Some(default),
    }
}

impl ServerConfig {
    /// Load configuration from environment variables and validate.
    ///
    /// In production mode (`IRONFLOW_ENV=production`), `JWT_SECRET` and
    /// `WORKER_TOKEN` must be explicitly set, must not carry the known
    /// development prefix `ironflow-dev-`, and must be at least 32 bytes long.
    /// `DATABASE_URL` is required in production.
    ///
    /// In development mode, insecure defaults are used with a warning.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError`] with all validation failures collected,
    /// so the operator can fix everything in one pass.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ironflow_api::config::ServerConfig;
    ///
    /// # fn example() -> Result<(), ironflow_api::config::ConfigError> {
    /// let config = ServerConfig::from_env()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_env() -> Result<Self, ConfigError> {
        let is_production = env::var("IRONFLOW_ENV")
            .map(|v| v.eq_ignore_ascii_case("production"))
            .unwrap_or(false);

        let mut errors = Vec::new();

        let database_url = env::var("DATABASE_URL").ok();
        if is_production && database_url.is_none() {
            errors.push("DATABASE_URL is required in production".to_string());
        }

        let jwt_secret_env = env::var("JWT_SECRET").ok();
        let jwt_secret = match jwt_secret_env {
            Some(val) => {
                if is_production {
                    reject_insecure_secret("JWT_SECRET", &val, &mut errors);
                }
                val
            }
            None if is_production => {
                errors.push("JWT_SECRET is required in production".to_string());
                String::new()
            }
            None => {
                warn!("JWT_SECRET not set, using insecure dev default -- do NOT use in production");
                DEV_JWT_SECRET.to_string()
            }
        };

        let worker_token_env = env::var("WORKER_TOKEN").ok();
        let worker_token = match worker_token_env {
            Some(val) => {
                if is_production {
                    reject_insecure_secret("WORKER_TOKEN", &val, &mut errors);
                }
                val
            }
            None if is_production => {
                errors.push("WORKER_TOKEN is required in production".to_string());
                String::new()
            }
            None => {
                warn!(
                    "WORKER_TOKEN not set, using insecure dev default -- do NOT use in production"
                );
                DEV_WORKER_TOKEN.to_string()
            }
        };

        let port = match env::var("PORT").ok() {
            Some(raw) => raw.parse::<u16>().unwrap_or_else(|_| {
                errors.push(format!("PORT must be a valid u16, got: {raw}"));
                0
            }),
            None => 3000,
        };

        let allowed_origins = env::var("ALLOWED_ORIGINS").ok();
        let dashboard_dir = env::var("DASHBOARD_DIR").ok().map(PathBuf::from);
        let webhook_url = env::var("WEBHOOK_URL").ok();

        let rate_limit_auth = parse_optional_u32("RATE_LIMIT_AUTH", 10, &mut errors);
        let rate_limit_general = parse_optional_u32("RATE_LIMIT_GENERAL", 60, &mut errors);

        let artifacts_dir = env::var("ARTIFACTS_DIR").ok().map(PathBuf::from);
        let artifact_max_bytes = match env::var("ARTIFACT_MAX_BYTES").ok() {
            Some(raw) => raw.parse::<u64>().unwrap_or_else(|_| {
                errors.push(format!(
                    "ARTIFACT_MAX_BYTES must be a valid u64, got: {raw}"
                ));
                DEFAULT_MAX_ARTIFACT_BYTES
            }),
            None => DEFAULT_MAX_ARTIFACT_BYTES,
        };

        let purge_max_age_days = match env::var("PURGE_MAX_AGE_DAYS").ok() {
            Some(raw) => raw.parse::<u32>().unwrap_or_else(|_| {
                errors.push(format!(
                    "PURGE_MAX_AGE_DAYS must be a valid u32, got: {raw}"
                ));
                90
            }),
            None => 90,
        };
        let purge_max_runs_per_workflow = match env::var("PURGE_MAX_RUNS_PER_WORKFLOW").ok() {
            Some(raw) => raw.parse::<u32>().unwrap_or_else(|_| {
                errors.push(format!(
                    "PURGE_MAX_RUNS_PER_WORKFLOW must be a valid u32, got: {raw}"
                ));
                1000
            }),
            None => 1000,
        };
        let purge_dry_run = env::var("PURGE_DRY_RUN")
            .map(|v| v.eq_ignore_ascii_case("true") || v == "1")
            .unwrap_or(false);
        let purge_interval_secs = match env::var("PURGE_INTERVAL_SECS").ok() {
            Some(raw) => {
                let parsed = raw.parse::<u64>().unwrap_or_else(|_| {
                    errors.push(format!(
                        "PURGE_INTERVAL_SECS must be a valid u64, got: {raw}"
                    ));
                    86400
                });
                if parsed < 60 {
                    errors.push(format!(
                        "PURGE_INTERVAL_SECS must be at least 60, got: {parsed}"
                    ));
                }
                parsed
            }
            None => 86400,
        };

        let artifact_backend = env::var("ARTIFACT_BACKEND")
            .unwrap_or_else(|_| "local".to_string())
            .to_lowercase();
        let artifact_s3_bucket = env::var("ARTIFACT_S3_BUCKET").ok();
        let artifact_s3_region =
            env::var("ARTIFACT_S3_REGION").unwrap_or_else(|_| "eu-west-1".to_string());
        let artifact_s3_endpoint = env::var("ARTIFACT_S3_ENDPOINT").ok();
        let artifact_s3_prefix = env::var("ARTIFACT_S3_PREFIX").ok();

        if artifact_backend == "s3" && artifact_s3_bucket.is_none() {
            errors.push("ARTIFACT_S3_BUCKET is required when ARTIFACT_BACKEND=s3".to_string());
        }
        if artifact_backend != "local" && artifact_backend != "s3" {
            errors.push(format!(
                "ARTIFACT_BACKEND must be 'local' or 's3', got: {artifact_backend}"
            ));
        }

        let artifact_gc_interval_secs = match env::var("ARTIFACT_GC_INTERVAL_SECS").ok() {
            Some(raw) => {
                let parsed = raw.parse::<u64>().unwrap_or_else(|_| {
                    errors.push(format!(
                        "ARTIFACT_GC_INTERVAL_SECS must be a valid u64, got: {raw}"
                    ));
                    86400
                });
                if parsed < 60 {
                    errors.push(format!(
                        "ARTIFACT_GC_INTERVAL_SECS must be at least 60, got: {parsed}"
                    ));
                }
                parsed
            }
            None => 86400,
        };
        let artifact_gc_grace_days = match env::var("ARTIFACT_GC_GRACE_DAYS").ok() {
            Some(raw) => raw.parse::<u32>().unwrap_or_else(|_| {
                errors.push(format!(
                    "ARTIFACT_GC_GRACE_DAYS must be a valid u32, got: {raw}"
                ));
                7
            }),
            None => 7,
        };
        let artifact_gc_dry_run = env::var("ARTIFACT_GC_DRY_RUN")
            .map(|v| v.eq_ignore_ascii_case("true") || v == "1")
            .unwrap_or(false);

        if !errors.is_empty() {
            return Err(ConfigError::new(errors));
        }

        Ok(Self {
            database_url,
            jwt_secret,
            worker_token,
            port,
            allowed_origins,
            dashboard_dir,
            webhook_url,
            is_production,
            rate_limit_auth,
            rate_limit_general,
            artifacts_dir,
            artifact_max_bytes,
            purge_max_age_days,
            purge_max_runs_per_workflow,
            purge_dry_run,
            purge_interval_secs,
            artifact_backend,
            artifact_s3_bucket,
            artifact_s3_region,
            artifact_s3_endpoint,
            artifact_s3_prefix,
            artifact_gc_interval_secs,
            artifact_gc_grace_days,
            artifact_gc_dry_run,
        })
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use super::*;

    // Env var mutations are not thread-safe -- serialize all tests that touch them.
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    /// # Safety
    ///
    /// Must be called while holding `ENV_LOCK`.
    unsafe fn clear_env() {
        unsafe {
            env::remove_var("IRONFLOW_ENV");
            env::remove_var("DATABASE_URL");
            env::remove_var("JWT_SECRET");
            env::remove_var("WORKER_TOKEN");
            env::remove_var("PORT");
            env::remove_var("ALLOWED_ORIGINS");
            env::remove_var("DASHBOARD_DIR");
            env::remove_var("WEBHOOK_URL");
            env::remove_var("RATE_LIMIT_AUTH");
            env::remove_var("RATE_LIMIT_GENERAL");
            env::remove_var("PURGE_MAX_AGE_DAYS");
            env::remove_var("PURGE_MAX_RUNS_PER_WORKFLOW");
            env::remove_var("PURGE_DRY_RUN");
            env::remove_var("PURGE_INTERVAL_SECS");
            env::remove_var("ARTIFACT_BACKEND");
            env::remove_var("ARTIFACT_S3_BUCKET");
            env::remove_var("ARTIFACT_S3_REGION");
            env::remove_var("ARTIFACT_S3_ENDPOINT");
            env::remove_var("ARTIFACT_S3_PREFIX");
            env::remove_var("ARTIFACT_GC_INTERVAL_SECS");
            env::remove_var("ARTIFACT_GC_GRACE_DAYS");
            env::remove_var("ARTIFACT_GC_DRY_RUN");
        }
    }

    #[test]
    fn config_error_display_lists_all_errors() {
        let err = ConfigError::new(vec![
            "JWT_SECRET is required".to_string(),
            "DATABASE_URL is required".to_string(),
        ]);
        let msg = err.to_string();
        assert!(msg.contains("JWT_SECRET"));
        assert!(msg.contains("DATABASE_URL"));
        assert!(msg.contains("configuration errors:"));
    }

    #[test]
    fn config_error_is_std_error() {
        let err = ConfigError::new(vec!["test".to_string()]);
        let _: &dyn std::error::Error = &err;
    }

    #[test]
    fn default_dev_config_succeeds() {
        let _guard = ENV_LOCK.lock().unwrap();
        unsafe { clear_env() };

        let config = ServerConfig::from_env().expect("dev config should succeed");
        assert!(!config.is_production);
        assert_eq!(config.port, 3000);
        assert_eq!(config.jwt_secret, DEV_JWT_SECRET);
        assert_eq!(config.worker_token, DEV_WORKER_TOKEN);
    }

    #[test]
    fn production_without_secrets_fails() {
        let _guard = ENV_LOCK.lock().unwrap();
        unsafe {
            clear_env();
            env::set_var("IRONFLOW_ENV", "production");
        }

        let result = ServerConfig::from_env();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.errors.len() >= 3);
        assert!(err.errors.iter().any(|e| e.contains("DATABASE_URL")));
        assert!(err.errors.iter().any(|e| e.contains("JWT_SECRET")));
        assert!(err.errors.iter().any(|e| e.contains("WORKER_TOKEN")));

        unsafe { env::remove_var("IRONFLOW_ENV") };
    }

    #[test]
    fn invalid_port_returns_error() {
        let _guard = ENV_LOCK.lock().unwrap();
        unsafe {
            clear_env();
            env::set_var("PORT", "not-a-number");
        }

        let result = ServerConfig::from_env();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.errors.iter().any(|e| e.contains("PORT")));

        unsafe { env::remove_var("PORT") };
    }

    #[test]
    fn default_rate_limits() {
        let _guard = ENV_LOCK.lock().unwrap();
        unsafe { clear_env() };

        let config = ServerConfig::from_env().unwrap();
        assert_eq!(config.rate_limit_auth, Some(10));
        assert_eq!(config.rate_limit_general, Some(60));
    }

    #[test]
    fn custom_rate_limits() {
        let _guard = ENV_LOCK.lock().unwrap();
        unsafe {
            clear_env();
            env::set_var("RATE_LIMIT_AUTH", "20");
            env::set_var("RATE_LIMIT_GENERAL", "120");
        }

        let config = ServerConfig::from_env().unwrap();
        assert_eq!(config.rate_limit_auth, Some(20));
        assert_eq!(config.rate_limit_general, Some(120));

        unsafe {
            env::remove_var("RATE_LIMIT_AUTH");
            env::remove_var("RATE_LIMIT_GENERAL");
        }
    }

    #[test]
    fn zero_rate_limit_disables() {
        let _guard = ENV_LOCK.lock().unwrap();
        unsafe {
            clear_env();
            env::set_var("RATE_LIMIT_AUTH", "0");
            env::set_var("RATE_LIMIT_GENERAL", "0");
        }

        let config = ServerConfig::from_env().unwrap();
        assert!(config.rate_limit_auth.is_none());
        assert!(config.rate_limit_general.is_none());

        unsafe {
            env::remove_var("RATE_LIMIT_AUTH");
            env::remove_var("RATE_LIMIT_GENERAL");
        }
    }

    #[test]
    fn invalid_rate_limit_returns_error() {
        let _guard = ENV_LOCK.lock().unwrap();
        unsafe {
            clear_env();
            env::set_var("RATE_LIMIT_AUTH", "not-a-number");
        }

        let result = ServerConfig::from_env();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.errors.iter().any(|e| e.contains("RATE_LIMIT_AUTH")));

        unsafe { env::remove_var("RATE_LIMIT_AUTH") };
    }

    #[test]
    fn default_purge_config() {
        let _guard = ENV_LOCK.lock().unwrap();
        unsafe { clear_env() };

        let config = ServerConfig::from_env().unwrap();
        assert_eq!(config.purge_max_age_days, 90);
        assert_eq!(config.purge_max_runs_per_workflow, 1000);
        assert!(!config.purge_dry_run);
        assert_eq!(config.purge_interval_secs, 86400);
    }

    #[test]
    fn custom_purge_config() {
        let _guard = ENV_LOCK.lock().unwrap();
        unsafe {
            clear_env();
            env::set_var("PURGE_MAX_AGE_DAYS", "30");
            env::set_var("PURGE_MAX_RUNS_PER_WORKFLOW", "500");
            env::set_var("PURGE_DRY_RUN", "true");
            env::set_var("PURGE_INTERVAL_SECS", "3600");
        }

        let config = ServerConfig::from_env().unwrap();
        assert_eq!(config.purge_max_age_days, 30);
        assert_eq!(config.purge_max_runs_per_workflow, 500);
        assert!(config.purge_dry_run);
        assert_eq!(config.purge_interval_secs, 3600);

        unsafe {
            env::remove_var("PURGE_MAX_AGE_DAYS");
            env::remove_var("PURGE_MAX_RUNS_PER_WORKFLOW");
            env::remove_var("PURGE_DRY_RUN");
            env::remove_var("PURGE_INTERVAL_SECS");
        }
    }

    #[test]
    fn invalid_purge_max_age_days_returns_error() {
        let _guard = ENV_LOCK.lock().unwrap();
        unsafe {
            clear_env();
            env::set_var("PURGE_MAX_AGE_DAYS", "not-a-number");
        }

        let result = ServerConfig::from_env();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.errors.iter().any(|e| e.contains("PURGE_MAX_AGE_DAYS")));

        unsafe { env::remove_var("PURGE_MAX_AGE_DAYS") };
    }

    // Strong secrets: >= 32 bytes and not carrying the dev prefix.
    const STRONG_JWT: &str = "prod-jwt-secret-0123456789abcdef0123456789";
    const STRONG_WORKER: &str = "prod-worker-token-0123456789abcdef01234567";

    /// Wipe the environment, then set production mode with the given secrets.
    ///
    /// # Safety
    ///
    /// Mutates process-global environment variables; must be called while
    /// holding `ENV_LOCK` so no other test observes a torn environment.
    unsafe fn setup_prod(jwt: &str, worker: &str) {
        unsafe {
            clear_env();
            env::set_var("IRONFLOW_ENV", "production");
            env::set_var("DATABASE_URL", "postgres://x");
            env::set_var("JWT_SECRET", jwt);
            env::set_var("WORKER_TOKEN", worker);
        }
    }

    #[test]
    fn from_env_production_rejects_known_dev_jwt_secret() {
        let _guard = ENV_LOCK.lock().unwrap();
        // "ironflow-dev-jwt-secret" is the exact value the setup template shipped.
        // SAFETY: env writes serialized by ENV_LOCK, held above.
        unsafe { setup_prod("ironflow-dev-jwt-secret", STRONG_WORKER) };

        let err = ServerConfig::from_env().unwrap_err();
        assert!(
            err.errors
                .iter()
                .any(|e| e.contains("JWT_SECRET") && e.contains("known development default")),
            "expected a known-default rejection for JWT_SECRET, got {:?}",
            err.errors
        );
        assert!(
            !err.errors.iter().any(|e| e.contains("WORKER_TOKEN")),
            "a strong WORKER_TOKEN must not be flagged, got {:?}",
            err.errors
        );

        unsafe { clear_env() };
    }

    #[test]
    fn from_env_production_rejects_known_dev_worker_token() {
        let _guard = ENV_LOCK.lock().unwrap();
        // SAFETY: env writes serialized by ENV_LOCK, held above.
        unsafe { setup_prod(STRONG_JWT, DEV_WORKER_TOKEN) };

        let err = ServerConfig::from_env().unwrap_err();
        assert!(
            err.errors
                .iter()
                .any(|e| e.contains("WORKER_TOKEN") && e.contains("known development default")),
            "expected a known-default rejection for WORKER_TOKEN, got {:?}",
            err.errors
        );
        assert!(!err.errors.iter().any(|e| e.contains("JWT_SECRET")));

        unsafe { clear_env() };
    }

    #[test]
    fn from_env_production_rejects_short_jwt_secret() {
        let _guard = ENV_LOCK.lock().unwrap();
        // "shortsecret" is not a dev default, but is under 32 bytes.
        // SAFETY: env writes serialized by ENV_LOCK, held above.
        unsafe { setup_prod("shortsecret", STRONG_WORKER) };

        let err = ServerConfig::from_env().unwrap_err();
        assert!(
            err.errors
                .iter()
                .any(|e| e.contains("JWT_SECRET") && e.contains("32 bytes")),
            "expected a length rejection for JWT_SECRET, got {:?}",
            err.errors
        );

        unsafe { clear_env() };
    }

    #[test]
    fn from_env_production_rejects_short_worker_token() {
        let _guard = ENV_LOCK.lock().unwrap();
        // SAFETY: env writes serialized by ENV_LOCK, held above.
        unsafe { setup_prod(STRONG_JWT, "tinytoken") };

        let err = ServerConfig::from_env().unwrap_err();
        assert!(
            err.errors
                .iter()
                .any(|e| e.contains("WORKER_TOKEN") && e.contains("32 bytes")),
            "expected a length rejection for WORKER_TOKEN, got {:?}",
            err.errors
        );

        unsafe { clear_env() };
    }

    #[test]
    fn from_env_production_accepts_strong_secrets() {
        let _guard = ENV_LOCK.lock().unwrap();
        // SAFETY: env writes serialized by ENV_LOCK, held above.
        unsafe { setup_prod(STRONG_JWT, STRONG_WORKER) };

        let config = ServerConfig::from_env().expect("strong secrets should be accepted");
        assert!(config.is_production);
        assert_eq!(config.jwt_secret, STRONG_JWT);
        assert_eq!(config.worker_token, STRONG_WORKER);

        unsafe { clear_env() };
    }

    #[test]
    fn from_env_production_secret_length_boundary() {
        // Exactly 32 bytes is accepted; 31 is rejected. Guards the `<` in the
        // length check against an off-by-one drift to `<=`.
        let exactly_32: &str = "0123456789abcdef0123456789abcdef";
        let just_under: &str = "0123456789abcdef0123456789abcde";
        assert_eq!(exactly_32.len(), 32);
        assert_eq!(just_under.len(), 31);

        let _guard = ENV_LOCK.lock().unwrap();

        // SAFETY: env writes serialized by ENV_LOCK, held above.
        unsafe { setup_prod(exactly_32, STRONG_WORKER) };
        let config = ServerConfig::from_env().expect("a 32-byte secret is accepted");
        assert_eq!(config.jwt_secret, exactly_32);

        // SAFETY: ENV_LOCK still held.
        unsafe { setup_prod(just_under, STRONG_WORKER) };
        let err = ServerConfig::from_env().unwrap_err();
        assert!(
            err.errors
                .iter()
                .any(|e| e.contains("JWT_SECRET") && e.contains("32 bytes")),
            "31 bytes must be rejected, got {:?}",
            err.errors
        );

        unsafe { clear_env() };
    }

    #[test]
    fn from_env_development_accepts_weak_secret() {
        // The value/length checks run in production only: a short, dev-prefixed
        // secret set outside production is accepted and used unchanged.
        let _guard = ENV_LOCK.lock().unwrap();
        // SAFETY: env writes serialized by ENV_LOCK, held above.
        unsafe {
            clear_env();
            env::set_var("IRONFLOW_ENV", "development");
            env::set_var("JWT_SECRET", "ironflow-dev-jwt-secret");
            env::set_var("WORKER_TOKEN", "tinytoken");
        }

        let config = ServerConfig::from_env().expect("weak secrets are allowed outside production");
        assert!(!config.is_production);
        assert_eq!(config.jwt_secret, "ironflow-dev-jwt-secret");
        assert_eq!(config.worker_token, "tinytoken");

        unsafe { clear_env() };
    }

    #[test]
    fn from_env_production_lists_all_insecure_secrets() {
        // Non-regression: the exact state a fresh deploy reached by copying the
        // setup template `.env.example` verbatim and flipping IRONFLOW_ENV to
        // production. It used to boot silently; it must now be refused, with
        // both secrets named.
        let _guard = ENV_LOCK.lock().unwrap();
        // SAFETY: env writes serialized by ENV_LOCK, held above.
        unsafe { setup_prod("ironflow-dev-jwt-secret", "ironflow-dev-worker-token") };

        let err = ServerConfig::from_env().unwrap_err();
        assert!(
            err.errors.iter().any(|e| e.contains("JWT_SECRET")),
            "JWT_SECRET must be listed, got {:?}",
            err.errors
        );
        assert!(
            err.errors.iter().any(|e| e.contains("WORKER_TOKEN")),
            "WORKER_TOKEN must be listed, got {:?}",
            err.errors
        );

        unsafe { clear_env() };
    }
}