repolens 2.0.0

A CLI tool to audit and prepare repositories for open source or enterprise standards
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
//! CODEOWNERS and Releases rules
//!
//! This module provides rules for checking:
//! - CODEOWNERS file presence and validity
//! - GitHub releases and tags
//!
//! ## Rules
//!
//! ### CODEOWNERS Rules
//! - CODE001 (info): CODEOWNERS file is missing
//! - CODE002 (warning): CODEOWNERS file has syntax errors
//! - CODE003 (warning): CODEOWNERS references non-existent users/teams
//!
//! ### Release Rules
//! - REL001 (info): No releases published
//! - REL002 (warning): Last release is older than 1 year
//! - REL003 (info): Tags are not signed

use crate::config::Config;
use crate::error::RepoLensError;
use crate::rules::engine::RuleCategory;
use crate::rules::results::{Finding, Severity};
use crate::scanner::Scanner;
use chrono::{DateTime, Utc};
use regex::Regex;
use serde::Deserialize;
use std::process::Command;

/// Rules for checking CODEOWNERS and releases
pub struct CodeownersRules;

#[async_trait::async_trait]
impl RuleCategory for CodeownersRules {
    fn name(&self) -> &'static str {
        "codeowners"
    }

    async fn run(&self, scanner: &Scanner, config: &Config) -> Result<Vec<Finding>, RepoLensError> {
        let mut findings = Vec::new();

        // CODEOWNERS rules
        if config.is_rule_enabled("codeowners/presence") {
            findings.extend(check_codeowners_presence(scanner, config));
        }

        if config.is_rule_enabled("codeowners/syntax") {
            findings.extend(check_codeowners_syntax(scanner));
        }

        if config.is_rule_enabled("codeowners/valid-owners") {
            findings.extend(check_codeowners_valid_owners(scanner).await);
        }

        // Release rules
        if config.is_rule_enabled("codeowners/releases") {
            findings.extend(check_releases().await);
        }

        if config.is_rule_enabled("codeowners/signed-tags") {
            findings.extend(check_signed_tags(scanner));
        }

        Ok(findings)
    }
}

/// CODEOWNERS file locations (in order of preference)
const CODEOWNERS_PATHS: &[&str] = &["CODEOWNERS", ".github/CODEOWNERS", "docs/CODEOWNERS"];

/// Find CODEOWNERS file if it exists
fn find_codeowners(scanner: &Scanner) -> Option<(String, String)> {
    for path in CODEOWNERS_PATHS {
        if scanner.file_exists(path) {
            if let Ok(content) = scanner.read_file(path) {
                return Some((path.to_string(), content));
            }
        }
    }
    None
}

/// CODE001: Check if CODEOWNERS file exists
fn check_codeowners_presence(scanner: &Scanner, config: &Config) -> Vec<Finding> {
    let mut findings = Vec::new();

    if find_codeowners(scanner).is_none() {
        let severity = if config.preset == "enterprise" {
            Severity::Critical
        } else {
            Severity::Info
        };

        findings.push(
            Finding::new(
                "CODE001",
                "codeowners",
                severity,
                "CODEOWNERS file is missing",
            )
            .with_description(
                "A CODEOWNERS file automatically assigns reviewers to pull requests \
                 based on file paths. This ensures code changes are reviewed by the \
                 appropriate team members.",
            )
            .with_remediation(
                "Create a CODEOWNERS file in .github/, the repository root, or docs/.\n\
                 Example content:\n\
                 # Default owners for everything\n\
                 * @org/team-name\n\n\
                 # Frontend code\n\
                 /src/frontend/ @org/frontend-team\n\n\
                 # Documentation\n\
                 /docs/ @org/docs-team",
            ),
        );
    }

    findings
}

