7.9 KiB · text History 1619312
//! JavaScript symbolication for Vigil (`Vigil.Sourcemap.Native`).
//!
//! * `read_bundle(zip, max_total, max_files)` unpacks an artifact bundle
//!   (sentry-cli `sourcemaps upload`): every entry inflated through a
//!   reader bounded by what is left of `max_total`, so the sizes the zip
//!   declares are never trusted and a zip bomb costs at most `max_total`
//!   bytes. `manifest.json` comes back as bytes, for Elixir to parse.
//! * `lookup(map, minified_source, positions)` parses a source map once
//!   (index maps flattened) and resolves many 0-based minified positions
//!   to original source, line, column, token name, the original function
//!   name where the minified source allows the scope guess, and context
//!   lines from `sourcesContent`.
//!
//! Both run on dirty CPU schedulers: a large map or bundle takes a while.

use std::io::{Cursor, Read};
use std::sync::Arc;

use rustler::{Atom, Binary, Encoder, Env, NifMap, NifResult, OwnedBinary, Term};
use sourcemap::{DecodedMap, SourceView};

mod atoms {
    rustler::atoms! {
        ok,
        error,
        invalid_zip,
        no_manifest,
        too_large,
        too_many_files,
        invalid_map,
    }
}

/// Lines of context on each side of the mapped line, as Sentry shows.
const CONTEXT_LINES: u32 = 5;

static MANIFEST_PATH: &str = "manifest.json";

// ---------------------------------------------------------------------------
// Artifact bundles
// ---------------------------------------------------------------------------

#[rustler::nif(schedule = "DirtyCpu")]
fn read_bundle<'a>(
    env: Env<'a>,
    input: Binary,
    max_total: u64,
    max_files: u64,
) -> NifResult<Term<'a>> {
    match unpack(input.as_slice(), max_total, max_files) {
        Ok((manifest, files)) => {
            let manifest = to_binary(env, &manifest)?;
            let files = files
                .into_iter()
                .map(|(name, bytes)| Ok((name, to_binary(env, &bytes)?)))
                .collect::<NifResult<Vec<_>>>()?;
            Ok((atoms::ok(), (manifest, files)).encode(env))
        }
        Err(reason) => Ok(error(env, reason)),
    }
}

type Unpacked = (Vec<u8>, Vec<(String, Vec<u8>)>);

fn unpack(input: &[u8], max_total: u64, max_files: u64) -> Result<Unpacked, Atom> {
    // symbolic's SourceBundleWriter puts an 8-byte `SYSB` header before
    // the zip; the zip crate finds the archive past such a prefix.
    let mut archive = zip::ZipArchive::new(Cursor::new(input)).map_err(|_| atoms::invalid_zip())?;

    if archive.len() as u64 > max_files.saturating_add(1) {
        return Err(atoms::too_many_files());
    }

    let mut remaining = max_total;
    let mut manifest = None;
    let mut files = Vec::new();

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i).map_err(|_| atoms::invalid_zip())?;
        if entry.is_dir() {
            continue;
        }

        let name = entry.name().map_err(|_| atoms::invalid_zip())?.into_owned();
        let mut bytes = Vec::new();
        (&mut entry)
            .take(remaining.saturating_add(1))
            .read_to_end(&mut bytes)
            .map_err(|_| atoms::invalid_zip())?;

        let len = bytes.len() as u64;
        if len > remaining {
            return Err(atoms::too_large());
        }
        remaining -= len;

        if name == MANIFEST_PATH {
            manifest = Some(bytes);
        } else {
            if files.len() as u64 >= max_files {
                return Err(atoms::too_many_files());
            }
            files.push((name, bytes));
        }
    }

    match manifest {
        Some(manifest) => Ok((manifest, files)),
        None => Err(atoms::no_manifest()),
    }
}

// ---------------------------------------------------------------------------
// Source map lookup
// ---------------------------------------------------------------------------

#[derive(NifMap)]
struct Context {
    pre: Vec<String>,
    line: String,
    post: Vec<String>,
}

#[derive(NifMap)]
struct Mapped {
    src: Option<String>,
    line: u32,
    col: u32,
    name: Option<String>,
    function: Option<String>,
    context: Option<Context>,
}

