mrapids 0.1.31

Your OpenAPI, but executable
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
/// Security utilities for MicroRapid CLI
/// Provides reusable security validation functions
use crate::core::api::ApiError;
use anyhow::Result;
use colored::*;
use std::net::IpAddr;
use std::path::Path;
use url::Url;

/// Validate URL for security (blocks SSRF attacks)
pub fn validate_url(url: &str) -> Result<()> {
    validate_url_with_options(url, false)
}

/// Validate URL for security with localhost override option
pub fn validate_url_with_options(url: &str, allow_localhost: bool) -> Result<()> {
    // Only allow HTTP and HTTPS
    if !url.starts_with("http://") && !url.starts_with("https://") {
        return Err(
            ApiError::ValidationError("Only HTTP and HTTPS URLs are allowed.".to_string()).into(),
        );
    }

    // Parse URL properly
    let parsed_url = Url::parse(url)
        .map_err(|e| ApiError::ValidationError(format!("Invalid URL format: {}", e)))?;

    // Get the host
    let host = parsed_url
        .host_str()
        .ok_or_else(|| ApiError::ValidationError("URL must have a host".to_string()))?;

    let host_lower = host.to_lowercase();

    // Check for localhost variants (unless explicitly allowed)
    if !allow_localhost {
        if host_lower == "localhost"
            || host_lower == "localhost.localdomain"
            || host_lower.starts_with("localhost:")
            || host_lower.ends_with(".local")
            || host_lower.ends_with(".localhost")
        {
            return Err(ApiError::ValidationError(
                "Access to localhost is not allowed. Use actual hostnames or IPs.\n\
                 For local development, use --allow-localhost flag."
                    .to_string(),
            )
            .into());
        }
    }

    // If host is an IP address, validate it
    if let Ok(ip) = host.parse::<IpAddr>() {
        match ip {
            IpAddr::V4(ipv4) => {
                // Check for loopback (127.0.0.0/8) unless explicitly allowed
                if !allow_localhost && ipv4.is_loopback() {
                    return Err(ApiError::ValidationError(
                        "Access to loopback addresses is not allowed.\n\
                         For local development, use --allow-localhost flag."
                            .to_string(),
                    )
                    .into());
                }

                // Check for private IP ranges (RFC 1918) unless localhost is allowed
                if !allow_localhost && ipv4.is_private() {
                    return Err(ApiError::ValidationError(
                        "Access to private IP ranges is not allowed for security reasons.\n\
                         For local development, use --allow-localhost flag."
                            .to_string(),
                    )
                    .into());
                }

                // Check for link-local (169.254.0.0/16)
                if ipv4.is_link_local() {
                    return Err(ApiError::ValidationError(
                        "Access to link-local addresses is not allowed.".to_string(),
                    )
                    .into());
                }

                // Check for broadcast
                if ipv4.is_broadcast() {
                    return Err(ApiError::ValidationError(
                        "Access to broadcast addresses is not allowed.".to_string(),
                    )
                    .into());
                }

                // Check for unspecified (0.0.0.0)
                if ipv4.is_unspecified() {
                    return Err(ApiError::ValidationError(
                        "Access to unspecified addresses is not allowed.".to_string(),
                    )
                    .into());
                }

                // Check for multicast
                if ipv4.is_multicast() {
                    return Err(ApiError::ValidationError(
                        "Access to multicast addresses is not allowed.".to_string(),
                    )
                    .into());
                }

                // Explicitly check cloud metadata endpoint
                if ipv4.octets() == [169, 254, 169, 254] {
                    return Err(ApiError::ValidationError(
                        "Access to cloud metadata endpoints is not allowed.".to_string(),
                    )
                    .into());
                }
            }
            IpAddr::V6(ipv6) => {
                // Check for loopback (::1)
                if ipv6.is_loopback() {
                    return Err(ApiError::ValidationError(
                        "Access to loopback addresses is not allowed.".to_string(),
                    )
                    .into());
                }

                // Check for unspecified (::)
                if ipv6.is_unspecified() {
                    return Err(ApiError::ValidationError(
                        "Access to unspecified addresses is not allowed.".to_string(),
                    )
                    .into());
                }

                // Check for multicast
                if ipv6.is_multicast() {
                    return Err(ApiError::ValidationError(
                        "Access to multicast addresses is not allowed.".to_string(),
                    )
                    .into());
                }

                // Check for IPv4-mapped IPv6 addresses
                if let Some(ipv4) = ipv6.to_ipv4_mapped() {
                    if ipv4.is_loopback() || ipv4.is_private() || ipv4.is_link_local() {
                        return Err(ApiError::ValidationError(
                            "Access to private/local addresses via IPv6 mapping is not allowed."
                                .to_string(),
                        )
                        .into());
                    }
                }
            }
        }
    }

    // Block known cloud metadata endpoints by hostname
    let blocked_hosts = [
        "metadata.google.internal",
        "metadata.google",
        "metadata.goog",
        "metadata.amazon",
        "metadata.azure",
        "instance-data",
        "instance.metadata",
    ];

    for blocked in &blocked_hosts {
        if host_lower.contains(blocked) {
            return Err(ApiError::ValidationError(
                "Access to cloud metadata endpoints is not allowed.".to_string(),
            )
            .into());
        }
    }

    // Block file:// and other dangerous protocols (redundant but explicit)
    match parsed_url.scheme() {
        "http" | "https" => Ok(()),
        _ => Err(ApiError::ValidationError(
            "Only HTTP and HTTPS protocols are allowed.".to_string(),
        )
        .into()),
    }
}

