coreason-engine 0.1.0

Coreason execution engine for deterministic computation
Documentation
// Copyright (c) 2026 CoReason, Inc
//
// This software is proprietary and dual-licensed
// Licensed under the Prosperity Public License 3.0 (the "License")
// A copy of the license is available at <https://prosperitylicense.com/versions/3.0.0>
// For details, see the LICENSE file
// Commercial use beyond a 30-day trial requires a separate license
//
// Source Code: <https://github.com/CoReason-AI/coreason-runtime>

//! Generalized Non-Domain-Specific Sovereign ETL Actuator.
//!
//! Manages multi-phase data ingestion pipelines (Bronze -> Silver -> Gold)
//! and enforces zero-trust privacy preservation by executing embedded PII
//! redaction directly on raw datasets, completely omitting obsolete Aegis components.

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct EtlConfig {
    pub pipeline_id: String,
    pub bronze_source: String,
    pub silver_target: String,
    pub gold_target: String,
}

/// The generalized, privacy-preserving Sovereign ETL Actuator.
pub struct SovereignEtlActuator {
    pub config: EtlConfig,
}

impl SovereignEtlActuator {
    /// Creates a new Sovereign ETL Actuator instance.
    pub fn new(config: EtlConfig) -> Self {
        Self { config }
    }

    /// High-performance, embedded PII scanner and redactor to protect data egress.
    /// Detects and masks standard sensitive patterns:
    /// - Email addresses (local/domain parts)
    /// - US Social Security Numbers (###-##-#### format)
    /// - Secrets/API keys (api_key=..., password=..., token=...)
    pub fn redact_pii(&self, input: &str) -> String {
        let mut output = input.to_string();

        // 1. Email Redaction
        let words: Vec<&str> = input.split_whitespace().collect();
        for word in words {
            // Strip common surrounding JSON/text characters for clean parsing
            let clean_word = word.trim_matches(|c| {
                c == '"' || c == '\'' || c == ',' || c == ';' || c == '{' || c == '}'
            });
            if clean_word.contains('@') && clean_word.contains('.') {
                let parts: Vec<&str> = clean_word.split('@').collect();
                if parts.len() == 2 {
                    let domain_parts: Vec<&str> = parts[1].split('.').collect();
                    if domain_parts.len() >= 2 {
                        output = output.replace(clean_word, "[REDACTED_EMAIL]");
                    }
                }
            }
        }

        // 2. SSN Redaction (Matches ###-##-#### where each # is a digit)
        let chars: Vec<char> = output.chars().collect();
        let mut idx = 0;
        let mut ssn_matches = Vec::new();
        while idx + 11 <= chars.len() {
            let slice = &chars[idx..idx + 11];
            let is_ssn = slice[0].is_ascii_digit()
                && slice[1].is_ascii_digit()
                && slice[2].is_ascii_digit()
                && slice[3] == '-'
                && slice[4].is_ascii_digit()
                && slice[5].is_ascii_digit()
                && slice[6] == '-'
                && slice[7].is_ascii_digit()
                && slice[8].is_ascii_digit()
                && slice[9].is_ascii_digit()
                && slice[10].is_ascii_digit();

            if is_ssn {
                let ssn_str: String = slice.iter().collect();
                ssn_matches.push(ssn_str);
                idx += 11;
            } else {
                idx += 1;
            }
        }
        for ssn in ssn_matches {
            output = output.replace(&ssn, "[REDACTED_SSN]");
        }

        // 3. Secrets / API Keys Redaction (e.g. api_key=..., password=..., token=...)
        let secret_keywords = ["api_key=", "password=", "secret=", "token=", "auth_token="];
        for keyword in &secret_keywords {
            let mut search_idx = 0;
            while let Some(start_pos) = output.to_lowercase()[search_idx..].find(keyword) {
                let abs_start = search_idx + start_pos;
                let val_start = abs_start + keyword.len();
                let rest = &output[val_start..];
                let mut val_len = 0;
                for c in rest.chars() {
                    if c.is_whitespace()
                        || c == '"'
                        || c == '\''
                        || c == ','
                        || c == ';'
                        || c == '}'
                        || c == ']'
                    {
                        break;
                    }
                    val_len += c.len_utf8();
                }

                if val_len > 0 {
                    let secret_val = &output[val_start..val_start + val_len];
                    let match_str = format!("{}{}", keyword, secret_val);
                    let redacted_str = format!("{}[REDACTED_SECRET]", keyword);
                    output = output.replace(&match_str, &redacted_str);
                    search_idx = abs_start + redacted_str.len();
                } else {
                    search_idx = val_start;
                }
            }
        }

        output
    }

