kingfisher-bin 2.8.0

MongoDB's blazingly fast and accurate secret scanning and validation tool
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
use std::{
    collections::HashMap,
    io::Read,
    net::SocketAddr,
    net::TcpListener as StdTcpListener,
    path::{Path, PathBuf},
    sync::{Arc, OnceLock},
};

use anyhow::{Context, Result, anyhow};
use axum::{
    Router,
    body::Body,
    extract::State,
    http::{HeaderValue, StatusCode, Uri, header},
    response::Response,
    routing::get,
};
use bytes::Bytes;
use flate2::read::GzDecoder;
use tokio::net::TcpListener;
use tracing::{info, warn};

pub const DEFAULT_PORT: u16 = 7890;

// Embedded viewer assets (gzip-compressed at build time, decompressed lazily).
const VIEWER_BUNDLE_MAGIC: &[u8] = b"KFVIEW\x01";
static COMPRESSED_VIEWER_ASSETS: &[u8] =
    include_bytes!(concat!(env!("OUT_DIR"), "/viewer-assets.gz"));
static VIEWER_ASSETS: OnceLock<HashMap<String, Bytes>> = OnceLock::new();

/// Lazily decompress the embedded viewer asset bundle into a path → contents map.
fn viewer_assets() -> &'static HashMap<String, Bytes> {
    VIEWER_ASSETS.get_or_init(|| {
        decompress_viewer_bundle(COMPRESSED_VIEWER_ASSETS).unwrap_or_else(|err| {
            warn!(%err, "failed to decompress embedded viewer asset bundle");
            HashMap::new()
        })
    })
}

fn decompress_viewer_bundle(data: &[u8]) -> Result<HashMap<String, Bytes>> {
    let mut decoded = Vec::new();
    GzDecoder::new(data)
        .read_to_end(&mut decoded)
        .context("failed to decompress embedded viewer asset bundle")?;

    let mut cursor = BundleCursor::new(&decoded);
    if cursor.take(VIEWER_BUNDLE_MAGIC.len())? != VIEWER_BUNDLE_MAGIC {
        anyhow::bail!("embedded viewer asset bundle has an invalid header");
    }

    let mut assets = HashMap::new();
    loop {
        let name_len = usize::try_from(cursor.u32()?)
            .map_err(|_| anyhow!("embedded viewer asset path length exceeds platform limits"))?;
        if name_len == 0 {
            break;
        }
        let contents_len = usize::try_from(cursor.u64()?).map_err(|_| {
            anyhow!("embedded viewer asset contents length exceeds platform limits")
        })?;
        let name = std::str::from_utf8(cursor.take(name_len)?)
            .context("embedded viewer asset bundle contains a non-UTF-8 path")?;
        assets.insert(name.to_owned(), Bytes::copy_from_slice(cursor.take(contents_len)?));
    }
    if !cursor.remaining.is_empty() {
        anyhow::bail!("embedded viewer asset bundle has trailing data");
    }
    Ok(assets)
}

struct BundleCursor<'a> {
    remaining: &'a [u8],
}

impl<'a> BundleCursor<'a> {
    fn new(contents: &'a [u8]) -> Self {
        Self { remaining: contents }
    }

    fn take(&mut self, length: usize) -> Result<&'a [u8]> {
        if self.remaining.len() < length {
            anyhow::bail!("embedded viewer asset bundle is truncated");
        }
        let (result, remaining) = self.remaining.split_at(length);
        self.remaining = remaining;
        Ok(result)
    }

    fn u32(&mut self) -> Result<u32> {
        let bytes: [u8; 4] = self.take(4)?.try_into().expect("slice length is checked");
        Ok(u32::from_le_bytes(bytes))
    }

    fn u64(&mut self) -> Result<u64> {
        let bytes: [u8; 8] = self.take(8)?.try_into().expect("slice length is checked");
        Ok(u64::from_le_bytes(bytes))
    }
}

/// Default bind address for the report viewer (localhost only for security).
pub const DEFAULT_ADDRESS: &str = "127.0.0.1";

