feluda 1.12.0

A CLI tool to check dependency licenses.
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
use crate::cli::Cli;
use crate::debug::{log, FeludaError, FeludaResult, LogLevel};
use git2::Cred;
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};

fn ssh_to_https_url(repo_url: &str) -> Option<String> {
    if repo_url.is_empty() || repo_url.len() < "git@github.com:a/b".len() {
        return None;
    }
    if !repo_url.starts_with("git@github.com:") {
        return None;
    }
    let repo_path = &repo_url["git@github.com:".len()..];
    if !is_valid_github_repo_path(repo_path) {
        return None;
    }
    Some(format!("https://github.com/{repo_path}"))
}

fn is_valid_github_repo_path(repo_path: &str) -> bool {
    if repo_path.is_empty() {
        return false;
    }
    let parts: Vec<&str> = repo_path.split('/').collect();
    if parts.len() != 2 {
        return false;
    }

    let (user_or_org, repo_name) = (parts[0], parts[1]);
    if user_or_org.is_empty() || repo_name.is_empty() {
        return false;
    }
    if !is_valid_github_username(user_or_org) {
        return false;
    }
    let repo_name_clean = repo_name.strip_suffix(".git").unwrap_or(repo_name);
    if !is_valid_github_repo_name(repo_name_clean) {
        return false;
    }

    true
}

fn is_valid_github_username(username: &str) -> bool {
    if username.is_empty() || username.len() > 39 {
        return false;
    }
    if username.starts_with('-') || username.ends_with('-') {
        return false;
    }
    username
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-')
}

fn is_valid_github_repo_name(repo_name: &str) -> bool {
    if repo_name.is_empty() || repo_name.len() > 100 {
        return false;
    }

    if repo_name == "." || repo_name == ".." {
        return false;
    }

    repo_name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}

fn validate_ssh_key(key_path: &Path) -> Result<(), git2::Error> {
    if !key_path.exists() {
        log(
            LogLevel::Error,
            &format!("SSH key file not found: {}", key_path.display()),
        );
        return Err(git2::Error::from_str("SSH key file not found"));
    }
    if key_path
        .extension()
        .map(|ext| ext == "pub")
        .unwrap_or(false)
    {
        log(
            LogLevel::Error,
            &format!(
                "Invalid SSH key: {} is a public key (.pub)",
                key_path.display()
            ),
        );
        return Err(git2::Error::from_str(
            "Public key provided instead of private key",
        ));
    }
    Ok(())
}