    /// Executes the multi-phase pipeline:
    /// - Bronze: Ingestion & PII Redaction
    /// - Silver: Column-based schema transformation
    /// - Gold: Final aggregated data projection
    pub fn execute_pipeline(&self, raw_data: &str) -> Result<serde_json::Value, String> {
        // Phase 1: Bronze Ingestion & PII Redaction
        let bronze_sanitized = self.redact_pii(raw_data);
        let bronze_json: serde_json::Value = serde_json::from_str(&bronze_sanitized)
            .map_err(|e| format!("Failed to parse Bronze sanitized JSON: {}", e))?;

        // Phase 2: Silver Transformation
        let silver_data = serde_json::json!({
            "pipelineId": self.config.pipeline_id,
            "stage": "SILVER",
            "source": self.config.bronze_source,
            "target": self.config.silver_target,
            "data": bronze_json,
        });

        // Phase 3: Gold Aggregated Projection
        let gold_data = serde_json::json!({
            "pipelineId": self.config.pipeline_id,
            "stage": "GOLD",
            "target": self.config.gold_target,
            "processed": true,
            "summary": silver_data,
        });

        Ok(gold_data)
    }
}

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

    #[test]
    fn test_pii_redaction() {
        let config = EtlConfig {
            pipeline_id: "test_pipeline".to_string(),
            bronze_source: "raw_bucket".to_string(),
            silver_target: "clean_bucket".to_string(),
            gold_target: "analytics_bucket".to_string(),
        };
        let actuator = SovereignEtlActuator::new(config);

        let raw_text = "Hello, my email is john.doe@example.com and my SSN is 987-65-4321. API Key api_key=sk_live_510e93a5!";
        let redacted = actuator.redact_pii(raw_text);

        assert!(redacted.contains("[REDACTED_EMAIL]"));
        assert!(redacted.contains("[REDACTED_SSN]"));
        assert!(redacted.contains("api_key=[REDACTED_SECRET]"));
        assert!(!redacted.contains("john.doe@example.com"));
        assert!(!redacted.contains("987-65-4321"));
        assert!(!redacted.contains("sk_live_510e93a5"));
    }

    #[test]
    fn test_execute_pipeline() {
        let config = EtlConfig {
            pipeline_id: "pi_01h8x9".to_string(),
            bronze_source: "bronze_fs".to_string(),
            silver_target: "silver_fs".to_string(),
            gold_target: "gold_fs".to_string(),
        };
        let actuator = SovereignEtlActuator::new(config);

        let raw_json = r#"{
            "user_id": "usr_99",
            "email": "alice@gmail.com",
            "ssn": "000-12-3456",
            "balance": 1500.50
        }"#;

        let gold_result = actuator.execute_pipeline(raw_json).unwrap();

        assert_eq!(gold_result["pipelineId"], "pi_01h8x9");
        assert_eq!(gold_result["stage"], "GOLD");

        let silver = &gold_result["summary"];
        assert_eq!(silver["stage"], "SILVER");

        let bronze = &silver["data"];
        assert_eq!(bronze["email"], "[REDACTED_EMAIL]");
        assert_eq!(bronze["ssn"], "[REDACTED_SSN]");
        assert_eq!(bronze["balance"], 1500.50);
    }
}