zorath-env 0.3.6

Fast CLI for .env validation against JSON/YAML schemas. 14 types, secret detection, watch mode, remote schemas, export to shell/docker/k8s/json, health diagnostics, code scanning, auto-fix. CI-friendly. Language-agnostic single binary.
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
use std::fs;
use std::io::{BufReader, Write};
use std::path::PathBuf;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use rustls::pki_types::CertificateDer;
use sha2::{Sha256, Digest};
use thiserror::Error;
use ureq::tls::TlsConfig;

#[derive(Error, Debug)]
pub enum RemoteError {
    #[error("HTTP request failed: {0}")]
    Network(String),
    #[error("invalid URL: {0}")]
    InvalidUrl(String),
    #[error("HTTP error: {0}")]
    HttpStatus(String),
    #[error("cache error: {0}")]
    Cache(String),
    #[error("only HTTPS URLs are allowed for security")]
    HttpNotAllowed,
    #[error("hash verification failed: expected {expected}, got {actual}")]
    HashMismatch { expected: String, actual: String },
    #[error("rate limited: wait {seconds} seconds before fetching again")]
    RateLimited { seconds: u64 },
    #[error("failed to load CA certificate: {0}")]
    CertificateError(String),
}

/// Default cache TTL: 1 hour
pub const CACHE_TTL_SECS: u64 = 3600;

/// Default rate limit: 60 seconds between fetches per URL
pub const DEFAULT_RATE_LIMIT_SECS: u64 = 60;

/// Security options for remote schema fetching
#[derive(Debug, Clone, Default)]
pub struct SecurityOptions {
    /// Expected SHA-256 hash of the schema content (hex-encoded)
    pub verify_hash: Option<String>,
    /// Custom CA certificate path for enterprise TLS
    pub ca_cert: Option<String>,
    /// Rate limit in seconds between fetches (0 to disable)
    pub rate_limit_seconds: u64,
}

impl SecurityOptions {
    pub fn new() -> Self {
        Self {
            verify_hash: None,
            ca_cert: None,
            rate_limit_seconds: DEFAULT_RATE_LIMIT_SECS,
        }
    }

    pub fn with_hash(mut self, hash: Option<String>) -> Self {
        self.verify_hash = hash;
        self
    }

    pub fn with_ca_cert(mut self, path: Option<String>) -> Self {
        self.ca_cert = path;
        self
    }

    pub fn with_rate_limit(mut self, seconds: u64) -> Self {
        self.rate_limit_seconds = seconds;
        self
    }
}

/// Check if a path is a remote URL (https://)
pub fn is_remote_url(path: &str) -> bool {
    path.starts_with("https://") || path.starts_with("http://")
}

/// Fetch schema content from a remote URL (backward compatible)
///
/// If `no_cache` is true, always fetches fresh content.
/// Otherwise, uses cached content if available and not expired.
#[allow(dead_code)]
pub fn fetch_remote_schema(url: &str, no_cache: bool) -> Result<String, RemoteError> {
    fetch_remote_schema_secure(url, no_cache, &SecurityOptions::new())
}

/// Fetch schema content from a remote URL with security options
///
/// Supports hash verification, rate limiting, and custom CA certificates.
pub fn fetch_remote_schema_secure(
    url: &str,
    no_cache: bool,
    security: &SecurityOptions,
) -> Result<String, RemoteError> {
    // Security: reject HTTP URLs
    if url.starts_with("http://") {
        return Err(RemoteError::HttpNotAllowed);
    }

    // Validate URL format
    if !url.starts_with("https://") {
        return Err(RemoteError::InvalidUrl(url.to_string()));
    }

    // Check rate limit (unless no_cache bypasses it)
    if !no_cache && security.rate_limit_seconds > 0 {
        check_rate_limit(url, security.rate_limit_seconds)?;
    }

    // Check cache first (unless no_cache is set)
    if !no_cache {
        if let Some(cached) = read_cache(url)? {
            // Verify hash even for cached content if hash is specified
            if let Some(ref expected_hash) = security.verify_hash {
                verify_content_hash(&cached, expected_hash)?;
            }
            return Ok(cached);
        }
    }

    // Fetch from network
    let content = fetch_url_secure(url, security.ca_cert.as_deref())?;

    // Verify hash if specified
    if let Some(ref expected_hash) = security.verify_hash {
        verify_content_hash(&content, expected_hash)?;
    }

    // Write to cache (with rate limit metadata)
    if let Err(e) = write_cache_with_metadata(url, &content) {
        // Cache write failure is not fatal, just log it
        eprintln!("warning: failed to cache schema: {}", e);
    }

    Ok(content)
}

