flintbase 0.3.1

Google / Firebase API key analyzer and APK secret scanner — tests keys against 20+ endpoints and extracts hardcoded credentials from Android apps
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
mod apk;
mod config;
mod firebase;
mod google;
mod parser;
mod preflight;
mod report;
mod scanner;

use std::io::{self, Write};
use std::path::PathBuf;
use std::time::Duration;

use clap::{Parser, Subcommand};
use colored::Colorize;

use config::FirebaseConfig;

/// flintBase — Google / Firebase API key analyzer and APK security toolkit
///
/// Tests API keys against 20+ endpoints and performs APK download,
/// decompilation, and secret scanning.
#[derive(Parser, Debug)]
#[command(name = "flintbase", version, about, long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Test a Google/Firebase API key against multiple services
    #[command(after_help = "\
EXAMPLES:
  flintbase key AIzaSyXXXXXXXXXXXXXXXXXXXX
  flintbase key AIzaSyXXXX --project-id my-project --app-id 1:123:android:abc
  flintbase key --config my_app
  flintbase key --list-configs")]
    Key {
        /// The API key to test (AIzaSy...)
        key: Option<String>,

        /// Firebase project ID
        #[arg(short = 'p', long = "project-id")]
        project_id: Option<String>,

        /// Firebase app ID (1:xxx:android:xxx)
        #[arg(short = 'a', long = "app-id")]
        app_id: Option<String>,

        /// GCM sender ID / project number
        #[arg(short = 's', long = "sender-id")]
        sender_id: Option<String>,

        /// Use pre-extracted app configuration
        #[arg(short = 'c', long = "config")]
        config: Option<String>,

        /// List available pre-extracted configs
        #[arg(long = "list-configs")]
        list_configs: bool,
    },

    /// Download, decompile, and scan an Android APK for secrets
    #[command(after_help = "\
EXAMPLES:
  flintbase apk https://play.google.com/store/apps/details?id=com.example.app
  flintbase apk com.example.app
  flintbase apk https://play.google.com/store/apps/developer?id=Developer+Name
  flintbase apk com.example.app --output-dir ./my_analysis --format json
  flintbase apk com.example.app -v  # verbose: show apkeep/jadx output")]
    Apk {
        /// Play Store URL or package name (e.g. com.example.app)
        input: String,

        /// Output directory for APK, decompiled sources, and reports
        #[arg(short = 'o', long = "output-dir", default_value = "flintbase_output")]
        output_dir: PathBuf,

        /// Report format: human, json, jsonl, sarif
        #[arg(short = 'f', long = "format", default_value = "human")]
        format: String,

        /// Show detailed output from external tools (apkeep, jadx, noseyparker)
        #[arg(short = 'v', long = "verbose")]
        verbose: bool,
    },

    /// Download, decompile, extract credentials, and auto-test all discovered API keys
    #[command(after_help = "\
The scan command combines the APK pipeline with automatic key testing.
It downloads and decompiles the APK, scans for secrets with NoseyParker,
parses the results to extract Firebase/Google credentials, then runs
the full key analysis against every discovered API key.

EXAMPLES:
  flintbase scan https://play.google.com/store/apps/details?id=com.example.app
  flintbase scan com.example.app
  flintbase scan com.example.app --output-dir ./analysis
  flintbase scan com.example.app -v  # verbose: show all tool output
  flintbase scan com.example.app --save  # save discovered configs for later use")]
    Scan {
        /// Play Store URL or package name (e.g. com.example.app)
        input: String,

        /// Output directory for APK, decompiled sources, and reports
        #[arg(short = 'o', long = "output-dir", default_value = "flintbase_output")]
        output_dir: PathBuf,

        /// Show detailed output from external tools (apkeep, jadx, noseyparker)
        #[arg(short = 'v', long = "verbose")]
        verbose: bool,

        /// Save discovered configs to ~/.config/flintbase/configs.json for later re-testing
        #[arg(long = "save")]
        save: bool,
    },

    /// Check and install required external tool dependencies
    #[command(after_help = "\
Required tools for the APK pipeline:
  apkeep       - APK downloading (EFF, Rust-based)
  jadx         - APK decompilation to Java source
  java         - Required by jadx
  noseyparker  - Secret scanning

EXAMPLES:
  flintbase setup              # Check status of all dependencies
  flintbase setup --install    # Auto-detect platform and install missing tools")]
    Setup {
        /// Automatically install missing tools (platform-aware)
        #[arg(long = "install", short = 'i')]
        install: bool,
    },
}

fn main() {
    let cli = Cli::parse();

    match cli.command {
        Commands::Key {
            key,
            project_id,
            app_id,
            sender_id,
            config,
            list_configs,
        } => run_key_command(key, project_id, app_id, sender_id, config, list_configs),

        Commands::Apk {
            input,
            output_dir,
            format,
            verbose,
        } => run_apk_command(&input, &output_dir, &format, verbose),

        Commands::Scan {
            input,
            output_dir,
            verbose,
            save,
        } => run_scan_command(&input, &output_dir, verbose, save),

        Commands::Setup { install } => {
            if install {
                preflight::run_auto_install();
            } else {
                preflight::run_setup_check();
            }
        }
    }
}

