ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! SQL Safety and Injection Prevention Module
//!
//! This module provides comprehensive protection against SQL injection attacks
//! and ensures safe SQL generation throughout the Ignis-DB system.

use crate::common::{validate_identifier, validate_string_literal};
use anyhow::{Context, Result};

/// SQL Safety Context for tracking and validating SQL generation
#[derive(Debug, Clone)]
pub struct SqlSafetyContext {
    /// Track if we're in a potentially dangerous context
    pub in_dynamic_context: bool,
    /// Track the current statement type being generated
    pub current_statement: Option<String>,
    /// Track identifiers that have been validated
    pub validated_identifiers: Vec<String>,
    /// Track string literals that have been escaped
    pub escaped_literals: Vec<String>,
}

impl Default for SqlSafetyContext {
    fn default() -> Self {
        Self {
            in_dynamic_context: false,
            current_statement: None,
            validated_identifiers: Vec::new(),
            escaped_literals: Vec::new(),
        }
    }
}

impl SqlSafetyContext {
    /// Create a new safety context for a specific statement type
    pub fn new(statement_type: &str) -> Self {
        Self {
            current_statement: Some(statement_type.to_string()),
            ..Default::default()
        }
    }

    /// Validate and track an identifier
    pub fn validate_identifier(&mut self, identifier: &str) -> Result<String> {
        let validated = validate_identifier(identifier).with_context(|| {
            format!(
                "Invalid identifier '{}' in statement {:?}",
                identifier, self.current_statement
            )
        })?;

        self.validated_identifiers.push(validated.clone());
        Ok(validated)
    }

    /// Escape and track a string literal
    pub fn escape_literal(&mut self, literal: &str) -> Result<String> {
        let escaped = validate_string_literal(literal).with_context(|| {
            format!(
                "Invalid string literal in statement {:?}",
                self.current_statement
            )
        })?;

        self.escaped_literals.push(escaped.clone());
        Ok(escaped)
    }

    /// Get a summary of safety measures applied
    pub fn safety_summary(&self) -> String {
        let validated_list = if self.validated_identifiers.is_empty() {
            "none".to_string()
        } else {
            self.validated_identifiers.join(", ")
        };

        let escaped_list = if self.escaped_literals.is_empty() {
            "none".to_string()
        } else {
            self.escaped_literals.join(", ")
        };

        format!(
            "SQL Safety Context: Statement={:?}, Validated=[{}], Escaped=[{}], Dynamic={}",
            self.current_statement, validated_list, escaped_list, self.in_dynamic_context
        )
    }
}

/// Safe SQL Builder for constructing SQL statements with validation
#[derive(Clone)]
pub struct SafeSqlBuilder {
    context: SqlSafetyContext,
    sql_parts: Vec<String>,
}

impl SafeSqlBuilder {
    /// Create a new safe SQL builder
    pub fn new(statement_type: &str) -> Self {
        Self {
            context: SqlSafetyContext::new(statement_type),
            sql_parts: Vec::new(),
        }
    }

    /// Add a safely escaped identifier
    pub fn identifier(mut self, identifier: &str) -> Result<Self> {
        let validated = self.context.validate_identifier(identifier)?;
        // The validated identifier already includes quotes from escape_identifier
        self.sql_parts.push(validated);
        Ok(self)
    }

    /// Add multiple safely escaped identifiers
    pub fn identifiers(mut self, identifiers: &[&str]) -> Result<Self> {
        for (i, &id) in identifiers.iter().enumerate() {
            if i > 0 {
                self.sql_parts.push(",".to_string());
            }
            let escaped = self.context.validate_identifier(id)?;
            self.sql_parts.push(escaped);
        }
        Ok(self)
    }

    /// Add a safely escaped string literal
    pub fn literal(mut self, literal: &str) -> Result<Self> {
        let escaped = self.context.escape_literal(literal)?;
        self.sql_parts.push(escaped);
        Ok(self)
    }

    /// Add raw SQL text (use with extreme caution)
    pub fn raw(mut self, text: &str) -> Self {
        self.context.in_dynamic_context = true;
        self.sql_parts.push(text.to_string());
        self
    }

    /// Add a placeholder for parameter binding
    pub fn placeholder(mut self) -> Self {
        self.sql_parts.push("?".to_string());
        self
    }

    /// Add multiple placeholders
    pub fn placeholders(mut self, count: usize) -> Self {
        for _ in 0..count {
            self.sql_parts.push("?".to_string());
        }
        self
    }

    /// Join parts with a separator
    pub fn join_with(mut self, separator: &str) -> Self {
        let joined = self.sql_parts.join(separator);
        self.sql_parts = vec![joined];
        self
    }

    /// Build the final SQL string
    pub fn build(self) -> Result<String> {
        if self.context.in_dynamic_context {
            // Log warning about dynamic context
            eprintln!(
                "⚠️  Warning: SQL built with dynamic content: {}",
                self.context.safety_summary()
            );
        }

        // Join parts with proper SQL formatting
        let mut result = String::new();
        for (i, part) in self.sql_parts.iter().enumerate() {
            if i > 0 {
                // Add space before most parts, but not before commas
                if !part.starts_with(',') && !part.starts_with('(') && !part.starts_with(')') {
                    result.push(' ');
                }
            }
            result.push_str(part);
        }

        Ok(result)
    }