/// Verify content matches expected SHA-256 hash
pub fn verify_content_hash(content: &str, expected_hash: &str) -> Result<(), RemoteError> {
    let mut hasher = Sha256::new();
    hasher.update(content.as_bytes());
    let actual_hash = format!("{:x}", hasher.finalize());

    // Support both full hash and prefix matching (for convenience)
    let expected_lower = expected_hash.to_lowercase();
    if actual_hash == expected_lower || actual_hash.starts_with(&expected_lower) {
        Ok(())
    } else {
        Err(RemoteError::HashMismatch {
            expected: expected_hash.to_string(),
            actual: actual_hash,
        })
    }
}

/// Compute SHA-256 hash of content (useful for generating expected hashes)
pub fn compute_content_hash(content: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(content.as_bytes());
    format!("{:x}", hasher.finalize())
}

/// Perform HTTP GET request (backward compatible, uses system root certs)
#[allow(dead_code)]
fn fetch_url(url: &str) -> Result<String, RemoteError> {
    fetch_url_secure(url, None)
}

/// Perform HTTP GET request with optional custom CA certificate
fn fetch_url_secure(url: &str, ca_cert_path: Option<&str>) -> Result<String, RemoteError> {
    let tls_config = build_tls_config(ca_cert_path)?;

    let agent = ureq::Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(30)))
        .tls_config(tls_config)
        .build()
        .new_agent();

    let mut response = agent
        .get(url)
        .call()
        .map_err(|e| RemoteError::Network(e.to_string()))?;

    if response.status() != 200 {
        return Err(RemoteError::HttpStatus(format!(
            "status {} for {}",
            response.status(),
            url
        )));
    }

    response
        .body_mut()
        .read_to_string()
        .map_err(|e| RemoteError::Network(e.to_string()))
}

/// Build TLS configuration with optional custom CA certificate
fn build_tls_config(ca_cert_path: Option<&str>) -> Result<TlsConfig, RemoteError> {
    // If custom CA cert is specified, validate it exists (for future use)
    if let Some(ca_path) = ca_cert_path {
        // Verify the file exists and contains valid certificates
        let ca_file = fs::File::open(ca_path)
            .map_err(|e| RemoteError::CertificateError(format!("failed to open {}: {}", ca_path, e)))?;
        let mut ca_reader = BufReader::new(ca_file);

        let certs: Vec<CertificateDer> = rustls_pemfile::certs(&mut ca_reader)
            .filter_map(|r| r.ok())
            .collect();

        if certs.is_empty() {
            return Err(RemoteError::CertificateError(
                format!("no valid certificates found in {}", ca_path)
            ));
        }

        // Note: Custom CA certificate loading is validated but ureq 3.x
        // uses system trust store by default. For internal/self-signed certs,
        // add them to your system's trust store.
        eprintln!("zenv: CA certificate validated from {} ({} cert(s))", ca_path, certs.len());
        eprintln!("zenv: Note: Add CA to system trust store for full support");
    }

    // Default TLS config (uses system root certificates)
    Ok(TlsConfig::default())
}

/// Check rate limit for a URL
fn check_rate_limit(url: &str, rate_limit_seconds: u64) -> Result<(), RemoteError> {
    let metadata_path = match metadata_path_for_url(url) {
        Some(p) => p,
        None => return Ok(()), // No cache dir, skip rate limiting
    };

    if !metadata_path.exists() {
        return Ok(()); // No previous fetch, allow
    }

    // Read last fetch timestamp from metadata
    if let Ok(content) = fs::read_to_string(&metadata_path) {
        if let Ok(metadata) = serde_json::from_str::<CacheMetadata>(&content) {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();

            let elapsed = now.saturating_sub(metadata.fetched_at);
            if elapsed < rate_limit_seconds {
                let wait_seconds = rate_limit_seconds - elapsed;
                return Err(RemoteError::RateLimited { seconds: wait_seconds });
            }
        }
    }

    Ok(())
}