// ═════════════════════════════════════════════════════════════════════════════
// Key subcommand
// ═════════════════════════════════════════════════════════════════════════════

fn run_key_command(
    key: Option<String>,
    project_id: Option<String>,
    app_id: Option<String>,
    sender_id: Option<String>,
    config_name: Option<String>,
    list_configs: bool,
) {
    if list_configs {
        report::print_saved_configs();
        return;
    }

    let (fb_config, app_name) = if let Some(ref cname) = config_name {
        let store = config::load_saved_configs();
        let saved = match store.configs.get(cname.as_str()) {
            Some(c) => c.clone(),
            None => {
                eprintln!(
                    "Error: unknown config '{}'. Use --list-configs to see available options.",
                    cname
                );
                if !store.configs.is_empty() {
                    eprintln!("Available configs: {}", store.configs.keys().cloned().collect::<Vec<_>>().join(", "));
                } else {
                    eprintln!("No saved configs found. Run `flintbase scan --save` to save configs from an APK scan.");
                }
                std::process::exit(1);
            }
        };

        println!(
            "\n{} {}",
            "Using saved configuration:".green().bold(),
            saved.name.bold()
        );

        let fb = saved.to_firebase_config();
        (fb, Some(saved.name.clone()))
    } else {
        let api_key = if let Some(ref k) = key {
            k.trim().to_string()
        } else {
            print!("Enter Google/Firebase API key → ");
            io::stdout().flush().unwrap();
            let mut input = String::new();
            io::stdin().read_line(&mut input).unwrap();
            input.trim().to_string()
        };

        if !api_key.starts_with("AIza") || api_key.len() < 30 {
            eprintln!("Error: Invalid key format (should start with AIzaSy... and be >= 30 chars)");
            std::process::exit(1);
        }

        let config = FirebaseConfig {
            api_key,
            app_id,
            project_id,
            project_number: None,
            gcm_sender_id: sender_id,
            storage_bucket: None,
            database_url: None,
        };
        (config, None)
    };

    run_key_tests(&fb_config, app_name.as_deref());
}

/// Run the full key analysis for a single FirebaseConfig (shared by `key` and `scan`).
fn run_key_tests(fb_config: &FirebaseConfig, app_name: Option<&str>) {
    report::print_config_info(fb_config, app_name);

    let client = reqwest::blocking::Client::builder()
        .timeout(Duration::from_secs(15))
        .build()
        .expect("Failed to build HTTP client");

    let (firebase_results, project_info) =
        firebase::run_firebase_deep_tests(&client, fb_config);
    let google_results = google::run_google_api_tests(&client, &fb_config.api_key);

    report::print_report(fb_config, &firebase_results, &google_results, &project_info);
}

// ═════════════════════════════════════════════════════════════════════════════
// APK subcommand
// ═════════════════════════════════════════════════════════════════════════════

fn run_apk_command(input: &str, output_dir: &PathBuf, format: &str, verbose: bool) {
    let valid_formats = ["human", "json", "jsonl", "sarif"];
    if !valid_formats.contains(&format) {
        eprintln!(
            "Error: Invalid format '{}'. Must be one of: {}",
            format,
            valid_formats.join(", ")
        );
        std::process::exit(1);
    }

    if let Err(e) = apk::run_apk_command(input, output_dir, format, verbose) {
        eprintln!("\n\x1b[1;31mError:\x1b[0m {}", e);
        std::process::exit(1);
    }
}

// ═════════════════════════════════════════════════════════════════════════════
// Scan subcommand  (APK pipeline → parse credentials → run key tests)
// ═════════════════════════════════════════════════════════════════════════════