    /// Get the safety context
    pub fn context(&self) -> &SqlSafetyContext {
        &self.context
    }
}

/// Safe SQL generation for common operations
pub mod safe_sql {
    use super::*;

    /// Generate a safe SELECT statement
    pub fn select(table: &str, columns: &[&str]) -> Result<String> {
        let mut builder = SafeSqlBuilder::new("SELECT");

        // Add SELECT keyword
        builder = builder.raw("SELECT");

        // Add escaped column names with proper separation
        for (i, &col) in columns.iter().enumerate() {
            if i > 0 {
                // Add comma without space before the next identifier
                builder = builder.raw(",");
            }
            builder = builder.identifier(col)?;
        }

        // Add FROM clause
        builder = builder.raw("FROM").identifier(table)?;

        builder.build()
    }

    /// Generate a safe INSERT statement
    pub fn insert(table: &str, columns: &[&str]) -> Result<String> {
        let mut builder = SafeSqlBuilder::new("INSERT");

        // Add INSERT INTO clause
        builder = builder.raw("INSERT INTO").identifier(table)?;

        // Add column list
        builder = builder.raw("(");
        for (i, &col) in columns.iter().enumerate() {
            if i > 0 {
                builder = builder.raw(",");
            }
            builder = builder.identifier(col)?;
        }
        builder = builder.raw(")");

        // Add VALUES clause with placeholders
        builder = builder.raw("VALUES").raw("(");
        for (i, _) in columns.iter().enumerate() {
            if i > 0 {
                builder = builder.raw(",");
            }
            builder = builder.placeholder();
        }
        builder = builder.raw(")");

        builder.build()
    }

    /// Generate a safe UPDATE statement
    pub fn update(table: &str, columns: &[&str]) -> Result<String> {
        let mut builder = SafeSqlBuilder::new("UPDATE");

        // Add UPDATE clause
        builder = builder.raw("UPDATE").identifier(table)?;

        // Add SET clause
        builder = builder.raw("SET");
        for (i, &col) in columns.iter().enumerate() {
            if i > 0 {
                builder = builder.raw(",");
            }
            builder = builder.identifier(col)?.raw("=").placeholder();
        }

        builder.build()
    }

    /// Generate a safe DELETE statement
    pub fn delete(table: &str) -> Result<String> {
        let mut builder = SafeSqlBuilder::new("DELETE");

        builder = builder.raw("DELETE FROM").identifier(table)?;

        builder.build()
    }

    /// Generate a safe WHERE clause
    pub fn where_clause(conditions: &[(&str, &str)]) -> Result<String> {
        if conditions.is_empty() {
            return Ok(String::new());
        }

        let mut builder = SafeSqlBuilder::new("WHERE");
        builder = builder.raw("WHERE");

        for (i, (column, _)) in conditions.iter().enumerate() {
            if i > 0 {
                builder = builder.raw("AND");
            }
            builder = builder.identifier(column)?.raw("=").placeholder();
        }

        builder.build()
    }
}

/// Macro for safely building SQL statements
#[macro_export]
macro_rules! safe_sql {
    (SELECT $($col:ident),* FROM $table:ident) => {{
        let columns = vec![$(stringify!($col)),*];
        let table_name = stringify!($table);
        $crate::macros::sql_safety::safe_sql::select(table_name, &columns)
    }};

    (INSERT INTO $table:ident ($($col:ident),*) VALUES) => {{
        let columns = vec![$(stringify!($col)),*];
        let table_name = stringify!($table);
        $crate::macros::sql_safety::safe_sql::insert(table_name, &columns)
    }};

    (UPDATE $table:ident SET $($col:ident),*) => {{
        let columns = vec![$(stringify!($col)),*];
        let table_name = stringify!($table);
        $crate::macros::sql_safety::safe_sql::update(table_name, &columns)
    }};

    (DELETE FROM $table:ident) => {{
        let table_name = stringify!($table);
        $crate::macros::sql_safety::safe_sql::delete(table_name)
    }};
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_safe_sql_builder() {
        let builder = SafeSqlBuilder::new("SELECT")
            .identifier("users")
            .unwrap()
            .raw("FROM")
            .identifier("users")
            .unwrap();

        let sql = builder.build().unwrap();
        assert_eq!(sql, "\"users\" FROM \"users\"");
    }

    #[test]
    fn test_safe_sql_macros() {
        let select_sql = safe_sql!(SELECT id, name FROM users).unwrap();
        assert_eq!(select_sql, "SELECT \"id\", \"name\" FROM \"users\"");

        let insert_sql = safe_sql!(INSERT INTO users (id, name) VALUES).unwrap();
        assert!(insert_sql.contains("INSERT INTO \"users\""));
        assert!(insert_sql.contains("VALUES"));
    }

    #[test]
    fn test_sql_safety_context() {
        let mut context = SqlSafetyContext::new("SELECT");
        context.validate_identifier("users").unwrap();
        context.escape_literal("test").unwrap();

        let summary = context.safety_summary();
        assert!(summary.contains("users"));
        assert!(summary.contains("test"));
    }
}