/// Cache metadata for rate limiting and integrity
#[derive(serde::Serialize, serde::Deserialize)]
struct CacheMetadata {
    url: String,
    fetched_at: u64,
    content_hash: String,
}

/// Get metadata file path for a URL
fn metadata_path_for_url(url: &str) -> Option<PathBuf> {
    cache_dir().map(|d| d.join(format!("{}.meta", cache_filename(url).trim_end_matches(".json"))))
}

/// Write schema content to cache with metadata
fn write_cache_with_metadata(url: &str, content: &str) -> Result<(), RemoteError> {
    // Write content
    write_cache(url, content)?;

    // Write metadata
    let metadata_path = match metadata_path_for_url(url) {
        Some(p) => p,
        None => return Ok(()),
    };

    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    let metadata = CacheMetadata {
        url: url.to_string(),
        fetched_at: now,
        content_hash: compute_content_hash(content),
    };

    let metadata_json = serde_json::to_string(&metadata)
        .map_err(|e| RemoteError::Cache(e.to_string()))?;

    fs::write(&metadata_path, metadata_json)
        .map_err(|e| RemoteError::Cache(e.to_string()))?;

    Ok(())
}

/// Get the cache directory path
pub fn cache_dir() -> Option<PathBuf> {
    dirs::cache_dir().map(|p| p.join("zorath-env"))
}

/// Generate cache filename from URL (simple hash)
pub fn cache_filename(url: &str) -> String {
    // Simple hash: sum of bytes mod large prime, hex encoded
    let hash: u64 = url.bytes().enumerate().fold(0u64, |acc, (i, b)| {
        acc.wrapping_add((b as u64).wrapping_mul((i as u64).wrapping_add(1)))
    });
    format!("{:016x}.json", hash)
}

/// Read cached schema if available and not expired
fn read_cache(url: &str) -> Result<Option<String>, RemoteError> {
    let cache_dir = match cache_dir() {
        Some(dir) => dir,
        None => return Ok(None),
    };

    let cache_path = cache_dir.join(cache_filename(url));

    if !cache_path.exists() {
        return Ok(None);
    }

    // Check if cache is expired
    let metadata = fs::metadata(&cache_path).map_err(|e| RemoteError::Cache(e.to_string()))?;

    let modified = metadata
        .modified()
        .map_err(|e| RemoteError::Cache(e.to_string()))?;

    let age = SystemTime::now()
        .duration_since(modified)
        .unwrap_or(Duration::MAX);

    if age.as_secs() > CACHE_TTL_SECS {
        // Cache expired
        return Ok(None);
    }

    // Read cached content
    let content = fs::read_to_string(&cache_path).map_err(|e| RemoteError::Cache(e.to_string()))?;

    Ok(Some(content))
}

/// Write schema content to cache
fn write_cache(url: &str, content: &str) -> Result<(), RemoteError> {
    let cache_dir = match cache_dir() {
        Some(dir) => dir,
        None => return Ok(()), // No cache dir available, skip caching
    };

    // Create cache directory if it doesn't exist
    fs::create_dir_all(&cache_dir).map_err(|e| RemoteError::Cache(e.to_string()))?;

    let cache_path = cache_dir.join(cache_filename(url));

    let mut file = fs::File::create(&cache_path).map_err(|e| RemoteError::Cache(e.to_string()))?;

    file.write_all(content.as_bytes())
        .map_err(|e| RemoteError::Cache(e.to_string()))?;

    Ok(())
}