/// CODE002: Check CODEOWNERS syntax
fn check_codeowners_syntax(scanner: &Scanner) -> Vec<Finding> {
    let mut findings = Vec::new();

    let Some((path, content)) = find_codeowners(scanner) else {
        return findings;
    };

    let syntax_errors = validate_codeowners_syntax(&content);

    for (line_num, error) in syntax_errors {
        findings.push(
            Finding::new(
                "CODE002",
                "codeowners",
                Severity::Warning,
                format!("CODEOWNERS syntax error on line {}: {}", line_num, error),
            )
            .with_location(format!("{}:{}", path, line_num))
            .with_description(
                "CODEOWNERS files must follow a specific syntax. Each line should contain \
                 a file pattern followed by one or more owners (GitHub usernames or team names).",
            )
            .with_remediation(
                "Fix the syntax error. Valid formats:\n\
                 - `* @owner` - All files\n\
                 - `/path/ @owner` - Specific directory\n\
                 - `*.js @owner` - File pattern\n\
                 - `# comment` - Comment line",
            ),
        );
    }

    findings
}

/// Validate CODEOWNERS file syntax and return errors with line numbers
fn validate_codeowners_syntax(content: &str) -> Vec<(usize, String)> {
    let mut errors = Vec::new();

    // Pattern for valid owner references: @user, @org/team, or email
    let owner_pattern =
        Regex::new(r"^(@[\w\-\.]+(/[\w\-\.]+)?|[\w\-\.]+@[\w\-\.]+\.\w+)$").unwrap();

    // Pattern for valid file patterns (basic glob check)
    let file_pattern = Regex::new(r"^[/\*\w\.\-\[\]{}!?]+$").unwrap();

    for (line_num, line) in content.lines().enumerate() {
        let line_num = line_num + 1; // 1-indexed
        let line = line.trim();

        // Skip empty lines and comments
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        // Split into parts
        let parts: Vec<&str> = line.split_whitespace().collect();

        if parts.is_empty() {
            continue;
        }

        // First part should be a file pattern
        let pattern = parts[0];

        // Check for basic pattern validity
        if !file_pattern.is_match(pattern) && !pattern.contains('/') && pattern != "*" {
            errors.push((line_num, format!("Invalid file pattern: '{}'", pattern)));
            continue;
        }

        // Must have at least one owner
        if parts.len() < 2 {
            errors.push((line_num, "No owners specified for pattern".to_string()));
            continue;
        }

        // Validate each owner
        for owner in &parts[1..] {
            if !owner_pattern.is_match(owner) {
                errors.push((
                    line_num,
                    format!(
                        "Invalid owner format: '{}'. Must be @username, @org/team, or email",
                        owner
                    ),
                ));
            }
        }
    }

    errors
}

/// CODE003: Check if CODEOWNERS references valid users/teams
async fn check_codeowners_valid_owners(scanner: &Scanner) -> Vec<Finding> {
    let mut findings = Vec::new();

    let Some((path, content)) = find_codeowners(scanner) else {
        return findings;
    };

    // Extract all owner references
    let owners = extract_owners(&content);

    // Try to validate via GitHub API
    let invalid_owners = validate_owners_via_github(&owners).await;

    for (owner, line_num) in invalid_owners {
        findings.push(
            Finding::new(
                "CODE003",
                "codeowners",
                Severity::Warning,
                format!("CODEOWNERS references potentially invalid owner: {}", owner),
            )
            .with_location(format!("{}:{}", path, line_num))
            .with_description(
                "The referenced user or team may not exist or may not have access to \
                 this repository. GitHub will not assign them as reviewers.",
            )
            .with_remediation(
                "Verify that the user/team exists and has access to this repository:\n\
                 - For users: Check the username is correct\n\
                 - For teams: Use the format @org/team-name\n\
                 - Ensure the user/team has at least read access to the repository",
            ),
        );
    }

    findings
}

/// Extract all owner references with line numbers from CODEOWNERS content
fn extract_owners(content: &str) -> Vec<(String, usize)> {
    let mut owners = Vec::new();
    let owner_pattern = Regex::new(r"@[\w\-\.]+(/[\w\-\.]+)?").unwrap();

    for (line_num, line) in content.lines().enumerate() {
        let line_num = line_num + 1;
        let line = line.trim();

        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        for cap in owner_pattern.find_iter(line) {
            owners.push((cap.as_str().to_string(), line_num));
        }
    }

    owners
}