/// Check if URL uses HTTPS and enforce security policy
pub fn enforce_https(url: &str, allow_insecure: bool) -> Result<()> {
    enforce_https_with_options(url, allow_insecure, false)
}

/// Check if URL uses HTTPS and enforce security policy with localhost override
pub fn enforce_https_with_options(
    url: &str,
    allow_insecure: bool,
    allow_localhost: bool,
) -> Result<()> {
    // First validate the URL for other security issues
    validate_url_with_options(url, allow_localhost)?;

    // Check if it's HTTP
    if url.starts_with("http://") && !allow_insecure {
        let url_lower = url.to_lowercase();
        let is_loopback = url_lower.starts_with("http://localhost")
            || url_lower.starts_with("http://127.0.0.1")
            || url_lower.starts_with("http://[::1]")
            || url_lower.starts_with("http://0.0.0.0");

        // --allow-localhost implies --allow-insecure for loopback addresses.
        // Loopback traffic never leaves the machine, so HTTPS adds no security.
        if is_loopback && allow_localhost {
            // Fall through to the warning below
        } else if is_loopback {
            return Err(ApiError::ValidationError(
                "HTTP localhost access requires --allow-localhost flag.\n\
                 For local development: mrapids run <op> --allow-localhost"
                    .to_string(),
            )
            .into());
        } else {
            return Err(ApiError::ValidationError(format!(
                "Insecure HTTP connection blocked: {}\n\
                 \n\
                 {} {}\n\
                 \n\
                 HTTP connections are vulnerable to:\n\
                 • Man-in-the-middle attacks\n\
                 • Credential theft\n\
                 • Data tampering\n\
                 \n\
                 To use HTTP anyway (NOT RECOMMENDED):\n\
                 Add --allow-insecure flag to your command\n\
                 \n\
                 Better solution: Use HTTPS URLs",
                url,
                "⚠️".red().bold(),
                "SECURITY WARNING".red().bold()
            ))
            .into());
        }
    }

    // If HTTP is allowed, show a warning (skip verbose warning for localhost)
    if url.starts_with("http://") && (allow_insecure || allow_localhost) {
        let url_lower = url.to_lowercase();
        let is_loopback = url_lower.starts_with("http://localhost")
            || url_lower.starts_with("http://127.0.0.1")
            || url_lower.starts_with("http://[::1]")
            || url_lower.starts_with("http://0.0.0.0");

        if is_loopback && !allow_insecure {
            // Lightweight warning for localhost — no scary ASCII box
            eprintln!("{} Using HTTP for localhost ({})", "ℹ️".dimmed(), url);
        } else {
            eprintln!("\n{}", "".repeat(60).red());
            eprintln!(
                "{} {} {}",
                "⚠️".red().bold(),
                "INSECURE CONNECTION WARNING".red().bold(),
                "⚠️".red().bold()
            );
            eprintln!("{}", "".repeat(60).red());
            eprintln!("{} Using insecure HTTP connection to:", "⚠️".yellow());
            eprintln!("   {}", url.yellow());
            eprintln!();
            eprintln!(
                "{}",
                "This connection is NOT encrypted and vulnerable to:".red()
            );
            eprintln!("{} Man-in-the-middle attacks", "".red());
            eprintln!("{} Credential and API key theft", "".red());
            eprintln!("{} Data tampering and injection", "".red());
            eprintln!("{} Request/response interception", "".red());
            eprintln!();
            eprintln!(
                "{} {}",
                "👉".cyan(),
                "Recommendation: Use HTTPS instead".cyan().bold()
            );
            eprintln!("{}", "".repeat(60).red());
            eprintln!();
        }
    }

    Ok(())
}

