File size: 22,634 Bytes
1269259 8e0fe4e 1269259 8e0fe4e 1269259 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 | // 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<String>,
pub errors: Vec<String>,
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");
}
}
|