/// Validate owners via GitHub API (returns invalid ones)
async fn validate_owners_via_github(owners: &[(String, usize)]) -> Vec<(String, usize)> {
    let mut invalid = Vec::new();

    for (owner, line_num) in owners {
        let owner_name = owner.trim_start_matches('@');

        // Check if it's a team reference (contains /)
        let is_valid = if owner_name.contains('/') {
            // Team reference: @org/team
            check_team_exists(owner_name)
        } else {
            // User reference: @username
            check_user_exists(owner_name)
        };

        if !is_valid {
            invalid.push((owner.clone(), *line_num));
        }
    }

    invalid
}

/// Check if a GitHub user exists using gh CLI
fn check_user_exists(username: &str) -> bool {
    let output = Command::new("gh")
        .args(["api", &format!("users/{}", username)])
        .output();

    match output {
        Ok(o) => o.status.success(),
        Err(_) => true, // If gh is not available, assume valid
    }
}

/// Check if a GitHub team exists using gh CLI
fn check_team_exists(team_ref: &str) -> bool {
    let parts: Vec<&str> = team_ref.split('/').collect();
    if parts.len() != 2 {
        return false;
    }

    let org = parts[0];
    let team = parts[1];

    let output = Command::new("gh")
        .args(["api", &format!("orgs/{}/teams/{}", org, team)])
        .output();

    match output {
        Ok(o) => o.status.success(),
        Err(_) => true, // If gh is not available, assume valid
    }
}

/// GitHub Release structure
#[derive(Debug, Deserialize)]
struct Release {
    #[serde(rename = "tagName")]
    tag_name: String,
    #[serde(rename = "publishedAt")]
    published_at: String,
    #[serde(rename = "isDraft")]
    is_draft: bool,
}

/// REL001 & REL002: Check releases
async fn check_releases() -> Vec<Finding> {
    let mut findings = Vec::new();

    // Get releases via gh CLI
    let output = Command::new("gh")
        .args([
            "release",
            "list",
            "--json",
            "tagName,publishedAt,isDraft",
            "--limit",
            "10",
        ])
        .output();

    let releases: Vec<Release> = match output {
        Ok(o) if o.status.success() => serde_json::from_slice(&o.stdout).unwrap_or_default(),
        _ => {
            // gh CLI not available or failed - skip these checks
            return findings;
        }
    };

    // Filter out drafts
    let published_releases: Vec<&Release> = releases.iter().filter(|r| !r.is_draft).collect();

    // REL001: No releases
    if published_releases.is_empty() {
        findings.push(
            Finding::new(
                "REL001",
                "codeowners",
                Severity::Info,
                "No releases have been published",
            )
            .with_description(
                "GitHub releases help users track versions and changes. Publishing releases \
                 makes it easier for users to download specific versions and see changelogs.",
            )
            .with_remediation(
                "Create a release using GitHub's release feature or the gh CLI:\n\
                 gh release create v1.0.0 --title \"v1.0.0\" --notes \"Initial release\"\n\n\
                 Consider using semantic versioning (MAJOR.MINOR.PATCH).",
            ),
        );
        return findings;
    }

    // REL002: Check if last release is older than 1 year
    if let Some(latest) = published_releases.first() {
        if let Ok(published) = DateTime::parse_from_rfc3339(&latest.published_at) {
            let now = Utc::now();
            let age = now.signed_duration_since(published.with_timezone(&Utc));

            if age.num_days() > 365 {
                let years = age.num_days() / 365;
                findings.push(
                    Finding::new(
                        "REL002",
                        "codeowners",
                        Severity::Warning,
                        format!(
                            "Last release ({}) is over {} year(s) old",
                            latest.tag_name, years
                        ),
                    )
                    .with_description(
                        "Having outdated releases may indicate the project is unmaintained \
                         or that users are not getting the latest features and fixes.",
                    )
                    .with_remediation(
                        "Consider creating a new release with the latest changes:\n\
                         gh release create vX.Y.Z --generate-notes\n\n\
                         If the project is actively maintained, regular releases help users \
                         track progress and adopt new features.",
                    ),
                );
            }
        }
    }

    findings
}