/// View a Kingfisher blast-radius report locally.
#[derive(clap::Args, Debug)]
pub struct ViewArgs {
    /// Paths to JSON/JSONL/SARIF reports or directories containing them.
    /// Multiple files are merged and deduplicated by fingerprint.
    /// Directories are scanned (non-recursively) for .json/.jsonl/.sarif files.
    #[arg(value_name = "REPORT", value_hint = clap::ValueHint::AnyPath)]
    pub reports: Vec<PathBuf>,

    /// Local port for the embedded viewer (default 7890)
    #[arg(long, default_value_t = DEFAULT_PORT)]
    pub port: u16,

    /// Bind address for the report viewer (default 127.0.0.1). Use 0.0.0.0 to allow access from Docker or other hosts.
    #[arg(long, default_value = DEFAULT_ADDRESS, value_name = "ADDRESS")]
    pub address: String,

    #[arg(skip)]
    pub open_browser: bool,

    #[arg(skip)]
    pub report_bytes: Option<Vec<u8>>,
}

#[derive(Clone)]
struct AppState {
    report: Option<Vec<u8>>,
}

fn addr_in_use_error(port: u16, flag_name: &str) -> anyhow::Error {
    anyhow!(
        "Port {} is already in use. Re-run with {} <PORT> to choose a different port.",
        port,
        flag_name
    )
}

pub fn ensure_port_available(port: u16, address: &str, flag_name: &str) -> Result<()> {
    let addr: std::net::IpAddr =
        address.parse().context("Invalid bind address for report viewer")?;
    StdTcpListener::bind((addr, port)).map_err(|err| match err.kind() {
        std::io::ErrorKind::AddrInUse => addr_in_use_error(port, flag_name),
        _ => err.into(),
    })?;
    Ok(())
}

/// Resolve report paths: expand directories (non-recursively) into their
/// `.json` / `.jsonl` / `.sarif` children, expand tildes, and filter to valid extensions.
/// Non-matching files inside directories are silently skipped.
async fn resolve_report_paths(raw: &[PathBuf]) -> Result<Vec<PathBuf>> {
    let mut paths = Vec::new();

    for raw_path in raw {
        let expanded = expand_tilde(raw_path)?;
        let meta = tokio::fs::metadata(&expanded)
            .await
            .with_context(|| format!("Cannot access path: {}", expanded.display()))?;

        if meta.is_dir() {
            let mut read_dir = tokio::fs::read_dir(&expanded)
                .await
                .with_context(|| format!("Cannot read directory: {}", expanded.display()))?;
            while let Some(entry) = read_dir.next_entry().await? {
                let child = entry.path();
                if child.is_file() && is_report_extension(&child) {
                    paths.push(child);
                }
            }
        } else if meta.is_file() {
            if !is_report_extension(&expanded) {
                warn!(path = %expanded.display(), "Skipping file with unsupported extension");
                continue;
            }
            paths.push(expanded);
        }
    }

    Ok(paths)
}

fn is_report_extension(path: &Path) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| {
            let lower = ext.to_ascii_lowercase();
            lower == "json" || lower == "jsonl" || lower == "sarif"
        })
        .unwrap_or(false)
}