fn run_scan_command(input: &str, output_dir: &PathBuf, verbose: bool, save: bool) {
    // Pre-flight
    if let Err(e) = preflight::ensure_apk_tools_available() {
        eprintln!("\n\x1b[1;31mError:\x1b[0m {}", e);
        std::process::exit(1);
    }

    println!(
        "\n{}",
        "flintBase Full Scan Pipeline".bright_cyan().bold()
    );
    println!("{}", "".repeat(60));

    // Step 1: Resolve packages
    println!("\n{}", "Phase 1: Resolve packages".bold());
    let packages = match apk::download::parse_store_input(input) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("\n\x1b[1;31mError:\x1b[0m {}", e);
            std::process::exit(1);
        }
    };

    if packages.is_empty() {
        eprintln!("\nError: No packages found to process.");
        std::process::exit(1);
    }

    for package in &packages {
        println!(
            "\n{}",
            "".repeat(60)
        );
        println!(
            "{} {}",
            "Scanning package:".bright_magenta().bold(),
            package.bold()
        );
        println!("{}", "".repeat(60));

        let ws = apk::ApkWorkspace::new(output_dir, package);
        if let Err(e) = ws.create_dirs() {
            eprintln!("  Failed to create workspace: {}", e);
            continue;
        }

        // Step 2: Download APK
        println!("\n{}", "Phase 2: Download APK".bold());
        let apk_path = match apk::download::download_apk(package, &ws.apk_dir, verbose) {
            Ok(p) => {
                println!("  {} APK saved: {}", "".green(), p.display());
                p
            }
            Err(e) => {
                eprintln!("  {} Download failed: {}", "".red(), e);
                continue;
            }
        };

        // Step 3: Decompile
        println!("\n{}", "Phase 3: Decompile APK".bold());
        let decompiled_dir = match apk::decompile::decompile_apk(&apk_path, &ws.decompiled_dir, verbose) {
            Ok(d) => d,
            Err(e) => {
                eprintln!("  {} Decompilation failed: {}", "".red(), e);
                continue;
            }
        };

        // Step 4: NoseyParker scan
        println!("\n{}", "Phase 4: Secret scan (NoseyParker)".bold());
        if let Err(e) = scanner::scan_directory(&decompiled_dir, &ws.datastore_dir) {
            eprintln!("  {} Scan failed: {}", "".red(), e);
            continue;
        }

        // Also write a human-readable report file
        let report_file = ws.report_dir.join("secrets.txt");
        let _ = scanner::generate_report(&ws.datastore_dir, "human", Some(&report_file));

        // Step 5: Parse credentials from NoseyParker JSON + config files
        println!("\n{}", "Phase 5: Extract credentials".bold());

        let mut all_creds = parser::ExtractedCredentials::default();

        // 5a: Parse NoseyParker JSON results
        match scanner::generate_json_report(&ws.datastore_dir) {
            Ok(json_str) => {
                match parser::parse_noseyparker_json(&json_str) {
                    Ok(np_creds) => {
                        println!(
                            "  {} Extracted {} credential(s) from NoseyParker findings",
                            "".cyan(),
                            np_creds.credentials.len()
                        );
                        all_creds.credentials.extend(np_creds.credentials);
                    }
                    Err(e) => {
                        eprintln!(
                            "  {} Failed to parse NoseyParker JSON: {}",
                            "".yellow(),
                            e
                        );
                    }
                }
            }
            Err(e) => {
                eprintln!(
                    "  {} Failed to generate NoseyParker JSON: {}",
                    "".yellow(),
                    e
                );
            }
        }

        // 5b: Scan decompiled files for Firebase config artifacts
        let config_creds = parser::scan_decompiled_configs(&decompiled_dir);
        println!(
            "  {} Extracted {} credential(s) from config files (google-services.json, strings.xml, etc.)",
            "".cyan(),
            config_creds.credentials.len()
        );
        all_creds.credentials.extend(config_creds.credentials);

        // Display extracted credentials
        parser::print_extracted_summary(&all_creds);

        // Step 6: Build FirebaseConfigs and run key tests
        let configs = all_creds.build_firebase_configs();

        if configs.is_empty() {
            println!(
                "\n  {} No Google API keys found — skipping key analysis.",
                "".yellow()
            );
            println!("  Full NoseyParker report saved to: {}", report_file.display());
            continue;
        }

        parser::print_configs_to_test(&configs);

        println!(
            "\n{}",
            "Phase 6: API Key Analysis".bold()
        );
        println!("{}", "".repeat(60));

        for (i, fb_config) in configs.iter().enumerate() {
            println!(
                "\n{} Testing key {}/{}: {}...{}",
                "".bright_cyan().bold(),
                i + 1,
                configs.len(),
                &fb_config.api_key[..12],
                &fb_config.api_key[fb_config.api_key.len().saturating_sub(4)..],
            );
            run_key_tests(fb_config, None);
        }

        // Save configs if requested
        if save && !configs.is_empty() {
            match config::save_firebase_configs(package, &configs) {
                Ok(n) => {
                    println!(
                        "\n  {} Saved {} config(s) to {}",
                        "".green(),
                        n,
                        config::config_file_path().display()
                    );
                    println!(
                        "  {} Re-test later with: {}",
                        "".cyan(),
                        format!("flintbase key --config {}", package).bold()
                    );
                    println!(
                        "  {} Edit the file to tweak values before re-testing.",
                        "".cyan()
                    );
                }
                Err(e) => {
                    eprintln!(
                        "\n  {} Failed to save configs: {}",
                        "".yellow(),
                        e
                    );
                }
            }
        }

        // Summary
        println!("\n{}", "".repeat(60));
        println!("{}", "Scan Complete".bright_cyan().bold());
        println!("  Workspace:    {}", ws.base_dir.display());
        println!("  APK:          {}", ws.apk_dir.display());
        println!("  Decompiled:   {}", ws.decompiled_dir.display());
        println!("  NP Report:    {}", report_file.display());
        println!("  Keys tested:  {}", configs.len());
        if save && !configs.is_empty() {
            println!(
                "  Saved to:     {}",
                config::config_file_path().display()
            );
        }
    }
}