icookforms 0.1.0

The World's Reference Cookie Audit Software - Complete Security & Compliance Analysis
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
//! Output formatting utilities for CLI
//!
//! This module provides utilities for formatting and displaying output in various formats.

use crate::types::{AnalysisResult, ComplianceResult, ScanResult, Severity};
use colored::{ColoredString, Colorize};

/// Format and print a scan result
pub fn print_scan_result(
    result: &ScanResult,
    format: &super::OutputFormat,
) -> crate::types::Result<()> {
    match format {
        super::OutputFormat::Human => {
            print_scan_result_human(result);
            Ok(())
        }
        super::OutputFormat::Json => print_scan_result_json(result),
        super::OutputFormat::Yaml => print_scan_result_yaml(result),
        super::OutputFormat::Csv => {
            print_scan_result_csv(result);
            Ok(())
        }
    }
}

/// Format and print an analysis result
pub fn print_analysis_result(
    result: &AnalysisResult,
    format: &super::OutputFormat,
) -> crate::types::Result<()> {
    match format {
        super::OutputFormat::Human => {
            print_analysis_result_human(result);
            Ok(())
        }
        super::OutputFormat::Json => print_analysis_result_json(result),
        super::OutputFormat::Yaml => print_analysis_result_yaml(result),
        super::OutputFormat::Csv => {
            print_analysis_result_csv(result);
            Ok(())
        }
    }
}

/// Format and print a compliance result
pub fn print_compliance_result(
    result: &ComplianceResult,
    format: &super::OutputFormat,
) -> crate::types::Result<()> {
    match format {
        super::OutputFormat::Human => {
            print_compliance_result_human(result);
            Ok(())
        }
        super::OutputFormat::Json => print_compliance_result_json(result),
        super::OutputFormat::Yaml => print_compliance_result_yaml(result),
        super::OutputFormat::Csv => {
            print_compliance_result_csv(result);
            Ok(())
        }
    }
}

// ============================================================================
// HUMAN FORMAT (with colors and formatting)
// ============================================================================

fn print_scan_result_human(result: &ScanResult) {
    println!("\n{}", "=".repeat(80).bright_blue());
    println!("{}", "SCAN RESULTS".bright_cyan().bold());
    println!("{}", "=".repeat(80).bright_blue());

    println!("\n{} {}", "Target URL:".bold(), result.url);
    println!("{} {}", "Scan ID:".bold(), result.id);
    println!("{} {:?}", "Status:".bold(), result.status);

    // Statistics
    println!("\n{}", "Statistics:".bold().underline());
    println!(
        "  {} {}",
        "Cookies found:".bold(),
        result.cookies.len().to_string().green()
    );
    println!("  {} {}", "Pages scanned:".bold(), result.pages_scanned);
    println!("  {} {}", "Requests made:".bold(), result.requests_made);

    if !result.errors.is_empty() {
        println!("\n{}", "Errors:".red().bold());
        for (i, error) in result.errors.iter().enumerate() {
            println!("  {}. {}", i + 1, error.red());
        }
    }

    // Cookie summary
    if !result.cookies.is_empty() {
        println!("\n{}", "Top Cookies:".bold().underline());
        for (i, cookie) in result.cookies.iter().take(5).enumerate() {
            println!(
                "  {}. {} = {} (domain: {})",
                i + 1,
                cookie.name.bold(),
                if cookie.value.len() > 30 {
                    format!("{}...", &cookie.value[..30])
                } else {
                    cookie.value.clone()
                },
                cookie.domain.as_deref().unwrap_or("N/A")
            );
        }

        if result.cookies.len() > 5 {
            println!("  ... and {} more", result.cookies.len() - 5);
        }
    }

    println!();
}

