use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use base64::Engine as _;
use rusqlite::hooks::{AuthAction, AuthContext, Authorization};
use rusqlite::types::{Value as SqlValue, ValueRef};
use rusqlite::{Connection, OpenFlags, TransactionBehavior, params_from_iter};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::model::now_ms;
use crate::store::state_dir;
use super::DebuggerManager;
pub const LEGACY_DEBUGGER_INDEX: &str = "debugger-legacy.sqlite";
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct LegacyDebuggerTableMigration {
pub name: String,
pub rows: u64,
pub source_digest: String,
pub sanitized_source_digest: String,
pub target_digest: String,
pub sanitized_columns: Vec<String>,
pub sanitized_values: u64,
pub matched: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct LegacyDebuggerArtifactMigration {
pub source: String,
pub kind: String,
pub media_type: String,
pub bytes: u64,
pub source_digest: String,
pub artifact_id: String,
pub artifact_path: String,
pub target_digest: String,
pub matched: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct LegacyDebuggerMigration {
pub source: String,
pub index: String,
pub backup: Option<String>,
pub tables: Vec<LegacyDebuggerTableMigration>,
pub total_rows: u64,
pub source_digest: String,
pub sanitized_source_digest: String,
pub target_digest: String,
pub sanitized_values: u64,
pub matched: bool,
#[serde(default)]
pub artifacts: Vec<LegacyDebuggerArtifactMigration>,
#[serde(default)]
pub artifact_files: u64,
#[serde(default)]
pub artifact_bytes: u64,
#[serde(default)]
pub artifact_source_digest: String,
#[serde(default)]
pub artifact_target_digest: String,
#[serde(default = "default_true")]
pub artifacts_matched: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct LegacyDebuggerQuery {
pub index: String,
pub columns: Vec<String>,
pub rows: Vec<BTreeMap<String, Value>>,
pub truncated: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct LegacyDebuggerIndexStatus {
pub index: String,
pub exists: bool,
pub bytes: Option<u64>,
pub tables: usize,
pub rows: u64,
pub digest: Option<String>,
}
struct StagedLegacyDebuggerMigration {
tables: Vec<LegacyDebuggerTableMigration>,
total_rows: u64,
source_digest: String,
sanitized_source_digest: String,
target_digest: String,
sanitized_values: u64,
}
pub fn default_legacy_debugger_index() -> Result<PathBuf, String> {
Ok(state_dir()?.join(LEGACY_DEBUGGER_INDEX))
}
pub fn migrate_legacy_debugger(
source: &Path,
index: Option<&Path>,
replace: bool,
) -> Result<LegacyDebuggerMigration, String> {
if !source.is_file() {
return Err(format!(
"legacy dbg database does not exist: {}",
source.display()
));
}
let index = index
.map(Path::to_path_buf)
.map_or_else(default_legacy_debugger_index, Ok)?;
if source == index {
return Err("legacy source and sanitized index must differ".to_string());
}
if index.exists() && !replace {
return Err(format!(
"sanitized debugger index already exists: {}; pass replace to migrate again",
index.display()
));
}
if let Some(parent) = index.parent() {
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
}
let staging = index.with_extension(format!("sqlite.{}.tmp", uuid::Uuid::now_v7()));
let result = migrate_to_staging(source, &staging);
let staged = match result {
Ok(result) => result,
Err(error) => {
let _ = std::fs::remove_file(&staging);
return Err(error);
}
};
let backup = if index.exists() {
let backup = index.with_extension(format!("sqlite.backup-{}", now_ms()));
std::fs::rename(&index, &backup).map_err(|error| error.to_string())?;
Some(backup)
} else {
None
};
if let Err(error) = std::fs::rename(&staging, &index) {
if let Some(backup) = &backup {
let _ = std::fs::rename(backup, &index);
}
return Err(error.to_string());
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&index, std::fs::Permissions::from_mode(0o600))
.map_err(|error| error.to_string())?;
}
Ok(LegacyDebuggerMigration {
source: source.display().to_string(),
index: index.display().to_string(),
backup: backup.map(|path| path.display().to_string()),
matched: staged.sanitized_source_digest == staged.target_digest,
tables: staged.tables,
total_rows: staged.total_rows,
source_digest: staged.source_digest,
sanitized_source_digest: staged.sanitized_source_digest,
target_digest: staged.target_digest,
sanitized_values: staged.sanitized_values,
artifacts: Vec::new(),
artifact_files: 0,
artifact_bytes: 0,
artifact_source_digest: empty_digest(),
artifact_target_digest: empty_digest(),
artifacts_matched: true,
})
}
impl DebuggerManager {
pub fn import_legacy_debugger_artifacts(
&self,
sources: &[PathBuf],
) -> Result<Vec<LegacyDebuggerArtifactMigration>, String> {
let mut files = BTreeSet::new();
for source in sources {
collect_artifact_files(source, &mut files)?;
}
files
.into_iter()
.map(|source| {
let (source_digest, bytes) = digest_file(&source)?;
let (kind, media_type) = legacy_artifact_type(&source);
let artifact = self.store.put_debugger_artifact_file(
"legacy-debugger-import",
None,
kind,
media_type,
&source,
)?;
let (target_digest, target_bytes) = digest_file(Path::new(&artifact.path))?;
Ok(LegacyDebuggerArtifactMigration {
source: source.display().to_string(),
kind: kind.to_string(),
media_type: media_type.to_string(),
bytes,
source_digest: source_digest.clone(),
artifact_id: artifact.id,
artifact_path: artifact.path,
target_digest: target_digest.clone(),
matched: source_digest == target_digest && bytes == target_bytes,
})
})
.collect()
}
}
pub fn validate_legacy_debugger_artifacts(sources: &[PathBuf]) -> Result<(), String> {
let mut files = BTreeSet::new();
for source in sources {
collect_artifact_files(source, &mut files)?;
}
for file in files {
digest_file(&file)?;
}
Ok(())
}
pub fn attach_legacy_artifact_summary(
migration: &mut LegacyDebuggerMigration,
artifacts: Vec<LegacyDebuggerArtifactMigration>,
) {
let mut source = Sha256::new();
let mut target = Sha256::new();
for artifact in &artifacts {
update_artifact_aggregate(&mut source, &artifact.source, &artifact.source_digest);
update_artifact_aggregate(&mut target, &artifact.source, &artifact.target_digest);
}
migration.artifact_files = artifacts.len() as u64;
migration.artifact_bytes = artifacts.iter().map(|artifact| artifact.bytes).sum();
migration.artifact_source_digest = format!("{:x}", source.finalize());
migration.artifact_target_digest = format!("{:x}", target.finalize());
migration.artifacts_matched = artifacts.iter().all(|artifact| artifact.matched)
&& migration.artifact_source_digest == migration.artifact_target_digest;
migration.artifacts = artifacts;
}
fn collect_artifact_files(path: &Path, files: &mut BTreeSet<PathBuf>) -> Result<(), String> {
let metadata = std::fs::symlink_metadata(path).map_err(|error| {
format!(
"legacy debugger artifact does not exist: {}: {error}",
path.display()
)
})?;
if metadata.file_type().is_symlink() {
return Err(format!(
"legacy debugger artifact symlinks are not followed: {}",
path.display()
));
}
if metadata.is_file() {
files.insert(path.canonicalize().map_err(|error| error.to_string())?);
return Ok(());
}
if !metadata.is_dir() {
return Err(format!(
"legacy debugger artifact is not a regular file or directory: {}",
path.display()
));
}
let mut children = std::fs::read_dir(path)
.map_err(|error| error.to_string())?
.map(|entry| {
entry
.map(|entry| entry.path())
.map_err(|error| error.to_string())
})
.collect::<Result<Vec<_>, _>>()?;
children.sort();
for child in children {
collect_artifact_files(&child, files)?;
}
Ok(())
}
fn digest_file(path: &Path) -> Result<(String, u64), String> {
use std::io::Read as _;
let mut file = std::fs::File::open(path).map_err(|error| error.to_string())?;
let mut digest = Sha256::new();
let mut bytes = 0_u64;
let mut buffer = [0_u8; 64 * 1024];
loop {
let read = file.read(&mut buffer).map_err(|error| error.to_string())?;
if read == 0 {
break;
}
digest.update(&buffer[..read]);
bytes = bytes.saturating_add(read as u64);
}
Ok((format!("{:x}", digest.finalize()), bytes))
}
fn legacy_artifact_type(path: &Path) -> (&'static str, &'static str) {
let extension = path
.extension()
.and_then(|value| value.to_str())
.unwrap_or_default()
.to_ascii_lowercase();
let name = path
.file_name()
.and_then(|value| value.to_str())
.unwrap_or_default()
.to_ascii_lowercase();
match extension.as_str() {
"png" => ("legacy_image", "image/png"),
"jpg" | "jpeg" => ("legacy_image", "image/jpeg"),
"webp" => ("legacy_image", "image/webp"),
"html" | "htm" => ("legacy_report", "text/html"),
"jsonl" | "ndjson" => ("legacy_trace", "application/x-ndjson"),
"json" if name.contains("record") => ("legacy_recording", "application/json"),
"json" => ("legacy_trace", "application/json"),
"zip" => ("legacy_bundle", "application/zip"),
"tar" => ("legacy_bundle", "application/x-tar"),
"bundle" => ("legacy_bundle", "application/octet-stream"),
_ if name.contains("record") => ("legacy_recording", "application/octet-stream"),
_ if name.contains("trace") => ("legacy_trace", "application/octet-stream"),
_ => ("legacy_artifact", "application/octet-stream"),
}
}
fn update_artifact_aggregate(digest: &mut Sha256, source: &str, content_digest: &str) {
digest.update((source.len() as u64).to_le_bytes());
digest.update(source.as_bytes());
digest.update(content_digest.as_bytes());
}
fn empty_digest() -> String {
format!("{:x}", Sha256::digest([]))
}
fn default_true() -> bool {
true
}
pub fn query_legacy_debugger(
index: Option<&Path>,
sql: &str,
limit: usize,
) -> Result<LegacyDebuggerQuery, String> {
let index = index
.map(Path::to_path_buf)
.map_or_else(default_legacy_debugger_index, Ok)?;
if !index.is_file() {
return Err(format!(
"sanitized debugger index does not exist: {}",
index.display()
));
}
let sql = sql.trim();
let lower = sql.to_ascii_lowercase();
if sql.is_empty()
|| sql.contains(';')
|| !(lower.starts_with("select ") || lower.starts_with("with "))
{
return Err("legacy debugger query must be one SELECT or WITH statement".to_string());
}
let limit = limit.clamp(1, 1_000);
let connection = Connection::open_with_flags(
&index,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
.map_err(|error| error.to_string())?;
connection
.execute_batch("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF;")
.map_err(|error| error.to_string())?;
connection
.authorizer(Some(authorize_legacy_query))
.map_err(|error| error.to_string())?;
let wrapped = format!("SELECT * FROM ({sql}) LIMIT {}", limit + 1);
let mut statement = connection
.prepare(&wrapped)
.map_err(|error| error.to_string())?;
let columns = statement
.column_names()
.into_iter()
.map(str::to_string)
.collect::<Vec<_>>();
let mut query = statement.query([]).map_err(|error| error.to_string())?;
let mut rows = Vec::new();
while let Some(row) = query.next().map_err(|error| error.to_string())? {
let mut output = BTreeMap::new();
for (index, column) in columns.iter().enumerate() {
output.insert(
column.clone(),
value_ref_json(row.get_ref(index).map_err(|error| error.to_string())?),
);
}
rows.push(output);
}
let truncated = rows.len() > limit;
rows.truncate(limit);
Ok(LegacyDebuggerQuery {
index: index.display().to_string(),
columns,
rows,
truncated,
})
}
fn authorize_legacy_query(context: AuthContext<'_>) -> Authorization {
match context.action {
AuthAction::Read { .. }
| AuthAction::Select
| AuthAction::Function { .. }
| AuthAction::Recursive => Authorization::Allow,
_ => Authorization::Deny,
}
}
pub fn legacy_debugger_status(index: Option<&Path>) -> Result<LegacyDebuggerIndexStatus, String> {
let index = index
.map(Path::to_path_buf)
.map_or_else(default_legacy_debugger_index, Ok)?;
if !index.is_file() {
return Ok(LegacyDebuggerIndexStatus {
index: index.display().to_string(),
exists: false,
bytes: None,
tables: 0,
rows: 0,
digest: None,
});
}
let connection = Connection::open_with_flags(
&index,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
.map_err(|error| error.to_string())?;
let tables = user_tables(&connection)?;
let (rows, digest) = database_digest(&connection, &tables)?;
Ok(LegacyDebuggerIndexStatus {
index: index.display().to_string(),
exists: true,
bytes: std::fs::metadata(&index)
.ok()
.map(|metadata| metadata.len()),
tables: tables.len(),
rows,
digest: Some(digest),
})
}
fn migrate_to_staging(
source: &Path,
staging: &Path,
) -> Result<StagedLegacyDebuggerMigration, String> {
let source_connection = Connection::open_with_flags(
source,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
.map_err(|error| error.to_string())?;
let tables = user_tables(&source_connection)?;
let mut target = Connection::open(staging).map_err(|error| error.to_string())?;
let transaction = target
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|error| error.to_string())?;
let mut sensitive_by_table = BTreeMap::new();
let mut sanitized_values_by_table = BTreeMap::new();
for table in &tables {
let (sensitive, sanitized_values) =
copy_sanitized_table(&source_connection, &transaction, table)?;
sensitive_by_table.insert(table.clone(), sensitive);
sanitized_values_by_table.insert(table.clone(), sanitized_values);
}
transaction.commit().map_err(|error| error.to_string())?;
let mut migrated = Vec::new();
let mut total_rows = 0;
let mut total_sanitized_values = 0;
for table in &tables {
let (source_rows, source_digest) = table_digest(&source_connection, table)?;
let sensitive = sensitive_by_table
.get(table)
.ok_or_else(|| format!("missing sanitization plan for legacy table {table}"))?;
let (_, sanitized_source_digest) =
table_digest_with_sanitization(&source_connection, table, sensitive)?;
let (target_rows, target_digest) = table_digest(&target, table)?;
if source_rows != target_rows {
return Err(format!(
"legacy table {table} row count changed from {source_rows} to {target_rows}"
));
}
total_rows += source_rows;
let sanitized_values = *sanitized_values_by_table.get(table).unwrap_or(&0);
total_sanitized_values += sanitized_values;
migrated.push(LegacyDebuggerTableMigration {
name: table.clone(),
rows: source_rows,
matched: sanitized_source_digest == target_digest,
source_digest,
sanitized_source_digest,
target_digest,
sanitized_columns: sensitive.iter().cloned().collect(),
sanitized_values,
});
}
let (_, source_digest) = database_digest(&source_connection, &tables)?;
let sanitized_source_digest = database_digest_from_tables(
migrated
.iter()
.map(|table| (&table.name, table.rows, &table.sanitized_source_digest)),
);
let (_, target_digest) = database_digest(&target, &tables)?;
if sanitized_source_digest != target_digest || migrated.iter().any(|table| !table.matched) {
return Err("legacy debugger migration digest mismatch".to_string());
}
Ok(StagedLegacyDebuggerMigration {
tables: migrated,
total_rows,
source_digest,
sanitized_source_digest,
target_digest,
sanitized_values: total_sanitized_values,
})
}
fn user_tables(connection: &Connection) -> Result<Vec<String>, String> {
let mut statement = connection
.prepare(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
)
.map_err(|error| error.to_string())?;
let rows = statement
.query_map([], |row| row.get::<_, String>(0))
.map_err(|error| error.to_string())?;
rows.collect::<Result<Vec<_>, _>>()
.map_err(|error| error.to_string())
}
fn copy_sanitized_table(
source: &Connection,
target: &rusqlite::Transaction<'_>,
table: &str,
) -> Result<(BTreeSet<String>, u64), String> {
let columns = table_columns(source, table)?;
if columns.is_empty() {
return Err(format!("legacy table {table} has no columns"));
}
let sensitive = columns
.iter()
.filter(|column| !legacy_query_column_is_safe(&column.name))
.map(|column| column.name.clone())
.collect::<BTreeSet<_>>();
let definition = columns
.iter()
.map(|column| format!("{} {}", quote_identifier(&column.name), column.affinity))
.collect::<Vec<_>>()
.join(", ");
target
.execute_batch(&format!(
"CREATE TABLE {} ({definition})",
quote_identifier(table)
))
.map_err(|error| format!("could not create sanitized table {table}: {error}"))?;
let mut source_statement = source
.prepare(&format!("SELECT * FROM {}", quote_identifier(table)))
.map_err(|error| error.to_string())?;
let placeholders = (1..=columns.len())
.map(|index| format!("?{index}"))
.collect::<Vec<_>>()
.join(", ");
let mut insert = target
.prepare(&format!(
"INSERT INTO {} VALUES ({placeholders})",
quote_identifier(table)
))
.map_err(|error| error.to_string())?;
let mut rows = source_statement
.query([])
.map_err(|error| error.to_string())?;
let mut sanitized_values = 0;
while let Some(row) = rows.next().map_err(|error| error.to_string())? {
let mut values = Vec::with_capacity(columns.len());
for (index, column) in columns.iter().enumerate() {
let value = row.get_ref(index).map_err(|error| error.to_string())?;
let sanitize = sensitive.contains(&column.name)
&& matches!(value, ValueRef::Text(_) | ValueRef::Blob(_));
if sanitize {
sanitized_values += 1;
}
values.push(owned_sanitized_value(value, sanitize));
}
insert
.execute(params_from_iter(values))
.map_err(|error| format!("could not copy sanitized row from {table}: {error}"))?;
}
Ok((sensitive, sanitized_values))
}
struct LegacyColumn {
name: String,
affinity: &'static str,
}
fn table_columns(connection: &Connection, table: &str) -> Result<Vec<LegacyColumn>, String> {
let mut statement = connection
.prepare(&format!("PRAGMA table_info({})", quote_identifier(table)))
.map_err(|error| error.to_string())?;
let rows = statement
.query_map([], |row| {
let name = row.get::<_, String>(1)?;
let declared = row.get::<_, String>(2)?;
Ok(LegacyColumn {
name,
affinity: portable_sqlite_affinity(&declared),
})
})
.map_err(|error| error.to_string())?;
rows.collect::<Result<Vec<_>, _>>()
.map_err(|error| error.to_string())
}
fn portable_sqlite_affinity(declared: &str) -> &'static str {
let declared = declared.to_ascii_uppercase();
if declared.contains("INT") {
"INTEGER"
} else if declared.contains("CHAR") || declared.contains("CLOB") || declared.contains("TEXT") {
"TEXT"
} else if declared.contains("REAL") || declared.contains("FLOA") || declared.contains("DOUB") {
"REAL"
} else if declared.is_empty() || declared.contains("BLOB") {
"BLOB"
} else {
"NUMERIC"
}
}
fn legacy_query_column_is_safe(column: &str) -> bool {
let column = column.to_ascii_lowercase();
column == "id"
|| column.ends_with("_id")
|| matches!(
column.as_str(),
"source"
| "category"
| "method"
| "kind"
| "status"
| "mode"
| "backend"
| "protocol"
| "target_type"
| "access"
| "tier"
| "metric"
| "rule"
| "anchor_kind"
| "hash"
| "sha256"
)
}
fn owned_sanitized_value(value: ValueRef<'_>, sanitize: bool) -> SqlValue {
if sanitize {
return SqlValue::Text("[redacted]".to_string());
}
match value {
ValueRef::Null => SqlValue::Null,
ValueRef::Integer(value) => SqlValue::Integer(value),
ValueRef::Real(value) => SqlValue::Real(value),
ValueRef::Text(value) => SqlValue::Text(String::from_utf8_lossy(value).into_owned()),
ValueRef::Blob(value) => SqlValue::Blob(value.to_vec()),
}
}
fn database_digest(connection: &Connection, tables: &[String]) -> Result<(u64, String), String> {
let mut rows = 0;
let mut table_digests = Vec::new();
for table in tables {
let (table_rows, table_digest) = table_digest(connection, table)?;
rows += table_rows;
table_digests.push((table, table_rows, table_digest));
}
Ok((
rows,
database_digest_from_tables(
table_digests
.iter()
.map(|(table, rows, digest)| (*table, *rows, digest)),
),
))
}
fn database_digest_from_tables<'a>(
tables: impl IntoIterator<Item = (&'a String, u64, &'a String)>,
) -> String {
let mut digest = Sha256::new();
for (table, rows, table_digest) in tables {
digest.update(table.as_bytes());
digest.update(rows.to_le_bytes());
digest.update(table_digest.as_bytes());
}
format!("sha256:{:x}", digest.finalize())
}
fn table_digest(connection: &Connection, table: &str) -> Result<(u64, String), String> {
table_digest_with_sanitization(connection, table, &BTreeSet::new())
}
fn table_digest_with_sanitization(
connection: &Connection,
table: &str,
sensitive: &BTreeSet<String>,
) -> Result<(u64, String), String> {
let mut statement = connection
.prepare(&format!("SELECT * FROM {}", quote_identifier(table)))
.map_err(|error| error.to_string())?;
let columns = statement
.column_names()
.into_iter()
.map(str::to_string)
.collect::<Vec<_>>();
let mut query = statement.query([]).map_err(|error| error.to_string())?;
let mut row_digests = Vec::new();
while let Some(row) = query.next().map_err(|error| error.to_string())? {
let mut digest = Sha256::new();
for (index, column) in columns.iter().enumerate() {
digest.update(column.as_bytes());
let value = row.get_ref(index).map_err(|error| error.to_string())?;
digest_value_ref(
&mut digest,
if sensitive.contains(column)
&& matches!(value, ValueRef::Text(_) | ValueRef::Blob(_))
{
ValueRef::Text(b"[redacted]")
} else {
value
},
);
}
row_digests.push(digest.finalize().to_vec());
}
row_digests.sort();
let mut digest = Sha256::new();
for row in &row_digests {
digest.update(row);
}
Ok((
row_digests.len() as u64,
format!("sha256:{:x}", digest.finalize()),
))
}
fn digest_value_ref(digest: &mut Sha256, value: ValueRef<'_>) {
match value {
ValueRef::Null => digest.update([0]),
ValueRef::Integer(value) => {
digest.update([1]);
digest.update(value.to_le_bytes());
}
ValueRef::Real(value) => {
digest.update([2]);
digest.update(value.to_bits().to_le_bytes());
}
ValueRef::Text(value) => {
digest.update([3]);
digest.update((value.len() as u64).to_le_bytes());
digest.update(value);
}
ValueRef::Blob(value) => {
digest.update([4]);
digest.update((value.len() as u64).to_le_bytes());
digest.update(value);
}
}
}
fn value_ref_json(value: ValueRef<'_>) -> Value {
match value {
ValueRef::Null => Value::Null,
ValueRef::Integer(value) => Value::Number(value.into()),
ValueRef::Real(value) => serde_json::Number::from_f64(value)
.map(Value::Number)
.unwrap_or(Value::Null),
ValueRef::Text(value) => Value::String(String::from_utf8_lossy(value).into_owned()),
ValueRef::Blob(value) => serde_json::json!({
"base64":base64::engine::general_purpose::STANDARD.encode(value)
}),
}
}
fn quote_identifier(identifier: &str) -> String {
format!("\"{}\"", identifier.replace('"', "\"\""))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn migrates_every_table_with_matching_counts_and_digests_and_queries_joins() {
let fixture = tempfile::tempdir().unwrap();
let source = fixture.path().join("legacy-source.sqlite");
let index = fixture.path().join("sanitized.sqlite");
let connection = Connection::open(&source).unwrap();
connection
.execute_batch(
"CREATE TABLE events(id INTEGER PRIMARY KEY, ts INTEGER, session_id TEXT, data TEXT);
CREATE TABLE captures(id TEXT PRIMARY KEY, ts INTEGER, session_id TEXT, screenshot_path TEXT);
INSERT INTO events VALUES(1, 10, 's0', '{\"kind\":\"console\"}');
INSERT INTO events VALUES(2, 20, 's0', '{\"kind\":\"route\"}');
INSERT INTO captures VALUES('c0', 15, 's0', '/tmp/capture.png');",
)
.unwrap();
drop(connection);
let migrated = migrate_legacy_debugger(&source, Some(&index), false).unwrap();
assert!(migrated.matched);
assert_eq!(migrated.tables.len(), 2);
assert_eq!(migrated.total_rows, 3);
assert_ne!(migrated.source_digest, migrated.target_digest);
assert_eq!(migrated.sanitized_source_digest, migrated.target_digest);
assert_eq!(migrated.sanitized_values, 3);
let result = query_legacy_debugger(
Some(&index),
"SELECT events.id, captures.screenshot_path FROM events JOIN captures USING(session_id) ORDER BY events.id",
10,
)
.unwrap();
assert_eq!(result.rows.len(), 2);
assert_eq!(result.rows[0]["id"], 1);
assert_eq!(result.rows[0]["screenshot_path"], "[redacted]");
assert!(!result.truncated);
}
#[test]
fn query_rejects_mutation_and_caps_rows() {
let fixture = tempfile::tempdir().unwrap();
let index = fixture.path().join("index.sqlite");
let connection = Connection::open(&index).unwrap();
connection
.execute_batch("CREATE TABLE events(id INTEGER); INSERT INTO events VALUES(1),(2),(3);")
.unwrap();
drop(connection);
assert!(query_legacy_debugger(Some(&index), "DELETE FROM events", 10).is_err());
assert!(
query_legacy_debugger(
Some(&index),
"WITH removed AS (DELETE FROM events RETURNING id) SELECT * FROM removed",
10
)
.is_err()
);
let result =
query_legacy_debugger(Some(&index), "SELECT * FROM events ORDER BY id", 2).unwrap();
assert_eq!(result.rows.len(), 2);
assert!(result.truncated);
}
#[cfg(unix)]
#[test]
fn artifact_preflight_rejects_symlinks_without_following_them() {
use std::os::unix::fs::symlink;
let fixture = tempfile::tempdir().unwrap();
let target = fixture.path().join("target.json");
let link = fixture.path().join("trace.json");
std::fs::write(&target, b"secret legacy trace").unwrap();
symlink(&target, &link).unwrap();
let error = validate_legacy_debugger_artifacts(&[link]).unwrap_err();
assert!(error.contains("symlinks are not followed"), "{error}");
}
}