pub fn clone_repository(args: &Cli, dest_path: &Path) -> FeludaResult<()> {
    let token = &args.token;
    let ssh_key = &args.ssh_key;
    let ssh_passphrase = &args.ssh_passphrase;
    let repo_url = &args.repo.as_deref().unwrap();

    log(
        LogLevel::Info,
        &format!(
            "Initializing clone of {} to {}",
            repo_url,
            dest_path.display()
        ),
    );

    let auth_attempts = AtomicUsize::new(0);
    const MAX_AUTH_ATTEMPTS: usize = 5;

    let mut callbacks = git2::RemoteCallbacks::new();
    callbacks.credentials(|url, username_from_url, allowed_types| {
        let attempts = auth_attempts.fetch_add(1, Ordering::SeqCst);
        if attempts >= MAX_AUTH_ATTEMPTS {
            log(LogLevel::Error, "Max authentication attempts reached");
            return Err(git2::Error::from_str("Too many authentication attempts"));
        }

        log(
            LogLevel::Info,
            &format!("Credentials callback for URL: {url}, username: {username_from_url:?}"),
        );
        if allowed_types.is_ssh_key() {
            log(LogLevel::Info, "Attempting SSH authentication");

            if let Some(key_path) = ssh_key {
                let key_path = Path::new(&key_path);
                validate_ssh_key(key_path)?;
                log(
                    LogLevel::Info,
                    &format!("Using custom SSH key at: {}", key_path.display()),
                );
                Cred::ssh_key(
                    username_from_url.unwrap_or("git"),
                    None,
                    key_path,
                    ssh_passphrase.as_deref(),
                )
            } else {
                log(LogLevel::Info, "Trying SSH agent");
                match Cred::ssh_key_from_agent(username_from_url.unwrap_or("git")) {
                    Ok(cred) => {
                        log(LogLevel::Info, "Using SSH agent credentials");
                        Ok(cred)
                    }
                    Err(e) => {
                        log(
                            LogLevel::Warn,
                            &format!("SSH agent failed: {e}, trying default key"),
                        );
                        Err(e)
                    }
                }
            }
        } else if allowed_types.is_user_pass_plaintext() && token.is_some() {
            log(LogLevel::Info, "Using HTTPS token authentication");
            Cred::userpass_plaintext("x-access-token", token.as_deref().unwrap())
        } else {
            log(LogLevel::Info, "Using default credentials for HTTPS");
            Cred::default()
        }
    });

    let mut fetch_options = git2::FetchOptions::new();
    fetch_options.remote_callbacks(callbacks);
    let mut builder = git2::build::RepoBuilder::new();
    builder.fetch_options(fetch_options);

    log(
        LogLevel::Info,
        &format!("Cloning {} into {}", repo_url, dest_path.display()),
    );
    match builder.clone(repo_url, dest_path) {
        Ok(_) => {
            log(LogLevel::Info, "Clone successful");
            Ok(())
        }
        Err(e) => {
            if repo_url.starts_with("git@") {
                if let Some(https_url) = ssh_to_https_url(repo_url) {
                    log(
                        LogLevel::Warn,
                        &format!("SSH clone failed: {e}, trying HTTPS: {https_url}"),
                    );
                    let mut https_callbacks = git2::RemoteCallbacks::new();
                    https_callbacks.credentials(|_url, _username, allowed_types| {
                        if allowed_types.is_user_pass_plaintext() && token.is_some() {
                            log(LogLevel::Info, "Using HTTPS token authentication");
                            Cred::userpass_plaintext("x-access-token", token.as_deref().unwrap())
                        } else {
                            log(LogLevel::Info, "Using default credentials for HTTPS");
                            Cred::default()
                        }
                    });
                    let mut https_fetch_options = git2::FetchOptions::new();
                    https_fetch_options.remote_callbacks(https_callbacks);
                    let mut https_builder = git2::build::RepoBuilder::new();
                    https_builder.fetch_options(https_fetch_options);

                    log(
                        LogLevel::Info,
                        &format!("Cloning {} into {}", https_url, dest_path.display()),
                    );
                    return match https_builder.clone(&https_url, dest_path) {
                        Ok(_) => {
                            log(LogLevel::Info, "HTTPS clone successful");
                            Ok(())
                        }
                        Err(e) => {
                            log(LogLevel::Error, &format!("HTTPS clone failed: {e}"));
                            Err(FeludaError::RepositoryClone(format!(
                                "Failed to clone repository: {e}"
                            )))
                        }
                    };
                }
            }
            log(LogLevel::Error, &format!("Failed to clone repository: {e}"));
            Err(FeludaError::RepositoryClone(format!(
                "Failed to clone repository: {e}"
            )))
        }
    }
}

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

    #[test]
    fn test_ssh_to_https_url_github_ssh() {
        let url = "git@github.com:anistark/feluda.git";
        let result = ssh_to_https_url(url);
        assert_eq!(
            result,
            Some("https://github.com/anistark/feluda.git".to_string())
        );
    }

    #[test]
    fn test_ssh_to_https_url_non_github() {
        let url = "git@gitlab.com:user/repo.git";
        let result = ssh_to_https_url(url);
        assert_eq!(result, None);
    }

    #[test]
    fn test_ssh_to_https_url_non_ssh() {
        let url = "https://github.com/anistark/feluda.git";
        let result = ssh_to_https_url(url);
        assert_eq!(result, None);
    }

    #[test]
    fn test_validate_ssh_key_exists() {
        let temp_dir = TempDir::new().unwrap();
        let key_path = temp_dir.path().join("id_rsa");
        File::create(&key_path).unwrap();

        let result = validate_ssh_key(&key_path);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_ssh_key_not_exists() {
        let temp_dir = TempDir::new().unwrap();
        let key_path = temp_dir.path().join("id_rsa");

        let result = validate_ssh_key(&key_path);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "SSH key file not found");
    }

    #[test]
    fn test_validate_ssh_key_public_key() {
        let temp_dir = TempDir::new().unwrap();
        let key_path = temp_dir.path().join("id_rsa.pub");
        File::create(&key_path).unwrap();

        let result = validate_ssh_key(&key_path);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Public key provided instead of private key"
        );
    }

    #[test]
    fn test_ssh_to_https_url_various_formats() {
        // Test standard GitHub SSH
        assert_eq!(
            ssh_to_https_url("git@github.com:user/repo.git"),
            Some("https://github.com/user/repo.git".to_string())
        );

        // Test without .git extension
        assert_eq!(
            ssh_to_https_url("git@github.com:user/repo"),
            Some("https://github.com/user/repo".to_string())
        );

        // Test with organization
        assert_eq!(
            ssh_to_https_url("git@github.com:organization/project.git"),
            Some("https://github.com/organization/project.git".to_string())
        );

        // Test HTTPS URL
        assert_eq!(ssh_to_https_url("https://github.com/user/repo.git"), None);

        // Test GitLab SSH
        assert_eq!(ssh_to_https_url("git@gitlab.com:user/repo.git"), None);

        // Test other SSH formats that aren't GitHub
        assert_eq!(ssh_to_https_url("git@bitbucket.org:user/repo.git"), None);
        assert_eq!(ssh_to_https_url("git@codeberg.org:user/repo.git"), None);

        // Test malformed SSH URL
        assert_eq!(ssh_to_https_url("invalid-ssh-format"), None);
        assert_eq!(ssh_to_https_url("git@github.com"), None);

        // These now return None with improved validation
        assert_eq!(ssh_to_https_url("git@github.com:"), None);

        // Test empty string
        assert_eq!(ssh_to_https_url(""), None);

        // Test with special characters in repo name
        assert_eq!(
            ssh_to_https_url("git@github.com:user/repo-with-dashes.git"),
            Some("https://github.com/user/repo-with-dashes.git".to_string())
        );

        assert_eq!(
            ssh_to_https_url("git@github.com:user/repo_name.git"),
            Some("https://github.com/user/repo_name.git".to_string())
        );

        // Test case sensitivity
        assert_eq!(ssh_to_https_url("git@GitHub.com:user/repo.git"), None);
        assert_eq!(ssh_to_https_url("git@GITHUB.COM:user/repo.git"), None);
    }

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

        // Test valid private key
        let private_key_path = temp_dir.path().join("id_rsa");
        std::fs::File::create(&private_key_path).unwrap();
        assert!(validate_ssh_key(&private_key_path).is_ok());

        // Test public key rejection
        let public_key_path = temp_dir.path().join("id_rsa.pub");
        std::fs::File::create(&public_key_path).unwrap();
        let result = validate_ssh_key(&public_key_path);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .message()
            .contains("Public key provided"));

        // Test non-existent key
        let missing_key_path = temp_dir.path().join("missing_key");
        let result = validate_ssh_key(&missing_key_path);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .message()
            .contains("SSH key file not found"));

        // Test different private key types
        let ed25519_key_path = temp_dir.path().join("id_ed25519");
        std::fs::File::create(&ed25519_key_path).unwrap();
        assert!(validate_ssh_key(&ed25519_key_path).is_ok());

        let ecdsa_key_path = temp_dir.path().join("id_ecdsa");
        std::fs::File::create(&ecdsa_key_path).unwrap();
        assert!(validate_ssh_key(&ecdsa_key_path).is_ok());

        // Test key with no extension
        let no_ext_key_path = temp_dir.path().join("ssh_key");
        std::fs::File::create(&no_ext_key_path).unwrap();
        assert!(validate_ssh_key(&no_ext_key_path).is_ok());

        // Test various public key extensions
        let pub_variations = [
            "key.pub",
            "id_rsa.pub",
            "id_ed25519.pub",
            "id_ecdsa.pub",
            "custom.pub",
        ];

        for pub_key_name in &pub_variations {
            let pub_key_path = temp_dir.path().join(pub_key_name);
            std::fs::File::create(&pub_key_path).unwrap();
            let result = validate_ssh_key(&pub_key_path);
            assert!(result.is_err());
            assert!(result
                .unwrap_err()
                .message()
                .contains("Public key provided"));
        }
    }

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

        // Create CLI args with invalid repository
        let args = Cli {
            debug: false,
            command: None,
            path: "./".to_string(),
            repo: Some("invalid-repo-url".to_string()),
            token: None,
            ssh_key: None,
            ssh_passphrase: None,
            github_token: None,
            json: false,
            yaml: false,
            verbose: false,
            restrictive: false,
            gui: false,
            language: None,
            ci_format: None,
            output_file: None,
            fail_on_restrictive: false,
            incompatible: false,
            fail_on_incompatible: false,
            project_license: None,
            gist: false,
            osi: None,
            strict: false,
            no_local: false,
        };

        let result = clone_repository(&args, temp_dir.path());
        assert!(result.is_err());
    }

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

        // Create a key file
        let key_path = temp_dir.path().join("test_key");
        std::fs::write(&key_path, "fake key content").unwrap();

        // Test that the file exists and validation passes
        assert!(validate_ssh_key(&key_path).is_ok());

        // Test validation after the file is deleted
        std::fs::remove_file(&key_path).unwrap();
        let result = validate_ssh_key(&key_path);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .message()
            .contains("SSH key file not found"));
    }

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

        let args = Cli {
            debug: true,
            command: None,
            path: "./".to_string(),
            repo: Some("https://github.com/nonexistent/repo.git".to_string()),
            token: None,
            ssh_key: None,
            ssh_passphrase: None,
            github_token: None,
            json: false,
            yaml: false,
            verbose: false,
            restrictive: false,
            gui: false,
            language: None,
            ci_format: None,
            output_file: None,
            fail_on_restrictive: false,
            incompatible: false,
            fail_on_incompatible: false,
            project_license: None,
            gist: false,
            osi: None,
            strict: false,
            no_local: false,
        };

        // Enable debug mode for this test
        crate::debug::set_debug_mode(true);

        let result = clone_repository(&args, temp_dir.path());
        assert!(result.is_err());

        // Reset debug mode
        crate::debug::set_debug_mode(false);
    }

    #[test]
    fn test_ssh_to_https_url_case_sensitivity() {
        // Test that the function handles case correctly
        assert_eq!(ssh_to_https_url("git@GitHub.com:user/repo.git"), None);

        assert_eq!(ssh_to_https_url("git@GITHUB.COM:user/repo.git"), None);

        // Test correct case
        assert_eq!(
            ssh_to_https_url("git@github.com:user/repo.git"),
            Some("https://github.com/user/repo.git".to_string())
        );
    }

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

        let args = Cli {
            debug: false,
            command: None,
            path: "./".to_string(),
            repo: Some("".to_string()),
            token: None,
            ssh_key: None,
            ssh_passphrase: None,
            github_token: None,
            json: false,
            yaml: false,
            verbose: false,
            restrictive: false,
            gui: false,
            language: None,
            ci_format: None,
            output_file: None,
            fail_on_restrictive: false,
            incompatible: false,
            fail_on_incompatible: false,
            project_license: None,
            gist: false,
            osi: None,
            strict: false,
            no_local: false,
        };

        let result = clone_repository(&args, temp_dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_ssh_to_https_url_validation() {
        // Test valid cases
        assert_eq!(
            ssh_to_https_url("git@github.com:microsoft/vscode.git"),
            Some("https://github.com/microsoft/vscode.git".to_string())
        );

        assert_eq!(
            ssh_to_https_url("git@github.com:user-name/repo-name.git"),
            Some("https://github.com/user-name/repo-name.git".to_string())
        );

        assert_eq!(
            ssh_to_https_url("git@github.com:user123/repo_name.config.git"),
            Some("https://github.com/user123/repo_name.config.git".to_string())
        );

        // Test invalid usernames (start/end with hyphen)
        assert_eq!(ssh_to_https_url("git@github.com:-user/repo.git"), None);
        assert_eq!(ssh_to_https_url("git@github.com:user-/repo.git"), None);

        // Test invalid repository names
        assert_eq!(ssh_to_https_url("git@github.com:user/.git"), None);
        assert_eq!(ssh_to_https_url("git@github.com:user/..git"), None);

        // Test too many path components
        assert_eq!(ssh_to_https_url("git@github.com:user/repo/extra"), None);

        // Test very long usernames/repos
        let long_username = "a".repeat(40);
        assert_eq!(
            ssh_to_https_url(&format!("git@github.com:{long_username}/repo.git")),
            None
        );

        let long_repo = "a".repeat(101);
        assert_eq!(
            ssh_to_https_url(&format!("git@github.com:user/{long_repo}.git")),
            None
        );

        // Test empty components
        assert_eq!(ssh_to_https_url("git@github.com:/repo.git"), None);
        assert_eq!(ssh_to_https_url("git@github.com:user/"), None);
    }

    #[test]
    fn test_ssh_to_https_url_special_characters() {
        // Valid special characters in repository names
        assert_eq!(
            ssh_to_https_url("git@github.com:user/my-project.js.git"),
            Some("https://github.com/user/my-project.js.git".to_string())
        );

        assert_eq!(
            ssh_to_https_url("git@github.com:user/config_file.json"),
            Some("https://github.com/user/config_file.json".to_string())
        );

        // Invalid characters in usernames
        assert_eq!(
            ssh_to_https_url("git@github.com:user-name/repo.git"),
            Some("https://github.com/user-name/repo.git".to_string())
        );

        // underscores in usernames should be invalid
        assert_eq!(ssh_to_https_url("git@github.com:user_name/repo.git"), None);

        // Invalid characters
        assert_eq!(ssh_to_https_url("git@github.com:user@name/repo.git"), None);
        assert_eq!(ssh_to_https_url("git@github.com:user/repo@name.git"), None);
        assert_eq!(ssh_to_https_url("git@github.com:user name/repo.git"), None);
    }
}