Skip to content

The platform for continuously improving AI agents.

9.1 KB
Raw Blame
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::custom::CustomSignalSpec;

pub const MAX_EVIDENCE_ITEMS: usize = 10;
pub const MAX_EXCERPT_CHARS: usize = 500;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SignalSeverity {
    High,
    Medium,
    Low,
}

impl SignalSeverity {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::High => "high",
            Self::Medium => "medium",
            Self::Low => "low",
        }
    }

    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "high" => Some(Self::High),
            "medium" => Some(Self::Medium),
            "low" => Some(Self::Low),
            _ => None,
        }
    }

    pub fn rank(self) -> u8 {
        match self {
            Self::High => 3,
            Self::Medium => 2,
            Self::Low => 1,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SignalCatalogItem {
    pub signal_type: String,
    pub title: String,
    pub description: String,
    pub category: String,
    pub severity: SignalSeverity,
    pub default_enabled: bool,
    pub default_params: Value,
    pub remedy: String,
    #[serde(default)]
    pub is_custom: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spec: Option<CustomSignalSpec>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SignalSubscription {
    /// Empty string `""` for global default, or a specific `service.name`.
    pub service_name: String,
    pub signal_type: String,
    pub enabled: bool,
    pub config: Value,
    pub updated_at_ms: i64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SignalEvidence {
    pub span_id: String,
    pub trace_id: String,
    pub name: String,
    pub span_type: Option<String>,
    pub status: String,
    pub status_message: Option<String>,
    pub model: Option<String>,
    pub tool: Option<String>,
    pub duration_ms: f64,
    pub tokens: Option<i64>,
    pub cost: Option<f64>,
    pub input: Option<String>,
    pub output: Option<String>,
    pub reason: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecommendedAction {
    pub kind: String,
    pub label: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SignalDetails {
    pub spans: usize,
    pub group: String,
    pub trace_ids: Vec<String>,
    pub group_trace_ids: Vec<String>,
    pub span_ids: Vec<String>,
    pub why: String,
    pub parameters: Value,
    pub measurements: Value,
    pub evidence: Vec<SignalEvidence>,
    pub evidence_truncated: bool,
    pub recommended_actions: Vec<RecommendedAction>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SignalEvent {
    pub id: String,
    pub signal_type: String,
    pub severity: SignalSeverity,
    pub service_name: String,
    pub message: String,
    pub details: SignalDetails,
    pub trace_id: String,
    pub conversation_id: Option<String>,
    pub dedupe_key: String,
    pub occurred_at_ms: i64,
    pub seen_at_ms: Option<i64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DailyCount {
    pub date: String,
    pub count: i64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SignalInsight {
    pub signal_type: String,
    pub title: String,
    pub category: String,
    pub is_custom: bool,
    pub severity: SignalSeverity,
    /// `"new"`, `"rising"`, `"ongoing"`, or `"falling"`.
    pub status: String,
    pub total_count: i64,
    pub unseen_count: i64,
    pub recent_count: i64,
    pub previous_count: i64,
    pub affected_traces: i64,
    pub remedy: String,
    pub top_causes: Vec<String>,
    pub daily_counts: Vec<DailyCount>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SecretMatch {
    start: usize,
    end: usize,
    kind: &'static str,
    replacement: &'static str,
}

fn is_token_char(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')
}

fn is_boundary_before(bytes: &[u8], idx: usize) -> bool {
    idx == 0 || !bytes[idx - 1].is_ascii_alphanumeric()
}

fn scan_secrets(text: &str) -> Vec<SecretMatch> {
    let bytes = text.as_bytes();
    let len = bytes.len();
    let mut matches = Vec::new();
    let mut i = 0;

    while i < len {
        // Bearer <20+ token chars>
        if bytes[i..].starts_with(b"Bearer ") && is_boundary_before(bytes, i) {
            let token_start = i + 7;
            let mut end = token_start;
            while end < len && is_token_char(bytes[end]) {
                end += 1;
            }
            if end - token_start >= 20 {
                matches.push(SecretMatch {
                    start: i,
                    end,
                    kind: "bearer_token",
                    replacement: "Bearer [REDACTED]",
                });
                i = end;
                continue;
            }
        }

        // AKIA[0-9A-Z]{16}
        if bytes[i..].starts_with(b"AKIA") && is_boundary_before(bytes, i) && i + 20 <= len {
            let suffix = &bytes[i + 4..i + 20];
            let valid_suffix = suffix
                .iter()
                .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit());
            let boundary_after = i + 20 == len || !bytes[i + 20].is_ascii_alphanumeric();
            if valid_suffix && boundary_after {
                matches.push(SecretMatch {
                    start: i,
                    end: i + 20,
                    kind: "aws_access_key",
                    replacement: "[REDACTED]",
                });
                i += 20;
                continue;
            }
        }

        // ghp_<token>
        if bytes[i..].starts_with(b"ghp_") && is_boundary_before(bytes, i) {
            let token_start = i + 4;
            let mut end = token_start;
            while end < len && (bytes[end].is_ascii_alphanumeric() || bytes[end] == b'_') {
                end += 1;
            }
            if end - token_start >= 8 {
                matches.push(SecretMatch {
                    start: i,
                    end,
                    kind: "github_token",
                    replacement: "[REDACTED]",
                });
                i = end;
                continue;
            }
        }

        // sk-<token>
        if bytes[i..].starts_with(b"sk-") && is_boundary_before(bytes, i) {
            let token_start = i + 3;
            let mut end = token_start;
            while end < len && is_token_char(bytes[end]) {
                end += 1;
            }
            if end - token_start >= 8 {
                matches.push(SecretMatch {
                    start: i,
                    end,
                    kind: "api_key",
                    replacement: "[REDACTED]",
                });
                i = end;
                continue;
            }
        }

        i += 1;
    }

    matches
}

pub fn find_secret_matches(text: &str) -> Vec<&'static str> {
    let mut kinds = Vec::new();
    for m in scan_secrets(text) {
        if !kinds.contains(&m.kind) {
            kinds.push(m.kind);
        }
    }
    kinds
}

pub fn redact_secrets(text: &str) -> String {
    let matches = scan_secrets(text);
    if matches.is_empty() {
        return text.to_string();
    }
    let mut out = String::with_capacity(text.len());
    let mut cursor = 0;
    for m in matches {
        out.push_str(&text[cursor..m.start]);
        out.push_str(m.replacement);
        cursor = m.end;
    }
    out.push_str(&text[cursor..]);
    out
}

pub fn clip_and_redact(text: &str, max_chars: usize) -> String {
    let redacted = redact_secrets(text);
    let mut chars = redacted.chars();
    let clipped: String = chars.by_ref().take(max_chars).collect();
    if chars.next().is_some() {
        format!("{clipped}…")
    } else {
        clipped
    }
}

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

    #[test]
    fn redacts_all_supported_secret_patterns() {
        let raw = "key=sk-proj-abc123456789 tok=ghp_1234567890abcdef aws=AKIAIOSFODNN7EXAMPLE auth=Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
        let kinds = find_secret_matches(raw);
        assert_eq!(
            kinds,
            vec!["api_key", "github_token", "aws_access_key", "bearer_token"]
        );

        let redacted = redact_secrets(raw);
        assert!(!redacted.contains("sk-proj-abc123456789"));
        assert!(!redacted.contains("ghp_1234567890abcdef"));
        assert!(!redacted.contains("AKIAIOSFODNN7EXAMPLE"));
        assert!(!redacted.contains("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"));
        assert!(redacted.contains("Bearer [REDACTED]"));
        assert!(redacted.contains("key=[REDACTED]"));
    }

    #[test]
    fn ignores_normal_words_containing_sk_dash() {
        assert!(find_secret_matches("task-manager desk-1234567890").is_empty());
    }

    #[test]
    fn clip_and_redact_clips_after_redacting() {
        let long = format!("{} sk-live-secret123456", "a".repeat(495));
        let clipped = clip_and_redact(&long, 500);
        assert!(!clipped.contains("sk-live"));
        assert!(clipped.chars().count() <= 501);
    }
}