// SPF Smart Gateway - Gate (Primary Enforcement Point) // Copyright 2026 Joseph Stone - All Rights Reserved // // Every tool call passes through here. Calculate -> Validate -> Allow/Warn. // Max mode: violations warn + force CRITICAL tier. Never blocks — escalates. // Enforcement: compiled validation rules, write whitelist, path blocking, // Build Anchor protocol, content inspection. No runtime config bypass. // // REFACTOR: Source-aware gate — source: &Source added to process(). // gate::process() is the SINGLE ENTRY POINT. Called before handle_tool_call // on every path (stdio, dispatch, FLINT). No gate calls inside match arms. // Source::Transformer (FLINT) — same permissions as Stdio. Full tool access. use chrono::Utc; use crate::calculate::{self, ComplexityResult, ToolParams}; use crate::config::{EnforceMode, SpfConfig}; use crate::dispatch::Source; use crate::inspect; use crate::session::Session; use crate::validate; use serde::{Deserialize, Serialize}; /// Gate decision — the final word on whether a tool call proceeds #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GateDecision { pub allowed: bool, pub tool: String, pub complexity: ComplexityResult, pub warnings: Vec, pub errors: Vec, pub message: String, } /// Human-readable summary of what the action will do. fn format_params(tool: &str, params: &ToolParams) -> String { match tool { "Bash" | "spf_bash" => { format!("Command: {}", params.command.as_deref().unwrap_or("(none)")) } "Read" | "spf_read" => { format!("File: {}", params.file_path.as_deref().unwrap_or("(none)")) } "Write" | "spf_write" => { let len = params.content.as_ref().map(|c| c.len()).unwrap_or(0); format!("File: {} | Content: {} bytes", params.file_path.as_deref().unwrap_or("(none)"), len) } "Edit" | "spf_edit" => { let old_preview: String = params.old_string.as_deref() .unwrap_or("").chars().take(60).collect(); let new_preview: String = params.new_string.as_deref() .unwrap_or("").chars().take(60).collect(); format!("File: {} | Replace: \"{}...\" -> \"{}...\"", params.file_path.as_deref().unwrap_or("(none)"), old_preview, new_preview) } "Glob" | "spf_glob" => { format!("Pattern: {} | Path: {}", params.command.as_deref().unwrap_or("*"), params.file_path.as_deref().unwrap_or(".")) } "Grep" | "spf_grep" => { format!("Pattern: {} | Path: {}", params.command.as_deref().unwrap_or(""), params.file_path.as_deref().unwrap_or(".")) } _ => { let mut parts = Vec::new(); if let Some(ref cmd) = params.command { parts.push(format!("arg: {}", cmd)); } if let Some(ref fp) = params.file_path { parts.push(format!("path: {}", fp)); } if parts.is_empty() { "(no params)".to_string() } else { parts.join(" | ") } } } } // ============================================================================ // GATE PROCESS — single entry point for all tool calls // ============================================================================ /// Process a tool call through the gate. /// Called BEFORE handle_tool_call on every path — gate is the door. /// /// Pipeline: /// 0. Source logging — who is calling? (logged, not blocked) /// 1. Rate limiting /// 2. Calculate complexity (C, tier, allocation) /// 3. Validate against rules (blocked paths, Build Anchor, write whitelist) /// 4. Content inspection on Write/Edit /// 5. Max mode escalation /// 6. Return allow/block decision pub fn process( tool: &str, params: &ToolParams, config: &SpfConfig, session: &Session, source: &Source, ) -> GateDecision { // ── STEP 0: SOURCE LOGGING ──────────────────────────────────────────────── // Log source identity for training pipeline. FLINT has full tool access — // same permissions as Stdio. All calls still pass through validation below. if let Source::Transformer { ref role, ref model_id } = source { eprintln!("[GATE] Source::Transformer role={} model={} tool={}", role, model_id, tool); } // ── STEP 1: RATE LIMITING ──────────────────────────────────────────────── let now = Utc::now(); let one_minute_ago = now - chrono::Duration::seconds(60); let recent_count = session.rate_window.iter() .filter(|ts| **ts > one_minute_ago) .count(); let max_per_minute = match tool { "Write" | "spf_write" | "Edit" | "spf_edit" | "Bash" | "spf_bash" | "spf_web_download" | "spf_notebook_edit" => 60, "spf_web_fetch" | "spf_web_search" | "spf_web_api" => 30, "spf_web_connect" | "spf_web_navigate" => 20, "spf_web_click" | "spf_web_fill" | "spf_web_select" | "spf_web_eval" | "spf_web_screenshot" | "spf_web_design" | "spf_web_page" => 60, "spf_mesh_call" => 60, _ => 120, }; if recent_count >= max_per_minute { let msg = format!("RATE LIMITED: {} calls in last minute (max {})", recent_count, max_per_minute); return GateDecision { allowed: false, tool: tool.to_string(), complexity: ComplexityResult { tool: tool.to_string(), c: 0, tier: "RATE_LIMITED".to_string(), analyze_percent: 100, build_percent: 0, a_optimal_tokens: 0, requires_approval: true, }, warnings: vec![], errors: vec![msg.clone()], message: format!("BLOCKED | {} | {}", tool, msg), }; } // ── STEP 2: CALCULATE COMPLEXITY ──────────────────────────────────────── let mut complexity = calculate::calculate(tool, params, config); let mut warnings = Vec::new(); let mut errors = Vec::new(); // ── STEP 3: VALIDATE AGAINST RULES ────────────────────────────────────── let validation = match tool { "Edit" | "spf_edit" => { let file_path = params.file_path.as_deref().unwrap_or("unknown"); validate::validate_edit(file_path, config, session) } "Write" | "spf_write" => { let file_path = params.file_path.as_deref().unwrap_or("unknown"); let content_len = params.content.as_ref().map(|c| c.len()).unwrap_or(0); validate::validate_write(file_path, content_len, config, session) } "Bash" | "spf_bash" => { let command = params.command.as_deref().unwrap_or(""); validate::validate_bash(command, config, Some(session)) } "Read" | "spf_read" => { let file_path = params.file_path.as_deref().unwrap_or("unknown"); validate::validate_read(file_path, config) } "spf_web_download" => { // Check source URL first (SSRF guard), then validate save path let url_result = validate::validate_url(params, config); if !url_result.valid { url_result } else { let file_path = params.file_path.as_deref().unwrap_or("unknown"); validate::validate_write(file_path, 0, config, session) } } "spf_notebook_edit" => { let file_path = params.file_path.as_deref().unwrap_or("unknown"); let content_len = params.content.as_ref().map(|c| c.len()).unwrap_or(0); validate::validate_write(file_path, content_len, config, session) } // HARD BLOCK — spf_fs_* tools are USER/SYSTEM-ONLY, never via AI "spf_fs_import" | "spf_fs_export" | "spf_fs_exists" | "spf_fs_stat" | "spf_fs_ls" | "spf_fs_read" | "spf_fs_write" | "spf_fs_mkdir" | "spf_fs_rm" | "spf_fs_rename" => { validate::ValidationResult { valid: false, warnings: vec![], errors: vec![format!("BLOCKED: {} is a user/system-only command — not available to AI agents", tool)], } } // ── TIER A — Filesystem reads (path traversal + sensitive prefix) ───── "Glob" | "spf_glob" | "Grep" | "spf_grep" | "spf_rag_collect_file" | "spf_rag_collect_folder" => validate::validate_fs_read(params, config), // ── TIER B — Web/URL (scheme + SSRF check) ──────────────────────────── "spf_web_fetch" | "spf_web_api" | "spf_web_navigate" => validate::validate_url(params, config), // ── TIER B+ — RAG content (URL + length + injection) ────────────────── "spf_rag_collect_web" | "spf_rag_fetch_url" => validate::validate_rag_content(params, config), // ── TIER C — Controlled delegation ──────────────────────────────────── "spf_flint_execute" => validate::validate_flint_execute(params, config), "spf_mesh_call" => validate::validate_mesh_call(params, config), // ── TIER D — Bounded inference ───────────────────────────────────────── "spf_transformer_infer" | "spf_transformer_chat" | "spf_transformer_train" | "spf_flint_train_evil" | "spf_flint_train_good" | "spf_flint_store" => validate::validate_transformer_ops(params, config), // ── TIER E+ — Brain write (source-gated) ──────────────────────────── // FLINT router thread writes brain via direct calls (bypasses gate). // Only MCP Source::Stdio reaches here — block agent brain writes. "spf_brain_store" | "spf_brain_index" => { match source { Source::Stdio => validate::ValidationResult::block( "BRAIN-WRITE: brain_store/brain_index blocked from agent (Source::Stdio). \ FLINT owns brain writes. Use brain_search/brain_recall to read.".to_string() ), _ => validate::ValidationResult::ok(), } }, // ── TIER E — Safe read-only (no mutation risk) ──────────────────────── "spf_calculate" | "spf_status" | "spf_session" | "spf_web_search" | "spf_brain_search" | "spf_brain_context" | "spf_brain_list" | "spf_brain_status" | "spf_brain_recall" | "spf_brain_list_docs" | "spf_brain_get_doc" | "spf_rag_collect_drop" | "spf_rag_index_gathered" | "spf_rag_dedupe" | "spf_rag_status" | "spf_rag_list_gathered" | "spf_rag_bandwidth_status" | "spf_rag_collect_rss" | "spf_rag_list_feeds" | "spf_rag_pending_searches" | "spf_rag_fulfill_search" | "spf_rag_smart_search" | "spf_rag_auto_fetch_gaps" | "spf_config_paths" | "spf_config_stats" | "spf_projects_list" | "spf_projects_get" | "spf_projects_set" | "spf_projects_delete" | "spf_projects_stats" | "spf_tmp_list" | "spf_tmp_stats" | "spf_tmp_get" | "spf_tmp_active" | "spf_agent_stats" | "spf_agent_memory_search" | "spf_agent_memory_by_tag" | "spf_agent_session_info" | "spf_agent_context" | "spf_web_connect" | "spf_web_click" | "spf_web_fill" | "spf_web_select" | "spf_web_eval" | "spf_web_screenshot" | "spf_web_design" | "spf_web_page" | "spf_mesh_status" | "spf_mesh_peers" | "spf_transformer_status" | "spf_transformer_metrics" | "spf_voice_mode" | "spf_voice_call" | "spf_voice_team" | "spf_chat_send" | "spf_chat_receive" | "spf_chat_history" | "spf_chat_rooms" | "spf_pool_status" | "spf_pool_assign" | "spf_pool_release" | "spf_channel" => validate::ValidationResult::ok(), // DEFAULT DENY — unknown tools blocked until explicitly added _ => { validate::ValidationResult { valid: false, warnings: vec![], errors: vec![format!("BLOCKED: unknown tool '{}' — not in gate allowlist", tool)], } } }; warnings.extend(validation.warnings); errors.extend(validation.errors); // ── STEP 4: CONTENT INSPECTION ─────────────────────────────────────────── let inspection = match tool { "Write" | "spf_write" => { let file_path = params.file_path.as_deref().unwrap_or("unknown"); let content = params.content.as_deref().unwrap_or(""); inspect::inspect_content(content, file_path, config) } "Edit" | "spf_edit" => { let file_path = params.file_path.as_deref().unwrap_or("unknown"); let new_string = params.new_string.as_deref().unwrap_or(""); inspect::inspect_content(new_string, file_path, config) } "spf_notebook_edit" => { let file_path = params.file_path.as_deref().unwrap_or("unknown"); let content = params.content.as_deref().unwrap_or(""); inspect::inspect_content(content, file_path, config) } "spf_flint_store" => { let content = params.text.as_deref().unwrap_or(""); inspect::inspect_content(content, "brain_store:text", config) } _ => validate::ValidationResult::ok(), }; warnings.extend(inspection.warnings); errors.extend(inspection.errors); // ── STEP 5: MAX MODE ESCALATION ────────────────────────────────────────── if config.enforce_mode == EnforceMode::Max { let has_max_warnings = warnings.iter().any(|w| w.starts_with("MAX TIER:")); if has_max_warnings { complexity.tier = "CRITICAL".to_string(); complexity.analyze_percent = config.tiers.critical.analyze_percent; complexity.build_percent = config.tiers.critical.build_percent; complexity.requires_approval = true; warnings.push("ESCALATED TO CRITICAL TIER — Max mode enforcement".to_string()); } } let allowed = validation.valid && inspection.valid; let details = format_params(tool, params); let message = if allowed { format!("ALLOWED | {} | C={} | {} | {}%/{}% | {}", tool, complexity.c, complexity.tier, complexity.analyze_percent, complexity.build_percent, details) } else { format!("BLOCKED | {} | C={} | {} errors | {}", tool, complexity.c, errors.len(), details) }; GateDecision { allowed, tool: tool.to_string(), complexity, warnings, errors, message } } // ============================================================================ // TESTS // ============================================================================ #[cfg(test)] mod tests { use super::*; use crate::config::SpfConfig; use crate::session::Session; fn default_config() -> SpfConfig { SpfConfig::default() } fn stdio() -> Source { Source::Stdio } fn transformer() -> Source { Source::Transformer { role: "worker".to_string(), model_id: "flint".to_string() } } #[test] fn allowed_tool_passes_gate() { let config = default_config(); let session = Session::new(); let params = ToolParams::default(); let decision = process("spf_status", ¶ms, &config, &session, &stdio()); assert!(decision.allowed, "spf_status should be allowed: {}", decision.message); } #[test] fn blocked_fs_tool_denied() { let config = default_config(); let session = Session::new(); let params = ToolParams::default(); let decision = process("spf_fs_write", ¶ms, &config, &session, &stdio()); assert!(!decision.allowed, "spf_fs_write should be BLOCKED"); assert!(decision.errors.iter().any(|e| e.contains("BLOCKED"))); } #[test] fn unknown_tool_denied_default_deny() { let config = default_config(); let session = Session::new(); let params = ToolParams::default(); let decision = process("evil_new_tool", ¶ms, &config, &session, &stdio()); assert!(!decision.allowed, "Unknown tool should be blocked by default-deny"); assert!(decision.errors.iter().any(|e| e.contains("not in gate allowlist"))); } #[test] fn all_fs_tools_blocked() { let config = default_config(); let session = Session::new(); let params = ToolParams::default(); let fs_tools = [ "spf_fs_exists", "spf_fs_stat", "spf_fs_ls", "spf_fs_read", "spf_fs_write", "spf_fs_mkdir", "spf_fs_rm", "spf_fs_rename", ]; for tool in &fs_tools { let decision = process(tool, ¶ms, &config, &session, &stdio()); assert!(!decision.allowed, "{} should be BLOCKED", tool); } } #[test] fn mesh_read_tools_allowed_through_gate() { let config = default_config(); let session = Session::new(); let params = ToolParams::default(); for tool in &["spf_mesh_status", "spf_mesh_peers"] { let decision = process(tool, ¶ms, &config, &session, &stdio()); assert!(decision.allowed, "{} should be ALLOWED: {}", tool, decision.message); } } #[test] fn mesh_call_blocked_without_peer_key() { let config = default_config(); let session = Session::new(); let params = ToolParams::default(); // peer_key = None let decision = process("spf_mesh_call", ¶ms, &config, &session, &stdio()); assert!(!decision.allowed, "spf_mesh_call with no peer_key must be BLOCKED"); assert!(decision.errors.iter().any(|e| e.contains("MESH"))); } #[test] fn mesh_call_allowed_with_valid_peer_key() { let config = default_config(); let session = Session::new(); let params = ToolParams { peer_key: Some("4c327f6d8dfa032873dcf4355b44ae412174f880e720d5bd0b2babbf0dbc33f3".to_string()), command: Some("spf_brain_search".to_string()), ..Default::default() }; let decision = process("spf_mesh_call", ¶ms, &config, &session, &stdio()); assert!(decision.allowed, "spf_mesh_call with valid peer_key+tool must be ALLOWED: {}", decision.message); } #[test] fn voice_chat_tools_allowed_through_gate() { let config = default_config(); let session = Session::new(); let params = ToolParams::default(); let tools = [ "spf_voice_mode", "spf_voice_call", "spf_voice_team", "spf_chat_send", "spf_chat_receive", "spf_chat_history", "spf_chat_rooms", ]; for tool in &tools { let decision = process(tool, ¶ms, &config, &session, &stdio()); assert!(decision.allowed, "{} should be ALLOWED: {}", tool, decision.message); } } #[test] fn flint_execute_blocked_without_tool_name() { let config = default_config(); let session = Session::new(); let params = ToolParams::default(); // tool_name = None let decision = process("spf_flint_execute", ¶ms, &config, &session, &stdio()); assert!(!decision.allowed, "flint_execute with no tool_name must be BLOCKED"); assert!(decision.errors.iter().any(|e| e.contains("FLINT"))); } #[test] fn flint_execute_allowed_with_valid_params() { let config = default_config(); let session = Session::new(); let params = ToolParams { tool_name: Some("spf_brain_search".to_string()), reason: Some("Searching for relevant project context".to_string()), ..Default::default() }; let decision = process("spf_flint_execute", ¶ms, &config, &session, &stdio()); assert!(decision.allowed, "flint_execute with valid tool_name+reason must be ALLOWED: {}", decision.message); } #[test] fn flint_execute_allowed_for_write_delegation() { let config = default_config(); let session = Session::new(); let params = ToolParams { tool_name: Some("spf_write".to_string()), reason: Some("Writing a file via FLINT".to_string()), ..Default::default() }; let decision = process("spf_flint_execute", ¶ms, &config, &session, &stdio()); assert!(decision.allowed, "flint_execute should delegate to spf_write: {}", decision.message); } #[test] fn transformer_has_same_permissions_as_stdio() { let config = default_config(); let session = Session::new(); let params = ToolParams::default(); // FLINT gets identical gate treatment to Stdio — no source-based blocking. // Both still subject to path validation, rate limiting, etc. let read_tools = ["spf_status", "spf_brain_search", "spf_mesh_status"]; for tool in &read_tools { let stdio_decision = process(tool, ¶ms, &config, &session, &stdio()); let flint_decision = process(tool, ¶ms, &config, &session, &transformer()); assert_eq!(stdio_decision.allowed, flint_decision.allowed, "FLINT and Stdio should have same result for {}", tool); } } #[test] fn transformer_can_read() { let config = default_config(); let session = Session::new(); let params = ToolParams::default(); let decision = process("spf_status", ¶ms, &config, &session, &transformer()); assert!(decision.allowed, "Transformer should be able to call spf_status"); } }