/// Load multiple report files and emit genuine JSONL so the viewer's
/// multi-document parser can split on newline boundaries. Kingfisher's
/// `json_format` writes pretty-printed (multi-line) documents; naive
/// concatenation would produce output that is neither valid JSON nor
/// valid JSONL and the viewer's fallback splitter would shatter nested
/// objects. For each file we try to parse the whole payload as a single
/// JSON value and emit it as one compact line; on failure we assume
/// JSONL input and re-emit each non-blank line compacted.
// nosemgrep: tokio::fs::read below operates on CLI-supplied paths (the
// user explicitly ran `kingfisher view <path>`); path-traversal rules
// designed for HTTP handlers don't apply to a CLI.
async fn load_and_combine_reports(paths: &[PathBuf]) -> Result<Vec<u8>> {
    let mut combined = Vec::new();
    let mut loaded = 0usize;

    for path in paths {
        // nosemgrep: CLI-supplied path — see function-level comment above.
        let bytes = match tokio::fs::read(path).await {
            Ok(b) => b,
            Err(err) => {
                warn!(path = %path.display(), %err, "Failed to read report file, skipping");
                continue;
            }
        };

        let mut push_compact = |value: &serde_json::Value| -> Result<()> {
            if !combined.is_empty() && !combined.ends_with(b"\n") {
                combined.push(b'\n');
            }
            serde_json::to_writer(&mut combined, value)?;
            combined.push(b'\n');
            Ok(())
        };

        match serde_json::from_slice::<serde_json::Value>(&bytes) {
            Ok(value) => {
                if let Err(err) = push_compact(&value) {
                    warn!(path = %path.display(), %err, "Failed to re-serialize report, skipping");
                    continue;
                }
            }
            Err(_) => {
                let mut any = false;
                for line in bytes.split(|b| *b == b'\n') {
                    let trimmed = match line.iter().position(|b| !b.is_ascii_whitespace()) {
                        Some(i) => &line[i..],
                        None => continue,
                    };
                    match serde_json::from_slice::<serde_json::Value>(trimmed) {
                        Ok(value) => {
                            if push_compact(&value).is_ok() {
                                any = true;
                            }
                        }
                        Err(err) => {
                            warn!(path = %path.display(), %err, "Skipping malformed JSONL line");
                        }
                    }
                }
                if !any {
                    warn!(path = %path.display(), "No parseable JSON in report, skipping");
                    continue;
                }
            }
        }
        loaded += 1;
    }

    if loaded == 0 && !paths.is_empty() {
        return Err(anyhow!("Failed to read any of the {} report file(s)", paths.len()));
    }

    if loaded > 0 {
        info!(loaded, total = paths.len(), "Loaded report files");
    }

    Ok(combined)
}

/// Run the `kingfisher view` subcommand.
pub async fn run(args: ViewArgs) -> Result<()> {
    let report = if let Some(report_bytes) = args.report_bytes.as_ref() {
        Some(report_bytes.clone())
    } else if !args.reports.is_empty() {
        let paths = resolve_report_paths(&args.reports).await?;
        if paths.is_empty() {
            warn!("No JSON/JSONL/SARIF report files found in the provided paths");
            None
        } else {
            let combined = load_and_combine_reports(&paths).await?;
            if combined.is_empty() { None } else { Some(combined) }
        }
    } else {
        None
    };

    let addr: std::net::IpAddr =
        args.address.parse().context("Invalid bind address for report viewer")?;
    let listener = TcpListener::bind((addr, args.port)).await.map_err(|err| match err.kind() {
        std::io::ErrorKind::AddrInUse => addr_in_use_error(args.port, "--port"),
        _ => err.into(),
    })?;

    let address: SocketAddr =
        listener.local_addr().context("Failed to read local listener address")?;

    let url = format!("http://{}:{}", address.ip(), address.port());

    info!(%address, "Starting blast-radius viewer");
    eprintln!("Serving blast-radius viewer at {} (Ctrl+C to stop)", url);

    let open_browser = args.open_browser || !args.reports.is_empty() || args.report_bytes.is_some();
    if open_browser {
        let url = url.clone();
        tokio::task::spawn_blocking(move || {
            if let Err(err) = webbrowser::open(&url) {
                warn!(%err, "Failed to open browser for blast-radius viewer");
            }
        });
    }

    let state = Arc::new(AppState { report });

    let app = Router::new()
        .route("/", get(serve_index))
        .route("/report", get(serve_report))
        .route("/favicon.ico", get(serve_favicon))
        .fallback(get(serve_asset))
        .with_state(state);

    axum::serve(listener, app).await?;
    Ok(())
}

async fn serve_index() -> Response {
    serve_asset_at("index.html").unwrap_or_else(not_found)
}

async fn serve_favicon() -> Response {
    Response::builder()
        .status(StatusCode::NO_CONTENT)
        .body(Body::empty())
        .map(apply_security_headers)
        .unwrap_or_else(|_| internal_error())
}

async fn serve_asset(uri: Uri) -> Response {
    let path = uri.path().trim_start_matches('/');
    if path.is_empty() {
        return serve_index().await;
    }
    if !is_safe_path(path) {
        return not_found();
    }

    serve_asset_at(path).unwrap_or_else(not_found)
}