fn print_analysis_result_human(result: &AnalysisResult) {
    println!("\n{}", "=".repeat(80).bright_blue());
    println!("{}", "ANALYSIS RESULTS".bright_cyan().bold());
    println!("{}", "=".repeat(80).bright_blue());

    println!("\n{} {}", "Analysis ID:".bold(), result.id);

    // Scores
    println!("\n{}", "Scores:".bold().underline());
    println!(
        "  {} {}/100",
        "Risk Score:".bold(),
        format_score(result.risk_score)
    );
    println!(
        "  {} {}/100",
        "Privacy Score:".bold(),
        format_score(result.privacy_score)
    );
    println!(
        "  {} {}/100",
        "Compliance Score:".bold(),
        format_score(result.compliance_score)
    );

    // Security Issues
    if result.security_issues.is_empty() {
        println!("\n{} None found", "Security Issues:".green().bold());
    } else {
        println!(
            "\n{} ({})",
            "Security Issues:".red().bold(),
            result.security_issues.len()
        );
        for (i, issue) in result.security_issues.iter().take(10).enumerate() {
            let severity_str = format_severity(issue.issue.severity);
            println!(
                "  {}. [{}] {:?}: {}",
                i + 1,
                severity_str,
                issue.issue.category,
                issue.issue.description
            );
        }

        if result.security_issues.len() > 10 {
            println!(
                "  ... and {} more issues",
                result.security_issues.len() - 10
            );
        }
    }

    // Compliance Issues
    if result.compliance_issues.is_empty() {
        println!("\n{} None found", "Compliance Issues:".green().bold());
    } else {
        println!(
            "\n{} ({})",
            "Compliance Issues:".yellow().bold(),
            result.compliance_issues.len()
        );
        for (i, issue) in result.compliance_issues.iter().take(10).enumerate() {
            let severity_str = format_severity(issue.issue.severity);
            println!(
                "  {}. [{}] {:?}: {}",
                i + 1,
                severity_str,
                issue.regulation,
                issue.issue.description
            );
        }

        if result.compliance_issues.len() > 10 {
            println!(
                "  ... and {} more issues",
                result.compliance_issues.len() - 10
            );
        }
    }

    println!();
}

fn print_compliance_result_human(result: &ComplianceResult) {
    println!("\n{}", "=".repeat(80).bright_blue());
    println!("{}", "COMPLIANCE RESULTS".bright_cyan().bold());
    println!("{}", "=".repeat(80).bright_blue());

    println!("\n{} {}", "Compliance ID:".bold(), result.id);
    println!("{} {:?}", "Regulation:".bold(), result.regulation);
    println!(
        "{} {}",
        "Checked at:".bold(),
        result.checked_at.format("%Y-%m-%d %H:%M:%S UTC")
    );

    // Compliance status
    println!("\n{}", "Status:".bold().underline());
    if result.compliant {
        println!("  {} {}", "Compliant:".green().bold(), "YES ✓".green());
    } else {
        println!("  {} {}", "Compliant:".red().bold(), "NO ✗".red());
    }
    println!("  {} {}/100", "Score:".bold(), format_score(result.score));

    // Statistics
    println!("\n{}", "Statistics:".bold().underline());
    println!(
        "  {} {}",
        "Compliant cookies:".green(),
        result.compliant_cookies
    );
    println!(
        "  {} {}",
        "Non-compliant cookies:".red(),
        result.non_compliant_cookies
    );

    // Issues
    if !result.issues.is_empty() {
        println!("\n{} ({})", "Issues:".red().bold(), result.issues.len());
        for (i, issue) in result.issues.iter().take(10).enumerate() {
            let severity_str = format_severity(issue.issue.severity);
            println!(
                "  {}. [{}] {}",
                i + 1,
                severity_str,
                issue.issue.description
            );
        }

        if result.issues.len() > 10 {
            println!("  ... and {} more issues", result.issues.len() - 10);
        }
    }

    // Recommendations
    if !result.recommendations.is_empty() {
        println!("\n{}", "Recommendations:".yellow().bold());
        for (i, rec) in result.recommendations.iter().take(5).enumerate() {
            println!("  {}. {}", i + 1, rec);
        }
    }

    println!();
}

// ============================================================================
// JSON FORMAT
// ============================================================================

fn print_scan_result_json(result: &ScanResult) -> crate::types::Result<()> {
    let json = serde_json::to_string_pretty(result)
        .map_err(|e| crate::types::Error::reporter(format!("JSON serialization error: {e}")))?;
    println!("{json}");
    Ok(())
}