/// Validate file path for reads (prevents directory traversal)
pub fn validate_file_path(path: &Path) -> Result<()> {
    let path_str = path.to_string_lossy();

    // Block path traversal
    if path_str.contains("..") {
        return Err(ApiError::ValidationError("Path traversal is not allowed".to_string()).into());
    }

    // Block access to sensitive system files
    let blocked_paths = [
        "/etc/passwd",
        "/etc/shadow",
        "/etc/sudoers",
        "/.ssh/",
        "/root/",
        "/proc/",
        "/sys/",
        "/.aws/",
        "/.kube/",
        "/.docker/",
        "/.git/credentials",
        "/.netrc",
        "/.npmrc",
    ];

    for blocked in &blocked_paths {
        if path_str.contains(blocked) {
            return Err(
                ApiError::ValidationError(format!("Access to {} is not allowed", blocked)).into(),
            );
        }
    }

    // Block Windows sensitive paths
    if cfg!(windows) {
        let blocked_windows = [
            "C:\\Windows\\System32",
            "C:\\Windows\\System",
            "C:\\Program Files",
        ];
        for blocked in &blocked_windows {
            if path_str.contains(blocked) {
                return Err(ApiError::ValidationError(format!(
                    "Access to {} is not allowed",
                    blocked
                ))
                .into());
            }
        }
    }

    Ok(())
}

/// Validate output path for writes (additional restrictions)
pub fn validate_output_path(path: &Path) -> Result<()> {
    // First do all read validations
    validate_file_path(path)?;

    let path_str = path.to_string_lossy();

    // Block writing to system directories
    let blocked_write_paths = [
        "/usr/",
        "/bin/",
        "/sbin/",
        "/lib/",
        "/lib64/",
        "/etc/",
        "/boot/",
        "/dev/",
        "/opt/",
        "/var/lib/",
        "/var/run/",
    ];

    for blocked in &blocked_write_paths {
        if path_str.starts_with(blocked) {
            return Err(ApiError::ValidationError(format!(
                "Cannot write to system directory: {}",
                blocked
            ))
            .into());
        }
    }

    // Block Windows system directories
    if cfg!(windows) {
        let blocked_windows = [
            "C:\\Windows",
            "C:\\Program Files",
            "C:\\ProgramData",
            "C:\\System",
        ];
        for blocked in &blocked_windows {
            if path_str.starts_with(blocked) {
                return Err(ApiError::ValidationError(format!(
                    "Cannot write to system directory: {}",
                    blocked
                ))
                .into());
            }
        }
    }

    Ok(())
}

/// Validate directory for deletion operations
pub fn validate_delete_path(path: &Path) -> Result<()> {
    validate_output_path(path)?;

    let path_str = path.to_string_lossy();

    // Extra restrictions for deletions
    let critical_paths = ["/", "/home", "/Users", "~", ".", ".."];

    for critical in &critical_paths {
        if path_str == *critical || path_str.ends_with(critical) {
            return Err(ApiError::ValidationError(format!(
                "Cannot delete critical directory: {}",
                critical
            ))
            .into());
        }
    }

    Ok(())
}

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

    #[test]
    fn test_url_validation() {
        // Should block
        assert!(validate_url("http://localhost/api").is_err());
        assert!(validate_url("http://127.0.0.1/api").is_err());
        assert!(validate_url("http://192.168.1.1/api").is_err());
        assert!(validate_url("http://10.0.0.1/api").is_err());
        assert!(validate_url("http://172.16.0.1/api").is_err());
        assert!(validate_url("http://169.254.169.254/metadata").is_err());
        assert!(validate_url("file:///etc/passwd").is_err());

        // Should allow
        assert!(validate_url("https://api.example.com").is_ok());
        assert!(validate_url("http://8.8.8.8/api").is_ok());
    }

    #[test]
    fn test_file_path_validation() {
        // Should block
        assert!(validate_file_path(Path::new("/etc/passwd")).is_err());
        assert!(validate_file_path(Path::new("../../../etc/passwd")).is_err());
        assert!(validate_file_path(Path::new("/home/user/.ssh/id_rsa")).is_err());

        // Should allow
        assert!(validate_file_path(Path::new("/home/user/project/api.yaml")).is_ok());
        assert!(validate_file_path(Path::new("./specs/api.yaml")).is_ok());
    }

    #[test]
    fn test_output_path_validation() {
        // Should block
        assert!(validate_output_path(Path::new("/etc/test.yaml")).is_err());
        assert!(validate_output_path(Path::new("/usr/bin/test")).is_err());

        // Should allow
        assert!(validate_output_path(Path::new("/tmp/test.yaml")).is_ok());
        assert!(validate_output_path(Path::new("./output/sdk/")).is_ok());
    }
}