#[rustler::nif(schedule = "DirtyCpu")]
fn lookup<'a>(
    env: Env<'a>,
    map: Binary,
    minified_source: Option<Binary>,
    positions: Vec<(u32, u32, Option<String>)>,
) -> NifResult<Term<'a>> {
    let map = match decode(map.as_slice()) {
        Some(map) => map,
        None => return Ok(error(env, atoms::invalid_map())),
    };

    let minified = minified_source
        .and_then(|source| {
            std::str::from_utf8(source.as_slice())
                .ok()
                .map(Arc::<str>::from)
        })
        .map(SourceView::new);

    let results: Vec<Option<Mapped>> = positions
        .iter()
        .map(|(line, col, name)| resolve(&map, minified.as_ref(), *line, *col, name.as_deref()))
        .collect();

    Ok((atoms::ok(), results).encode(env))
}

/// A regular or Hermes map; an index map flattened into a regular one (its
/// sections must be embedded, as every bundler writes them).
fn decode(bytes: &[u8]) -> Option<DecodedMap> {
    match sourcemap::decode_slice(bytes).ok()? {
        DecodedMap::Index(index) => index.flatten().ok().map(DecodedMap::Regular),
        map => Some(map),
    }
}

fn resolve(
    map: &DecodedMap,
    minified: Option<&SourceView>,
    line: u32,
    col: u32,
    minified_name: Option<&str>,
) -> Option<Mapped> {
    let token = map.lookup_token(line, col)?;

    // The closest token at or before the position, but on another line, is
    // not this position's: unmapped rather than wrong.
    if token.get_dst_line() != line || !token.has_source() {
        return None;
    }

    let function = map
        .get_original_function_name(line, col, minified_name, minified)
        .map(str::to_owned);

    let (src_line, src_col) = (token.get_src_line(), token.get_src_col());
    let context = token
        .get_source_view()
        .and_then(|view| context(view, src_line, src_col));

    Some(Mapped {
        src: token.get_source().map(str::to_owned),
        line: src_line,
        col: src_col,
        name: token.get_name().map(str::to_owned),
        function,
        context,
    })
}

fn context(view: &SourceView, line: u32, col: u32) -> Option<Context> {
    let current = trim_line(view.get_line(line)?, col);
    let first = line.saturating_sub(CONTEXT_LINES);

    let pre = (first..line)
        .filter_map(|i| view.get_line(i))
        .map(|l| trim_line(l, 0))
        .collect();

    let post = (line + 1..=line + CONTEXT_LINES)
        .map_while(|i| view.get_line(i))
        .map(|l| trim_line(l, 0))
        .collect();

    Some(Context {
        pre,
        line: current,
        post,
    })
}

/// Sentry's `trim_line`: a line over 150 characters is cut to about 140
/// around `column`, with `{snip}` marking the cuts.
fn trim_line(line: &str, column: u32) -> String {
    let line = line.trim_end_matches(['\n', '\r']);
    let chars: Vec<char> = line.chars().collect();
    let len = chars.len();
    if len <= 150 {
        return line.to_owned();
    }

    let column = (column as usize).min(len);
    let mut start = column.saturating_sub(60);
    if start < 5 {
        start = 0;
    }
    let mut end = (start + 140).min(len);
    if end > len - 5 {
        end = len;
    }
    if end == len {
        start = end.saturating_sub(140);
    }

    let mut out: String = chars[start..end].iter().collect();
    if end < len {
        out.push_str(" {snip}");
    }
    if start > 0 {
        out.insert_str(0, "{snip} ");
    }
    out
}

// ---------------------------------------------------------------------------

fn to_binary<'a>(env: Env<'a>, bytes: &[u8]) -> NifResult<Binary<'a>> {
    let mut binary =
        OwnedBinary::new(bytes.len()).ok_or(rustler::Error::Term(Box::new("allocation failed")))?;
    binary.as_mut_slice().copy_from_slice(bytes);
    Ok(binary.release(env))
}

fn error<'a>(env: Env<'a>, reason: Atom) -> Term<'a> {
    (atoms::error(), reason).encode(env)
}

rustler::init!("Elixir.Vigil.Sourcemap.Native");