async fn serve_report(State(state): State<Arc<AppState>>) -> Response {
    if let Some(report) = &state.report {
        return Response::builder()
            .status(StatusCode::OK)
            .header(header::CONTENT_TYPE, content_type_for("report.json"))
            .body(Body::from(report.clone()))
            .map(apply_security_headers)
            .unwrap_or_else(|_| internal_error());
    }

    not_found()
}

fn serve_asset_at(path: &str) -> Option<Response> {
    let contents = viewer_assets().get(path)?;
    let body = Body::from(contents.clone());
    let content_type = content_type_for(path);

    Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, content_type)
        .body(body)
        .map(apply_security_headers)
        .ok()
}

fn content_type_for(path: &str) -> HeaderValue {
    if let Some(ext) = path.rsplit('.').next() {
        let mime = match ext {
            "html" => "text/html; charset=utf-8",
            "js" => "application/javascript; charset=utf-8",
            "css" => "text/css; charset=utf-8",
            "json" | "jsonl" => "application/json; charset=utf-8",
            "png" => "image/png",
            _ => "application/octet-stream",
        };
        return HeaderValue::from_static(mime);
    }

    HeaderValue::from_static("application/octet-stream")
}

fn is_safe_path(path: &str) -> bool {
    let candidate = std::path::Path::new(path);
    candidate.components().all(|comp| matches!(comp, std::path::Component::Normal(_)))
}

fn not_found() -> Response {
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .body(Body::from("Not found"))
        .map(apply_security_headers)
        .unwrap_or_else(|_| internal_error())
}

fn internal_error() -> Response {
    Response::builder()
        .status(StatusCode::INTERNAL_SERVER_ERROR)
        .body(Body::from("Internal server error"))
        .map(apply_security_headers)
        .unwrap()
}

fn apply_security_headers(response: Response) -> Response {
    let mut response = response;
    let headers = response.headers_mut();
    headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
    headers.insert(header::PRAGMA, HeaderValue::from_static("no-cache"));
    headers.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));
    headers.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
    headers.insert(
        header::CONTENT_SECURITY_POLICY,
        HeaderValue::from_static(
            "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:; object-src 'none'",
        ),
    );
    response
}

fn expand_tilde(path: &Path) -> Result<PathBuf> {
    let path_str = path.to_string_lossy();
    if path_str == "~" || path_str.starts_with("~/") {
        let home = std::env::var("HOME")
            .context("Could not resolve home directory for tilde-expanded path")?;
        let trimmed = path_str.trim_start_matches("~/");
        return Ok(PathBuf::from(home).join(trimmed));
    }

    Ok(path.to_path_buf())
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use flate2::{Compression, write::GzEncoder};

    use super::{
        VIEWER_BUNDLE_MAGIC, decompress_viewer_bundle, ensure_port_available, is_report_extension,
    };

    #[test]
    fn decompress_viewer_bundle_rejects_trailing_data() {
        let mut bundle = VIEWER_BUNDLE_MAGIC.to_vec();
        bundle.extend_from_slice(&0_u32.to_le_bytes());
        bundle.push(0);

        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(&bundle).unwrap();
        let compressed_bundle = encoder.finish().unwrap();

        let err = decompress_viewer_bundle(&compressed_bundle).unwrap_err();
        assert!(err.to_string().contains("trailing data"));
    }

    #[test]
    fn ensure_port_available_uses_passed_flag_name_in_error() {
        let listener = match std::net::TcpListener::bind(("127.0.0.1", 0)) {
            Ok(listener) => listener,
            Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => return,
            Err(err) => panic!("failed to bind local test port: {err}"),
        };
        let port = listener.local_addr().unwrap().port();

        let err = ensure_port_available(port, "127.0.0.1", "--view-report-port").unwrap_err();
        assert!(err.to_string().contains("--view-report-port <PORT>"));
    }

    #[test]
    fn report_extension_accepts_json_jsonl_and_sarif() {
        assert!(is_report_extension(std::path::Path::new("report.json")));
        assert!(is_report_extension(std::path::Path::new("report.jsonl")));
        assert!(is_report_extension(std::path::Path::new("report.sarif")));
        assert!(is_report_extension(std::path::Path::new("report.SARIF")));
        assert!(!is_report_extension(std::path::Path::new("report.txt")));
    }
}