/// Resolve a relative URL against a base URL
pub fn resolve_relative_url(base_url: &str, relative_path: &str) -> Result<String, RemoteError> {
    // If relative_path is already absolute, return it
    if relative_path.starts_with("https://") || relative_path.starts_with("http://") {
        return Ok(relative_path.to_string());
    }

    // Parse base URL and resolve relative path
    let base = url::Url::parse(base_url).map_err(|e| RemoteError::InvalidUrl(e.to_string()))?;

    let resolved = base
        .join(relative_path)
        .map_err(|e| RemoteError::InvalidUrl(e.to_string()))?;

    Ok(resolved.to_string())
}

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

    #[test]
    fn test_is_remote_url() {
        assert!(is_remote_url("https://example.com/schema.json"));
        assert!(is_remote_url("http://example.com/schema.json"));
        assert!(!is_remote_url("env.schema.json"));
        assert!(!is_remote_url("./schemas/env.schema.json"));
        assert!(!is_remote_url("/absolute/path/schema.json"));
    }

    #[test]
    fn test_http_rejected() {
        let result = fetch_remote_schema("http://example.com/schema.json", true);
        assert!(matches!(result, Err(RemoteError::HttpNotAllowed)));
    }

    #[test]
    fn test_cache_filename() {
        let name1 = cache_filename("https://example.com/a.json");
        let name2 = cache_filename("https://example.com/b.json");
        assert_ne!(name1, name2);
        assert!(name1.ends_with(".json"));
    }

    #[test]
    fn test_resolve_relative_url() {
        let base = "https://example.com/schemas/prod.json";

        // Relative sibling
        let resolved = resolve_relative_url(base, "base.json").unwrap();
        assert_eq!(resolved, "https://example.com/schemas/base.json");

        // Parent directory
        let resolved = resolve_relative_url(base, "../common.json").unwrap();
        assert_eq!(resolved, "https://example.com/common.json");

        // Absolute URL passthrough
        let resolved = resolve_relative_url(base, "https://other.com/schema.json").unwrap();
        assert_eq!(resolved, "https://other.com/schema.json");
    }

    // Security feature tests

    #[test]
    fn test_compute_content_hash() {
        let content = r#"{"FOO": {"type": "string"}}"#;
        let hash = compute_content_hash(content);
        // SHA-256 produces 64 hex characters
        assert_eq!(hash.len(), 64);
        // Same content should produce same hash
        assert_eq!(hash, compute_content_hash(content));
    }

    #[test]
    fn test_verify_content_hash_matches() {
        let content = "test content";
        let hash = compute_content_hash(content);

        // Full hash should match
        assert!(verify_content_hash(content, &hash).is_ok());

        // Uppercase hash should match
        assert!(verify_content_hash(content, &hash.to_uppercase()).is_ok());

        // Prefix should match (convenience feature)
        assert!(verify_content_hash(content, &hash[..16]).is_ok());
    }

    #[test]
    fn test_verify_content_hash_mismatch() {
        let content = "test content";
        let wrong_hash = "0000000000000000000000000000000000000000000000000000000000000000";

        let result = verify_content_hash(content, wrong_hash);
        assert!(matches!(result, Err(RemoteError::HashMismatch { .. })));
    }

    #[test]
    fn test_security_options_builder() {
        let opts = SecurityOptions::new()
            .with_hash(Some("abc123".to_string()))
            .with_ca_cert(Some("/path/to/cert.pem".to_string()))
            .with_rate_limit(120);

        assert_eq!(opts.verify_hash, Some("abc123".to_string()));
        assert_eq!(opts.ca_cert, Some("/path/to/cert.pem".to_string()));
        assert_eq!(opts.rate_limit_seconds, 120);
    }

    #[test]
    fn test_security_options_defaults() {
        let opts = SecurityOptions::default();
        assert_eq!(opts.verify_hash, None);
        assert_eq!(opts.ca_cert, None);
        assert_eq!(opts.rate_limit_seconds, 0); // Default trait gives 0
    }

    #[test]
    fn test_security_options_new() {
        let opts = SecurityOptions::new();
        assert_eq!(opts.verify_hash, None);
        assert_eq!(opts.ca_cert, None);
        assert_eq!(opts.rate_limit_seconds, DEFAULT_RATE_LIMIT_SECS);
    }

    #[test]
    fn test_cache_metadata_serialization() {
        let metadata = CacheMetadata {
            url: "https://example.com/schema.json".to_string(),
            fetched_at: 1234567890,
            content_hash: "abc123".to_string(),
        };

        let json = serde_json::to_string(&metadata).unwrap();
        let parsed: CacheMetadata = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.url, metadata.url);
        assert_eq!(parsed.fetched_at, metadata.fetched_at);
        assert_eq!(parsed.content_hash, metadata.content_hash);
    }

    #[test]
    fn test_http_rejected_secure() {
        let security = SecurityOptions::new();
        let result = fetch_remote_schema_secure("http://example.com/schema.json", true, &security);
        assert!(matches!(result, Err(RemoteError::HttpNotAllowed)));
    }

    #[test]
    fn test_invalid_ca_cert_path() {
        let result = build_tls_config(Some("/nonexistent/path/ca.pem"));
        assert!(matches!(result, Err(RemoteError::CertificateError(_))));
    }
}