fn print_analysis_result_json(result: &AnalysisResult) -> crate::types::Result<()> {
    let json = serde_json::to_string_pretty(result)
        .map_err(|e| crate::types::Error::reporter(format!("JSON serialization error: {e}")))?;
    println!("{json}");
    Ok(())
}

fn print_compliance_result_json(result: &ComplianceResult) -> crate::types::Result<()> {
    let json = serde_json::to_string_pretty(result)
        .map_err(|e| crate::types::Error::reporter(format!("JSON serialization error: {e}")))?;
    println!("{json}");
    Ok(())
}

// ============================================================================
// YAML FORMAT
// ============================================================================

fn print_scan_result_yaml(result: &ScanResult) -> crate::types::Result<()> {
    let yaml = serde_yaml::to_string(result)
        .map_err(|e| crate::types::Error::reporter(format!("YAML serialization error: {e}")))?;
    println!("{yaml}");
    Ok(())
}

fn print_analysis_result_yaml(result: &AnalysisResult) -> crate::types::Result<()> {
    let yaml = serde_yaml::to_string(result)
        .map_err(|e| crate::types::Error::reporter(format!("YAML serialization error: {e}")))?;
    println!("{yaml}");
    Ok(())
}

fn print_compliance_result_yaml(result: &ComplianceResult) -> crate::types::Result<()> {
    let yaml = serde_yaml::to_string(result)
        .map_err(|e| crate::types::Error::reporter(format!("YAML serialization error: {e}")))?;
    println!("{yaml}");
    Ok(())
}

// ============================================================================
// CSV FORMAT
// ============================================================================

fn print_scan_result_csv(result: &ScanResult) {
    println!("name,value,domain,path,secure,http_only,same_site,expires");
    for cookie in &result.cookies {
        println!(
            "{},{},{},{},{},{},{},{}",
            csv_escape(&cookie.name),
            csv_escape(&cookie.value),
            csv_escape(cookie.domain.as_deref().unwrap_or("")),
            csv_escape(cookie.path.as_deref().unwrap_or("")),
            cookie.secure,
            cookie.http_only,
            cookie
                .same_site
                .as_ref()
                .map(|s| format!("{s:?}"))
                .unwrap_or_default(),
            cookie.expires.map(|e| e.to_rfc3339()).unwrap_or_default()
        );
    }
}

fn print_analysis_result_csv(_result: &AnalysisResult) {
    println!("Analysis results in CSV format not yet implemented");
}

fn print_compliance_result_csv(_result: &ComplianceResult) {
    println!("Compliance results in CSV format not yet implemented");
}

// ============================================================================
// HELPER FUNCTIONS
// ============================================================================

fn format_score(score: f32) -> ColoredString {
    let score_str = format!("{score:.1}");
    if score >= 80.0 {
        score_str.green()
    } else if score >= 60.0 {
        score_str.yellow()
    } else {
        score_str.red()
    }
}

fn format_severity(severity: Severity) -> ColoredString {
    match severity {
        Severity::Critical => "CRITICAL".red().bold(),
        Severity::High => "HIGH".red(),
        Severity::Medium => "MEDIUM".yellow(),
        Severity::Low => "LOW".blue(),
        Severity::Info => "INFO".normal(),
    }
}

fn csv_escape(s: &str) -> String {
    if s.contains(',') || s.contains('"') || s.contains('\n') {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}

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

    #[test]
    fn test_csv_escape() {
        assert_eq!(csv_escape("simple"), "simple");
        assert_eq!(csv_escape("with,comma"), "\"with,comma\"");
        assert_eq!(csv_escape("with\"quote"), "\"with\"\"quote\"");
    }

    #[test]
    fn test_format_score() {
        let high = format_score(90.0);
        let medium = format_score(70.0);
        let low = format_score(40.0);

        // Just check they don't panic
        assert!(!high.to_string().is_empty());
        assert!(!medium.to_string().is_empty());
        assert!(!low.to_string().is_empty());
    }
}