/// REL003: Check for unsigned tags
fn check_signed_tags(scanner: &Scanner) -> Vec<Finding> {
    let mut findings = Vec::new();

    // Get tags and check if they're signed
    let output = Command::new("git")
        .args(["tag", "-l", "--format=%(refname:short) %(objecttype)"])
        .current_dir(scanner.root())
        .output();

    let tags_output = match output {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(),
        _ => return findings,
    };

    let tags: Vec<&str> = tags_output.lines().collect();

    if tags.is_empty() {
        return findings;
    }

    // Check for signed tags
    let mut unsigned_tags = Vec::new();

    for line in &tags {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 2 {
            let tag_name = parts[0];
            let object_type = parts[1];

            // Annotated tags have type "tag", lightweight have "commit"
            // For annotated tags, check signature
            if object_type == "tag" {
                let verify = Command::new("git")
                    .args(["tag", "-v", tag_name])
                    .current_dir(scanner.root())
                    .output();

                match verify {
                    Ok(o) if !o.status.success() => {
                        unsigned_tags.push(tag_name.to_string());
                    }
                    _ => {}
                }
            } else {
                // Lightweight tags are never signed
                unsigned_tags.push(tag_name.to_string());
            }
        }
    }

    if !unsigned_tags.is_empty() {
        let tag_list = if unsigned_tags.len() > 5 {
            format!(
                "{} and {} more",
                unsigned_tags[..5].join(", "),
                unsigned_tags.len() - 5
            )
        } else {
            unsigned_tags.join(", ")
        };

        findings.push(
            Finding::new(
                "REL003",
                "codeowners",
                Severity::Info,
                format!("Unsigned tags found: {}", tag_list),
            )
            .with_description(
                "Signed tags provide cryptographic proof of authenticity, helping users \
                 verify that releases came from a trusted source.",
            )
            .with_remediation(
                "Create signed tags using GPG:\n\
                 1. Set up GPG signing: git config --global user.signingkey YOUR_KEY_ID\n\
                 2. Create signed tag: git tag -s v1.0.0 -m \"Version 1.0.0\"\n\n\
                 For existing tags, you can recreate them as signed tags.",
            ),
        );
    }

    findings
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // ===== CODEOWNERS Presence Tests (CODE001) =====

    #[test]
    fn test_check_codeowners_presence_missing() {
        let temp_dir = TempDir::new().unwrap();
        let scanner = Scanner::new(temp_dir.path().to_path_buf());
        let config = Config::default();

        let findings = check_codeowners_presence(&scanner, &config);

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule_id, "CODE001");
        assert_eq!(findings[0].severity, Severity::Info);
    }

    #[test]
    fn test_check_codeowners_presence_missing_enterprise() {
        let temp_dir = TempDir::new().unwrap();
        let scanner = Scanner::new(temp_dir.path().to_path_buf());
        let config = Config {
            preset: "enterprise".to_string(),
            ..Default::default()
        };

        let findings = check_codeowners_presence(&scanner, &config);

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule_id, "CODE001");
        assert_eq!(findings[0].severity, Severity::Critical);
    }

    #[test]
    fn test_check_codeowners_presence_in_root() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("CODEOWNERS"), "* @owner").unwrap();

        let scanner = Scanner::new(temp_dir.path().to_path_buf());
        let config = Config::default();

        let findings = check_codeowners_presence(&scanner, &config);
        assert!(findings.is_empty());
    }

    #[test]
    fn test_check_codeowners_presence_in_github_dir() {
        let temp_dir = TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join(".github")).unwrap();
        fs::write(temp_dir.path().join(".github/CODEOWNERS"), "* @owner").unwrap();

        let scanner = Scanner::new(temp_dir.path().to_path_buf());
        let config = Config::default();

        let findings = check_codeowners_presence(&scanner, &config);
        assert!(findings.is_empty());
    }

    #[test]
    fn test_check_codeowners_presence_in_docs_dir() {
        let temp_dir = TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join("docs")).unwrap();
        fs::write(temp_dir.path().join("docs/CODEOWNERS"), "* @owner").unwrap();

        let scanner = Scanner::new(temp_dir.path().to_path_buf());
        let config = Config::default();

        let findings = check_codeowners_presence(&scanner, &config);
        assert!(findings.is_empty());
    }

    // ===== CODEOWNERS Syntax Tests (CODE002) =====

    #[test]
    fn test_validate_codeowners_syntax_valid() {
        let content = r#"
# This is a comment
* @global-owner

/src/ @src-team
/docs/*.md @docs-team
*.js @frontend-team
/api/ @org/api-team
/config/ user@example.com
"#;

        let errors = validate_codeowners_syntax(content);
        assert!(
            errors.is_empty(),
            "Expected no errors but got: {:?}",
            errors
        );
    }

    #[test]
    fn test_validate_codeowners_syntax_no_owner() {
        let content = "/src/";

        let errors = validate_codeowners_syntax(content);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].1.contains("No owners specified"));
    }

    #[test]
    fn test_validate_codeowners_syntax_invalid_owner() {
        let content = "* invalid-owner";

        let errors = validate_codeowners_syntax(content);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].1.contains("Invalid owner format"));
    }

    #[test]
    fn test_check_codeowners_syntax_with_errors() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("CODEOWNERS"), "/src/\n* bad-owner").unwrap();

        let scanner = Scanner::new(temp_dir.path().to_path_buf());

        let findings = check_codeowners_syntax(&scanner);
        assert_eq!(findings.len(), 2);
        assert!(findings.iter().all(|f| f.rule_id == "CODE002"));
    }

    // ===== Extract Owners Tests =====

    #[test]
    fn test_extract_owners() {
        let content = r#"
# Comment
* @global-owner
/src/ @team1 @team2
/docs/ @org/docs-team
"#;

        let owners = extract_owners(content);
        assert_eq!(owners.len(), 4);
        assert!(owners.iter().any(|(o, _)| o == "@global-owner"));
        assert!(owners.iter().any(|(o, _)| o == "@team1"));
        assert!(owners.iter().any(|(o, _)| o == "@team2"));
        assert!(owners.iter().any(|(o, _)| o == "@org/docs-team"));
    }

    #[test]
    fn test_extract_owners_with_line_numbers() {
        let content = "* @owner1\n/src/ @owner2";

        let owners = extract_owners(content);
        assert_eq!(owners.len(), 2);
        assert_eq!(owners[0], ("@owner1".to_string(), 1));
        assert_eq!(owners[1], ("@owner2".to_string(), 2));
    }

    // ===== Full Integration Test =====

    #[tokio::test]
    async fn test_codeowners_rules_run() {
        let temp_dir = TempDir::new().unwrap();
        let scanner = Scanner::new(temp_dir.path().to_path_buf());
        let config = Config::default();

        let rules = CodeownersRules;
        let findings = rules.run(&scanner, &config).await.unwrap();

        // Should at least have CODE001 (missing CODEOWNERS)
        assert!(findings.iter().any(|f| f.rule_id == "CODE001"));
    }

    #[tokio::test]
    async fn test_codeowners_rules_with_valid_file() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("CODEOWNERS"), "* @valid-owner").unwrap();

        let scanner = Scanner::new(temp_dir.path().to_path_buf());
        let config = Config::default();

        let rules = CodeownersRules;
        let findings = rules.run(&scanner, &config).await.unwrap();

        // Should not have CODE001 (CODEOWNERS exists)
        assert!(!findings.iter().any(|f| f.rule_id == "CODE001"));
        // Should not have CODE002 (valid syntax)
        assert!(!findings.iter().any(|f| f.rule_id == "CODE002"));
    }

    #[test]
    fn test_find_codeowners_priority() {
        let temp_dir = TempDir::new().unwrap();

        // Create both root and .github CODEOWNERS
        fs::write(temp_dir.path().join("CODEOWNERS"), "root content").unwrap();
        fs::create_dir_all(temp_dir.path().join(".github")).unwrap();
        fs::write(temp_dir.path().join(".github/CODEOWNERS"), "github content").unwrap();

        let scanner = Scanner::new(temp_dir.path().to_path_buf());

        // Root should be preferred
        let (path, content) = find_codeowners(&scanner).unwrap();
        assert_eq!(path, "CODEOWNERS");
        assert_eq!(content, "root content");
    }
}