From f529a36149d0a30d7c27ef153f9d50f4081d904a Mon Sep 17 00:00:00 2001 From: Jay Ehsaniara Date: Mon, 6 Apr 2026 10:14:25 -0700 Subject: [PATCH] feat: add interactive content keyword approval with whitelist/blacklist - Adds deny_content_keywords policy that scans request bodies for sensitive terms and prompts users to allow or block before forwarding to LLMs. - Users can permanently whitelist or blacklist files to avoid repeated prompts. Includes desktop UI modal and headless fallback. --- README.md | 23 +- cmd/egressor/main.go | 7 + config.yaml | 5 + docs/design.md | 20 +- internal/config/config.go | 7 +- internal/policy/policy.go | 171 +++++++++++++++ internal/policy/policy_test.go | 148 +++++++++++++ internal/policy/prompt.go | 43 ++++ internal/proxy/intercept.go | 79 ++++++- internal/ui/app.go | 125 ++++++++++- internal/ui/frontend/src/App.tsx | 22 +- .../src/components/ContentPromptModal.tsx | 95 +++++++++ .../frontend/src/components/PolicyEditor.tsx | 199 +++++++++++------- .../frontend/src/hooks/useContentPrompts.ts | 32 +++ internal/ui/frontend/src/hooks/usePolicy.ts | 54 ++++- internal/ui/frontend/src/types.ts | 10 + internal/ui/frontend/wailsjs/go/ui/App.ts | 42 ++++ 17 files changed, 980 insertions(+), 102 deletions(-) create mode 100644 internal/policy/prompt.go create mode 100644 internal/ui/frontend/src/components/ContentPromptModal.tsx create mode 100644 internal/ui/frontend/src/hooks/useContentPrompts.ts diff --git a/README.md b/README.md index f22129a..d9966d7 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,11 @@ policy: - "**/credentials*" - ".aws/*" + # Keywords that trigger interactive approval + deny_content_keywords: + - "CONFIDENTIAL" + - "INTERNAL ONLY" + logging: format: json file: ~/.egressor/logs/audit.log @@ -155,6 +160,17 @@ Glob patterns that block requests containing matching file references: When a request body contains a file matching a deny pattern, Egressor returns `403` to the client and logs the blocked request — the payload never reaches the LLM. +### Content keywords (interactive approval) + +When `deny_content_keywords` is set, request bodies are scanned for these keywords (case-insensitive). If a match is found, Egressor pauses the request and prompts the user in the desktop UI with four options: + +- **Allow Once** — forward this request, don't remember +- **Allow Always** — forward and add the file to the whitelist (never ask again) +- **Block Once** — return 403, don't remember +- **Block Always** — return 403 and add the file to the blacklist (auto-block in future) + +The whitelist and blacklist are persisted to `config.yaml` via "Save to config". In headless mode, keyword matches are blocked by default (no UI to prompt). + --- ## Desktop UI @@ -163,7 +179,7 @@ The default mode opens a native desktop window (built with Wails + React): - **Sessions tab** — live table of intercepted connections with method, host, status, file count - **Detail panel** — click a session to see full request/response headers, body (JSON-formatted), and detected files -- **Policy tab** — manage allowed directories and deny file patterns, save to config +- **Policy tab** — manage allowed directories, deny file patterns, content keywords, whitelist/blacklist - **Bottom bar** — proxy start/stop, pause/resume policy, session stats Blocked requests are highlighted in red with the matching deny pattern shown. @@ -186,8 +202,9 @@ Client ──TLS(egressor cert)──► Egressor ──TLS(real cert)──► 6. Extracts file references from the JSON payload 7. Checks file paths against `allowed_directories` — blocks if out of scope 8. Checks file paths against `deny_file_patterns` — blocks if matched -9. If blocked: returns `403`, logs the attempt, never forwards to the server -10. If allowed: forwards the request, captures the response, logs everything +9. Scans body for `deny_content_keywords` — prompts user if matched (whitelist/blacklist checked first) +10. If blocked: returns `403`, logs the attempt, never forwards to the server +11. If allowed: forwards the request, captures the response, logs everything ### File detection diff --git a/cmd/egressor/main.go b/cmd/egressor/main.go index 215653b..e0857dc 100644 --- a/cmd/egressor/main.go +++ b/cmd/egressor/main.go @@ -86,6 +86,7 @@ func main() { slog.Info("TLS interception enabled") if *headless { + interceptor.SetResolver(policy.HeadlessResolver{}) server := proxy.NewServer(cfg.ListenAddress, logger, interceptor) runHeadless(server, cfg) return @@ -96,6 +97,7 @@ func main() { sink := audit.NewMultiSink(logger, store) server := proxy.NewServer(cfg.ListenAddress, sink, interceptor) app := ui.NewApp(server, store, engine, cfg, resolvedConfig) + interceptor.SetResolver(app) slog.Info("egressor starting", "address", cfg.ListenAddress, "mode", "ui") if err := ui.RunUI(app); err != nil { @@ -125,6 +127,11 @@ policy: - "**/credentials*" - ".aws/*" + # Keywords that trigger interactive approval before sending to LLM. + # deny_content_keywords: + # - "CONFIDENTIAL" + # - "INTERNAL ONLY" + logging: format: json file: ~/.egressor/logs/audit.log diff --git a/config.yaml b/config.yaml index 0ab0b9b..fa60c5f 100644 --- a/config.yaml +++ b/config.yaml @@ -14,6 +14,11 @@ policy: - "**/credentials*" - ".aws/*" + # Keywords that trigger interactive approval before sending to LLM. + deny_content_keywords: + - "CONFIDENTIAL" + - "INTERNAL ONLY" + logging: format: json file: ~/.egressor/logs/audit.log diff --git a/docs/design.md b/docs/design.md index b5f7644..b8643b1 100644 --- a/docs/design.md +++ b/docs/design.md @@ -29,8 +29,13 @@ Egressor is a local HTTPS intercepting proxy that monitors and controls outbound │ ├──▶ Check allowed_directories │ │ │ └─ OUT OF SCOPE → 403 │ │ ├──▶ Check deny_file_patterns │ -│ │ ├─ BLOCKED → 403 to client │ -│ │ └─ ALLOWED → forward upstream │ +│ │ └─ BLOCKED → 403 to client │ +│ ├──▶ Check deny_content_keywords │ +│ │ ├─ WHITELIST → auto-allow │ +│ │ ├─ BLACKLIST → auto-block 403 │ +│ │ └─ PROMPT USER → allow/block │ +│ │ │ +│ └──▶ ALLOWED → forward upstream │ │ │ │ │ ▼ │ │ ┌──────────┐ ┌───────────────┐ │ @@ -72,6 +77,7 @@ For each connection: - Extract file references from the body - Evaluate file paths against `allowed_directories` — block if out of scope - Evaluate file paths against `deny_file_patterns` — block if matched + - Scan body for `deny_content_keywords` — check whitelist/blacklist, prompt user if needed - If blocked: send 403 back to client, log, stop - If allowed: forward request to upstream, relay response back 4. Record exchange in session @@ -103,7 +109,15 @@ Two-layer policy enforcement: - Pattern matching: `filepath.Match` for globs, `**/` prefix for recursive matching, basename fallback - Runtime mutation: `GetDenyPatterns()`, `SetDenyPatterns()`, `AddDenyPattern()`, `RemoveDenyPattern()` -Both layers: +**Content keyword approval** — `EvaluateContentKeywords(body string, filePaths []string) ContentKeywordResult`: +- Case-insensitive substring scan of body against `deny_content_keywords` +- Partitions files into whitelist-allowed, blacklist-blocked, and needs-prompt +- Interactive: pauses request, emits `content:prompt` event, waits for user decision (30s timeout) +- User choices: Allow Once, Allow Always (whitelist), Block Once, Block Always (blacklist) +- `PromptResolver` interface: `App` implements for UI mode, `HeadlessResolver` blocks by default +- Whitelist/blacklist persisted to config via SaveConfig + +All layers: - Pause/bypass via atomic bool (for UI toggle) - Thread-safe with `sync.RWMutex` diff --git a/internal/config/config.go b/internal/config/config.go index d6a5f3c..8350638 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -24,8 +24,11 @@ type InterceptConfig struct { } type PolicyConfig struct { - DenyFilePatterns []string `yaml:"deny_file_patterns"` - AllowedDirectories []string `yaml:"allowed_directories"` + DenyFilePatterns []string `yaml:"deny_file_patterns"` + AllowedDirectories []string `yaml:"allowed_directories"` + DenyContentKeywords []string `yaml:"deny_content_keywords"` + ContentKeywordWhitelist []string `yaml:"content_keyword_whitelist"` + ContentKeywordBlacklist []string `yaml:"content_keyword_blacklist"` } type LogConfig struct { diff --git a/internal/policy/policy.go b/internal/policy/policy.go index c665cae..c1bc56b 100644 --- a/internal/policy/policy.go +++ b/internal/policy/policy.go @@ -156,6 +156,177 @@ func resolvePath(p string) string { return p } +// --- Content keyword methods --- + +// GetDenyContentKeywords returns the current deny content keywords. +func (e *Engine) GetDenyContentKeywords() []string { + e.mu.RLock() + defer e.mu.RUnlock() + out := make([]string, len(e.cfg.DenyContentKeywords)) + copy(out, e.cfg.DenyContentKeywords) + return out +} + +// SetDenyContentKeywords replaces all deny content keywords. +func (e *Engine) SetDenyContentKeywords(keywords []string) { + e.mu.Lock() + defer e.mu.Unlock() + e.cfg.DenyContentKeywords = make([]string, len(keywords)) + copy(e.cfg.DenyContentKeywords, keywords) +} + +// AddDenyContentKeyword appends a single deny content keyword. +func (e *Engine) AddDenyContentKeyword(keyword string) { + e.mu.Lock() + defer e.mu.Unlock() + e.cfg.DenyContentKeywords = append(e.cfg.DenyContentKeywords, keyword) +} + +// RemoveDenyContentKeyword removes a single deny content keyword. +func (e *Engine) RemoveDenyContentKeyword(keyword string) { + e.mu.Lock() + defer e.mu.Unlock() + filtered := e.cfg.DenyContentKeywords[:0] + for _, k := range e.cfg.DenyContentKeywords { + if k != keyword { + filtered = append(filtered, k) + } + } + e.cfg.DenyContentKeywords = filtered +} + +// GetContentKeywordWhitelist returns file paths that bypass content keyword checks. +func (e *Engine) GetContentKeywordWhitelist() []string { + e.mu.RLock() + defer e.mu.RUnlock() + out := make([]string, len(e.cfg.ContentKeywordWhitelist)) + copy(out, e.cfg.ContentKeywordWhitelist) + return out +} + +// AddToContentKeywordWhitelist adds a file path to the content keyword whitelist. +func (e *Engine) AddToContentKeywordWhitelist(path string) { + e.mu.Lock() + defer e.mu.Unlock() + for _, p := range e.cfg.ContentKeywordWhitelist { + if p == path { + return + } + } + e.cfg.ContentKeywordWhitelist = append(e.cfg.ContentKeywordWhitelist, path) +} + +// RemoveFromContentKeywordWhitelist removes a file path from the whitelist. +func (e *Engine) RemoveFromContentKeywordWhitelist(path string) { + e.mu.Lock() + defer e.mu.Unlock() + filtered := e.cfg.ContentKeywordWhitelist[:0] + for _, p := range e.cfg.ContentKeywordWhitelist { + if p != path { + filtered = append(filtered, p) + } + } + e.cfg.ContentKeywordWhitelist = filtered +} + +// GetContentKeywordBlacklist returns file paths that are always blocked by content keyword checks. +func (e *Engine) GetContentKeywordBlacklist() []string { + e.mu.RLock() + defer e.mu.RUnlock() + out := make([]string, len(e.cfg.ContentKeywordBlacklist)) + copy(out, e.cfg.ContentKeywordBlacklist) + return out +} + +// AddToContentKeywordBlacklist adds a file path to the content keyword blacklist. +func (e *Engine) AddToContentKeywordBlacklist(path string) { + e.mu.Lock() + defer e.mu.Unlock() + for _, p := range e.cfg.ContentKeywordBlacklist { + if p == path { + return + } + } + e.cfg.ContentKeywordBlacklist = append(e.cfg.ContentKeywordBlacklist, path) +} + +// RemoveFromContentKeywordBlacklist removes a file path from the blacklist. +func (e *Engine) RemoveFromContentKeywordBlacklist(path string) { + e.mu.Lock() + defer e.mu.Unlock() + filtered := e.cfg.ContentKeywordBlacklist[:0] + for _, p := range e.cfg.ContentKeywordBlacklist { + if p != path { + filtered = append(filtered, p) + } + } + e.cfg.ContentKeywordBlacklist = filtered +} + +// ContentKeywordResult holds the outcome of a content keyword evaluation. +type ContentKeywordResult struct { + HasMatch bool + MatchedKeyword string + AutoAllowed []string // file paths resolved by whitelist + AutoBlocked []string // file paths resolved by blacklist + NeedPrompt []string // file paths needing user decision +} + +// EvaluateContentKeywords scans the body for deny_content_keywords and partitions +// detected file paths into whitelist-allowed, blacklist-blocked, and needs-prompt. +func (e *Engine) EvaluateContentKeywords(body string, filePaths []string) ContentKeywordResult { + if e.bypassed.Load() { + return ContentKeywordResult{} + } + + e.mu.RLock() + keywords := make([]string, len(e.cfg.DenyContentKeywords)) + copy(keywords, e.cfg.DenyContentKeywords) + whitelist := make(map[string]bool, len(e.cfg.ContentKeywordWhitelist)) + for _, p := range e.cfg.ContentKeywordWhitelist { + whitelist[p] = true + } + blacklist := make(map[string]bool, len(e.cfg.ContentKeywordBlacklist)) + for _, p := range e.cfg.ContentKeywordBlacklist { + blacklist[p] = true + } + e.mu.RUnlock() + + if len(keywords) == 0 { + return ContentKeywordResult{} + } + + // Case-insensitive keyword scan + bodyLower := strings.ToLower(body) + var matchedKeyword string + for _, kw := range keywords { + if strings.Contains(bodyLower, strings.ToLower(kw)) { + matchedKeyword = kw + break + } + } + if matchedKeyword == "" { + return ContentKeywordResult{} + } + + // Partition file paths by whitelist/blacklist + result := ContentKeywordResult{ + HasMatch: true, + MatchedKeyword: matchedKeyword, + } + for _, fp := range filePaths { + switch { + case whitelist[fp]: + result.AutoAllowed = append(result.AutoAllowed, fp) + case blacklist[fp]: + result.AutoBlocked = append(result.AutoBlocked, fp) + default: + result.NeedPrompt = append(result.NeedPrompt, fp) + } + } + return result +} + // EvaluateFiles checks if any detected file paths match deny_file_patterns. func (e *Engine) EvaluateFiles(paths []string) Decision { if e.bypassed.Load() { diff --git a/internal/policy/policy_test.go b/internal/policy/policy_test.go index 923a973..91faeb7 100644 --- a/internal/policy/policy_test.go +++ b/internal/policy/policy_test.go @@ -157,6 +157,154 @@ func TestEvaluateScope_ParentTraversal(t *testing.T) { } } +func TestEvaluateContentKeywords_Match(t *testing.T) { + engine := NewEngine(config.PolicyConfig{ + DenyContentKeywords: []string{"CONFIDENTIAL", "INTERNAL ONLY"}, + }) + + result := engine.EvaluateContentKeywords("This document is CONFIDENTIAL and should not be shared", []string{"doc.txt"}) + if !result.HasMatch { + t.Fatal("expected match") + } + if result.MatchedKeyword != "CONFIDENTIAL" { + t.Errorf("expected keyword CONFIDENTIAL, got %q", result.MatchedKeyword) + } + if len(result.NeedPrompt) != 1 || result.NeedPrompt[0] != "doc.txt" { + t.Errorf("expected doc.txt in NeedPrompt, got %v", result.NeedPrompt) + } +} + +func TestEvaluateContentKeywords_CaseInsensitive(t *testing.T) { + engine := NewEngine(config.PolicyConfig{ + DenyContentKeywords: []string{"confidential"}, + }) + + result := engine.EvaluateContentKeywords("This is CONFIDENTIAL data", []string{"file.go"}) + if !result.HasMatch { + t.Error("expected case-insensitive match") + } +} + +func TestEvaluateContentKeywords_NoMatch(t *testing.T) { + engine := NewEngine(config.PolicyConfig{ + DenyContentKeywords: []string{"CONFIDENTIAL"}, + }) + + result := engine.EvaluateContentKeywords("This is a normal document", []string{"file.go"}) + if result.HasMatch { + t.Error("expected no match") + } +} + +func TestEvaluateContentKeywords_NoKeywords(t *testing.T) { + engine := NewEngine(config.PolicyConfig{}) + + result := engine.EvaluateContentKeywords("CONFIDENTIAL data", []string{"file.go"}) + if result.HasMatch { + t.Error("expected no match when no keywords configured") + } +} + +func TestEvaluateContentKeywords_Bypassed(t *testing.T) { + engine := NewEngine(config.PolicyConfig{ + DenyContentKeywords: []string{"CONFIDENTIAL"}, + }) + engine.SetBypassed(true) + + result := engine.EvaluateContentKeywords("CONFIDENTIAL data", []string{"file.go"}) + if result.HasMatch { + t.Error("expected no match when policy bypassed") + } +} + +func TestEvaluateContentKeywords_WhitelistBypass(t *testing.T) { + engine := NewEngine(config.PolicyConfig{ + DenyContentKeywords: []string{"CONFIDENTIAL"}, + ContentKeywordWhitelist: []string{"trusted.go"}, + }) + + result := engine.EvaluateContentKeywords("CONFIDENTIAL data", []string{"trusted.go", "untrusted.go"}) + if !result.HasMatch { + t.Fatal("expected match") + } + if len(result.AutoAllowed) != 1 || result.AutoAllowed[0] != "trusted.go" { + t.Errorf("expected trusted.go in AutoAllowed, got %v", result.AutoAllowed) + } + if len(result.NeedPrompt) != 1 || result.NeedPrompt[0] != "untrusted.go" { + t.Errorf("expected untrusted.go in NeedPrompt, got %v", result.NeedPrompt) + } +} + +func TestEvaluateContentKeywords_BlacklistBlock(t *testing.T) { + engine := NewEngine(config.PolicyConfig{ + DenyContentKeywords: []string{"CONFIDENTIAL"}, + ContentKeywordBlacklist: []string{"blocked.go"}, + }) + + result := engine.EvaluateContentKeywords("CONFIDENTIAL data", []string{"blocked.go", "other.go"}) + if !result.HasMatch { + t.Fatal("expected match") + } + if len(result.AutoBlocked) != 1 || result.AutoBlocked[0] != "blocked.go" { + t.Errorf("expected blocked.go in AutoBlocked, got %v", result.AutoBlocked) + } + if len(result.NeedPrompt) != 1 || result.NeedPrompt[0] != "other.go" { + t.Errorf("expected other.go in NeedPrompt, got %v", result.NeedPrompt) + } +} + +func TestEvaluateContentKeywords_AllWhitelisted(t *testing.T) { + engine := NewEngine(config.PolicyConfig{ + DenyContentKeywords: []string{"CONFIDENTIAL"}, + ContentKeywordWhitelist: []string{"a.go", "b.go"}, + }) + + result := engine.EvaluateContentKeywords("CONFIDENTIAL data", []string{"a.go", "b.go"}) + if !result.HasMatch { + t.Fatal("expected match") + } + if len(result.NeedPrompt) != 0 { + t.Errorf("expected empty NeedPrompt when all whitelisted, got %v", result.NeedPrompt) + } + if len(result.AutoAllowed) != 2 { + t.Errorf("expected 2 AutoAllowed, got %v", result.AutoAllowed) + } +} + +func TestContentKeywordWhitelistCRUD(t *testing.T) { + engine := NewEngine(config.PolicyConfig{}) + + engine.AddToContentKeywordWhitelist("file.go") + engine.AddToContentKeywordWhitelist("file.go") // duplicate + wl := engine.GetContentKeywordWhitelist() + if len(wl) != 1 { + t.Fatalf("expected 1 entry, got %d", len(wl)) + } + + engine.RemoveFromContentKeywordWhitelist("file.go") + wl = engine.GetContentKeywordWhitelist() + if len(wl) != 0 { + t.Fatalf("expected 0 entries, got %d", len(wl)) + } +} + +func TestContentKeywordBlacklistCRUD(t *testing.T) { + engine := NewEngine(config.PolicyConfig{}) + + engine.AddToContentKeywordBlacklist("file.go") + engine.AddToContentKeywordBlacklist("file.go") // duplicate + bl := engine.GetContentKeywordBlacklist() + if len(bl) != 1 { + t.Fatalf("expected 1 entry, got %d", len(bl)) + } + + engine.RemoveFromContentKeywordBlacklist("file.go") + bl = engine.GetContentKeywordBlacklist() + if len(bl) != 0 { + t.Fatalf("expected 0 entries, got %d", len(bl)) + } +} + func TestMatchFilePattern(t *testing.T) { tests := []struct { path string diff --git a/internal/policy/prompt.go b/internal/policy/prompt.go new file mode 100644 index 0000000..0db907a --- /dev/null +++ b/internal/policy/prompt.go @@ -0,0 +1,43 @@ +package policy + +import "log/slog" + +// PromptAction represents the user's decision on a content keyword prompt. +type PromptAction string + +const ( + PromptAllowOnce PromptAction = "allow_once" + PromptAllowAlways PromptAction = "allow_always" + PromptBlockOnce PromptAction = "block_once" + PromptBlockAlways PromptAction = "block_always" +) + +// ContentPrompt is sent to the UI when a content keyword match requires user input. +type ContentPrompt struct { + ID string `json:"id"` + SessionID string `json:"session_id"` + URL string `json:"url"` + MatchedKeyword string `json:"matched_keyword"` + FilePaths []string `json:"file_paths"` +} + +// ContentPromptResponse is the user's decision from the UI. +type ContentPromptResponse struct { + Action PromptAction `json:"action"` +} + +// PromptResolver pauses a request and waits for user input. +type PromptResolver interface { + PromptUser(prompt ContentPrompt) ContentPromptResponse +} + +// HeadlessResolver blocks all content keyword matches without prompting. +type HeadlessResolver struct{} + +func (h HeadlessResolver) PromptUser(prompt ContentPrompt) ContentPromptResponse { + slog.Warn("content keyword match in headless mode, blocking", + "keyword", prompt.MatchedKeyword, + "files", prompt.FilePaths, + ) + return ContentPromptResponse{Action: PromptBlockOnce} +} diff --git a/internal/proxy/intercept.go b/internal/proxy/intercept.go index 694ed6a..60d5a72 100644 --- a/internal/proxy/intercept.go +++ b/internal/proxy/intercept.go @@ -24,18 +24,24 @@ type Interceptor struct { logBody bool maxBody int policy *policy.Engine + resolver policy.PromptResolver } // NewInterceptor creates an interceptor backed by the given CA authority. -func NewInterceptor(authority *ca.Authority, logBody bool, maxBody int, policy *policy.Engine) *Interceptor { +func NewInterceptor(authority *ca.Authority, logBody bool, maxBody int, pol *policy.Engine) *Interceptor { return &Interceptor{ certCache: ca.NewCertCache(authority), logBody: logBody, maxBody: maxBody, - policy: policy, + policy: pol, } } +// SetResolver sets the prompt resolver for interactive content keyword approval. +func (i *Interceptor) SetResolver(r policy.PromptResolver) { + i.resolver = r +} + // Intercept performs TLS MITM on an established CONNECT tunnel. // clientConn has already received "200 Connection Established". // upstreamConn is a raw TCP connection to the target server. @@ -162,6 +168,75 @@ func (i *Interceptor) Intercept(clientConn net.Conn, upstreamConn net.Conn, host sess.Exchanges = append(sess.Exchanges, exchange) return nil } + + // Check content keywords — interactive approval + kwResult := i.policy.EvaluateContentKeywords(bodyStr, paths) + if kwResult.HasMatch { + // Auto-blocked files from blacklist + if len(kwResult.AutoBlocked) > 0 { + reason := fmt.Sprintf("file %q is blacklisted (keyword %q)", kwResult.AutoBlocked[0], kwResult.MatchedKeyword) + slog.Warn("request blocked by content keyword blacklist", + "session", sess.ID, + "url", exchange.URL, + "reason", reason, + ) + exchange.StatusCode = 403 + exchange.Blocked = true + exchange.BlockReason = reason + if i.logBody { + exchange.RequestBody = truncateBody(bodyStr, i.maxBody) + } + resp403 := &http.Response{ + StatusCode: 403, + ProtoMajor: 1, + ProtoMinor: 1, + Header: http.Header{"Content-Type": {"text/plain"}}, + Body: io.NopCloser(strings.NewReader("blocked by egressor: " + reason)), + } + resp403.Write(clientTLS) + sess.Exchanges = append(sess.Exchanges, exchange) + return nil + } + + // Files needing user prompt + if len(kwResult.NeedPrompt) > 0 && i.resolver != nil { + promptID := fmt.Sprintf("%s-%d", sess.ID, time.Now().UnixNano()) + prompt := policy.ContentPrompt{ + ID: promptID, + SessionID: sess.ID, + URL: exchange.URL, + MatchedKeyword: kwResult.MatchedKeyword, + FilePaths: kwResult.NeedPrompt, + } + slog.Info("content keyword match, prompting user", + "session", sess.ID, + "keyword", kwResult.MatchedKeyword, + "files", kwResult.NeedPrompt, + ) + resp := i.resolver.PromptUser(prompt) + switch resp.Action { + case policy.PromptBlockOnce, policy.PromptBlockAlways: + reason := fmt.Sprintf("user blocked: keyword %q in files %v", kwResult.MatchedKeyword, kwResult.NeedPrompt) + exchange.StatusCode = 403 + exchange.Blocked = true + exchange.BlockReason = reason + if i.logBody { + exchange.RequestBody = truncateBody(bodyStr, i.maxBody) + } + resp403 := &http.Response{ + StatusCode: 403, + ProtoMajor: 1, + ProtoMinor: 1, + Header: http.Header{"Content-Type": {"text/plain"}}, + Body: io.NopCloser(strings.NewReader("blocked by egressor: " + reason)), + } + resp403.Write(clientTLS) + sess.Exchanges = append(sess.Exchanges, exchange) + return nil + } + // allow_once or allow_always — continue forwarding + } + } } if i.logBody { diff --git a/internal/ui/app.go b/internal/ui/app.go index f31ad45..93fbd97 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -3,6 +3,8 @@ package ui import ( "context" "log/slog" + "sync" + "time" "github.com/ehsaniara/egressor/internal/audit" "github.com/ehsaniara/egressor/internal/config" @@ -20,15 +22,19 @@ type App struct { engine *policy.Engine cfg *config.Config cfgPath string + + pendingMu sync.Mutex + pendingPrompts map[string]chan policy.ContentPromptResponse } func NewApp(server *proxy.Server, store *audit.SessionStore, engine *policy.Engine, cfg *config.Config, cfgPath string) *App { return &App{ - server: server, - store: store, - engine: engine, - cfg: cfg, - cfgPath: cfgPath, + server: server, + store: store, + engine: engine, + cfg: cfg, + cfgPath: cfgPath, + pendingPrompts: make(map[string]chan policy.ContentPromptResponse), } } @@ -66,7 +72,7 @@ func (a *App) GetStats() audit.StoreStats { return a.store.Stats() } -// --- Policy management --- +// --- Policy management: deny patterns --- func (a *App) GetDenyPatterns() []string { return a.engine.GetDenyPatterns() @@ -84,6 +90,8 @@ func (a *App) RemoveDenyPattern(pattern string) { a.engine.RemoveDenyPattern(pattern) } +// --- Policy management: allowed directories --- + func (a *App) GetAllowedDirectories() []string { return a.engine.GetAllowedDirectories() } @@ -109,6 +117,42 @@ func (a *App) RemoveAllowedDirectory(dir string) { a.engine.SetAllowedDirectories(filtered) } +// --- Policy management: content keywords --- + +func (a *App) GetDenyContentKeywords() []string { + return a.engine.GetDenyContentKeywords() +} + +func (a *App) SetDenyContentKeywords(keywords []string) { + a.engine.SetDenyContentKeywords(keywords) +} + +func (a *App) AddDenyContentKeyword(keyword string) { + a.engine.AddDenyContentKeyword(keyword) +} + +func (a *App) RemoveDenyContentKeyword(keyword string) { + a.engine.RemoveDenyContentKeyword(keyword) +} + +func (a *App) GetContentKeywordWhitelist() []string { + return a.engine.GetContentKeywordWhitelist() +} + +func (a *App) RemoveFromContentKeywordWhitelist(path string) { + a.engine.RemoveFromContentKeywordWhitelist(path) +} + +func (a *App) GetContentKeywordBlacklist() []string { + return a.engine.GetContentKeywordBlacklist() +} + +func (a *App) RemoveFromContentKeywordBlacklist(path string) { + a.engine.RemoveFromContentKeywordBlacklist(path) +} + +// --- Policy bypass --- + func (a *App) IsPolicyBypassed() bool { return a.engine.IsBypassed() } @@ -122,9 +166,78 @@ func (a *App) SetPolicyBypassed(bypassed bool) { } } +// --- Content keyword prompt resolution --- + +// PromptUser implements policy.PromptResolver. It emits a Wails event and blocks +// until the frontend calls ResolveContentPrompt or the 30s timeout expires. +func (a *App) PromptUser(prompt policy.ContentPrompt) policy.ContentPromptResponse { + ch := make(chan policy.ContentPromptResponse, 1) + + a.pendingMu.Lock() + a.pendingPrompts[prompt.ID] = ch + a.pendingMu.Unlock() + + wailsRuntime.EventsEmit(a.ctx, "content:prompt", prompt) + + select { + case resp := <-ch: + return resp + case <-time.After(30 * time.Second): + a.pendingMu.Lock() + delete(a.pendingPrompts, prompt.ID) + a.pendingMu.Unlock() + slog.Warn("content prompt timed out, blocking", + "prompt_id", prompt.ID, + "keyword", prompt.MatchedKeyword, + ) + return policy.ContentPromptResponse{Action: policy.PromptBlockOnce} + } +} + +// ResolveContentPrompt is called by the frontend to respond to a content keyword prompt. +func (a *App) ResolveContentPrompt(promptID string, action string) { + a.pendingMu.Lock() + ch, ok := a.pendingPrompts[promptID] + if ok { + delete(a.pendingPrompts, promptID) + } + a.pendingMu.Unlock() + + if !ok { + return + } + + promptAction := policy.PromptAction(action) + + // Handle persistent decisions + // For allow_always/block_always, we apply to all files from the original prompt. + // The interceptor already has the file paths; the whitelist/blacklist stores them. + // We retrieve pending prompt info from the channel interaction. + + ch <- policy.ContentPromptResponse{Action: promptAction} +} + +// ResolveContentPromptForFile is called by the frontend with a specific file path +// for whitelist/blacklist persistence, separate from the blocking resolution. +func (a *App) ResolveContentPromptForFile(action string, filePath string) { + switch policy.PromptAction(action) { + case policy.PromptAllowAlways: + a.engine.AddToContentKeywordWhitelist(filePath) + slog.Info("file added to content keyword whitelist", "path", filePath) + case policy.PromptBlockAlways: + a.engine.AddToContentKeywordBlacklist(filePath) + slog.Info("file added to content keyword blacklist", "path", filePath) + } +} + +// --- Config persistence --- + func (a *App) SaveConfig() error { a.cfg.Policy.DenyFilePatterns = a.engine.GetDenyPatterns() a.cfg.Policy.AllowedDirectories = a.engine.GetAllowedDirectories() + a.cfg.Policy.DenyContentKeywords = a.engine.GetDenyContentKeywords() + a.cfg.Policy.ContentKeywordWhitelist = a.engine.GetContentKeywordWhitelist() + a.cfg.Policy.ContentKeywordBlacklist = a.engine.GetContentKeywordBlacklist() return config.Save(a.cfgPath, a.cfg) } diff --git a/internal/ui/frontend/src/App.tsx b/internal/ui/frontend/src/App.tsx index 6e05e8d..32c8954 100644 --- a/internal/ui/frontend/src/App.tsx +++ b/internal/ui/frontend/src/App.tsx @@ -1,16 +1,19 @@ import { useState } from 'react'; import { useSessions } from './hooks/useSessions'; import { usePolicy } from './hooks/usePolicy'; +import { useContentPrompts } from './hooks/useContentPrompts'; import { SessionTable } from './components/SessionTable'; import { SessionDetail } from './components/SessionDetail'; import { ProxyControls } from './components/ProxyControls'; import { PolicyEditor } from './components/PolicyEditor'; +import { ContentPromptModal } from './components/ContentPromptModal'; type Tab = 'sessions' | 'policy'; function App() { const { sessions, stats } = useSessions(); const policy = usePolicy(); + const { current: currentPrompt, resolve: resolvePrompt } = useContentPrompts(); const [selectedId, setSelectedId] = useState(null); const [activeTab, setActiveTab] = useState('sessions'); @@ -72,7 +75,7 @@ function App() { )} ) : ( -
+
@@ -92,8 +102,16 @@ function App() { bypassed={policy.bypassed} onToggleBypassed={policy.toggleBypassed} /> + + {/* Content keyword prompt modal */} + {currentPrompt && ( + + )}
); } -export default App; +export default App; \ No newline at end of file diff --git a/internal/ui/frontend/src/components/ContentPromptModal.tsx b/internal/ui/frontend/src/components/ContentPromptModal.tsx new file mode 100644 index 0000000..5c57ad7 --- /dev/null +++ b/internal/ui/frontend/src/components/ContentPromptModal.tsx @@ -0,0 +1,95 @@ +import { useState, useEffect } from 'react'; +import type { ContentPrompt, PromptAction } from '../types'; + +interface Props { + prompt: ContentPrompt; + onResolve: (promptId: string, action: PromptAction, filePaths: string[]) => void; +} + +export function ContentPromptModal({ prompt, onResolve }: Props) { + const [countdown, setCountdown] = useState(30); + + useEffect(() => { + setCountdown(30); + const timer = setInterval(() => { + setCountdown(prev => { + if (prev <= 1) { + clearInterval(timer); + return 0; + } + return prev - 1; + }); + }, 1000); + return () => clearInterval(timer); + }, [prompt.id]); + + const handle = (action: PromptAction) => { + onResolve(prompt.id, action, prompt.file_paths); + }; + + return ( +
+
+ {/* Header */} +
+

Content Review Required

+ auto-block in {countdown}s +
+ + {/* Body */} +
+
+ Matched keyword +
+ {prompt.matched_keyword} +
+
+ +
+ Target +
{prompt.url}
+
+ +
+ Files in request ({prompt.file_paths.length}) +
+ {prompt.file_paths.map(fp => ( +
+ {fp} +
+ ))} +
+
+
+ + {/* Actions */} +
+ + + + +
+
+
+ ); +} \ No newline at end of file diff --git a/internal/ui/frontend/src/components/PolicyEditor.tsx b/internal/ui/frontend/src/components/PolicyEditor.tsx index 1434b1e..ac37934 100644 --- a/internal/ui/frontend/src/components/PolicyEditor.tsx +++ b/internal/ui/frontend/src/components/PolicyEditor.tsx @@ -7,12 +7,27 @@ interface Props { allowedDirs: string[]; onAddDir: (dir: string) => void; onRemoveDir: (dir: string) => void; + contentKeywords: string[]; + onAddKeyword: (keyword: string) => void; + onRemoveKeyword: (keyword: string) => void; + whitelist: string[]; + onRemoveWhitelist: (path: string) => void; + blacklist: string[]; + onRemoveBlacklist: (path: string) => void; onSave: () => void; } -export function PolicyEditor({ patterns, onAdd, onRemove, allowedDirs, onAddDir, onRemoveDir, onSave }: Props) { +export function PolicyEditor({ + patterns, onAdd, onRemove, + allowedDirs, onAddDir, onRemoveDir, + contentKeywords, onAddKeyword, onRemoveKeyword, + whitelist, onRemoveWhitelist, + blacklist, onRemoveBlacklist, + onSave, +}: Props) { const [patternInput, setPatternInput] = useState(''); const [dirInput, setDirInput] = useState(''); + const [keywordInput, setKeywordInput] = useState(''); const [saved, setSaved] = useState(false); const handleAddPattern = () => { @@ -31,6 +46,14 @@ export function PolicyEditor({ patterns, onAdd, onRemove, allowedDirs, onAddDir, } }; + const handleAddKeyword = () => { + const trimmed = keywordInput.trim(); + if (trimmed && !contentKeywords.includes(trimmed)) { + onAddKeyword(trimmed); + setKeywordInput(''); + } + }; + const handleSave = () => { onSave(); setSaved(true); @@ -54,90 +77,114 @@ export function PolicyEditor({ patterns, onAdd, onRemove, allowedDirs, onAddDir, {/* Allowed Directories */} -
-
-

Allowed Directories

-

- Files outside these directories will be blocked. Leave empty to allow all. -

-
+
+ + +
-
- setDirInput(e.target.value)} - onKeyDown={(e) => e.key === 'Enter' && handleAddDir()} - placeholder="e.g. ~/Projects/my-app" - className="flex-1 bg-[#1a1a2e] border border-gray-700 rounded px-3 py-1.5 text-xs text-gray-300 font-mono placeholder-gray-600 focus:outline-none focus:border-blue-600" - /> - -
+ {/* Deny File Patterns */} +
+ + +
-
- {allowedDirs.map((d) => ( -
- {d} - -
- ))} - {allowedDirs.length === 0 && ( -
No directory scope configured — all directories allowed.
- )} -
+ {/* Content Keywords */} +
+ + +
+ + {/* Whitelist */} + {whitelist.length > 0 && ( +
+ +
+ )} + + {/* Blacklist */} + {blacklist.length > 0 && ( +
+ +
+ )} +
+ ); +} + +function Section({ title, description, children }: { title: string; description: string; children: React.ReactNode }) { + return ( +
+
+

{title}

+

{description}

+ {children} +
+ ); +} - {/* Deny File Patterns */} -
-
-

Deny File Patterns

-

- Files matching these patterns will be blocked even within allowed directories. -

-
+function AddInput({ value, onChange, onAdd, placeholder }: { + value: string; + onChange: (v: string) => void; + onAdd: () => void; + placeholder: string; +}) { + return ( +
+ onChange(e.target.value)} + onKeyDown={(e) => e.key === 'Enter' && onAdd()} + placeholder={placeholder} + className="flex-1 bg-[#1a1a2e] border border-gray-700 rounded px-3 py-1.5 text-xs text-gray-300 font-mono placeholder-gray-600 focus:outline-none focus:border-blue-600" + /> + +
+ ); +} -
- setPatternInput(e.target.value)} - onKeyDown={(e) => e.key === 'Enter' && handleAddPattern()} - placeholder="e.g. *.env, **/secrets/**, .aws/*" - className="flex-1 bg-[#1a1a2e] border border-gray-700 rounded px-3 py-1.5 text-xs text-gray-300 font-mono placeholder-gray-600 focus:outline-none focus:border-blue-600" - /> +function ItemList({ items, onRemove, color, empty }: { + items: string[]; + onRemove: (item: string) => void; + color: string; + empty: string; +}) { + return ( +
+ {items.map((item) => ( +
+ {item}
- -
- {patterns.map((p) => ( -
- {p} - -
- ))} - {patterns.length === 0 && ( -
No deny patterns configured.
- )} -
-
+ ))} + {items.length === 0 && empty && ( +
{empty}
+ )}
); } \ No newline at end of file diff --git a/internal/ui/frontend/src/hooks/useContentPrompts.ts b/internal/ui/frontend/src/hooks/useContentPrompts.ts new file mode 100644 index 0000000..73fd5aa --- /dev/null +++ b/internal/ui/frontend/src/hooks/useContentPrompts.ts @@ -0,0 +1,32 @@ +import { useState, useEffect, useCallback } from 'react'; +import { EventsOn } from '../../wailsjs/runtime/runtime'; +import { + ResolveContentPrompt, + ResolveContentPromptForFile, +} from '../../wailsjs/go/ui/App'; +import type { ContentPrompt, PromptAction } from '../types'; + +export function useContentPrompts() { + const [queue, setQueue] = useState([]); + + useEffect(() => { + const cancel = EventsOn('content:prompt', (prompt: ContentPrompt) => { + setQueue(prev => [...prev, prompt]); + }); + return () => { cancel(); }; + }, []); + + const resolve = useCallback(async (promptId: string, action: PromptAction, filePaths: string[]) => { + // Persist whitelist/blacklist for each file if needed + if (action === 'allow_always' || action === 'block_always') { + for (const fp of filePaths) { + await ResolveContentPromptForFile(action, fp); + } + } + // Unblock the interceptor + await ResolveContentPrompt(promptId, action); + setQueue(prev => prev.filter(p => p.id !== promptId)); + }, []); + + return { current: queue[0] ?? null, queueLength: queue.length, resolve }; +} \ No newline at end of file diff --git a/internal/ui/frontend/src/hooks/usePolicy.ts b/internal/ui/frontend/src/hooks/usePolicy.ts index 11751e7..39a4c82 100644 --- a/internal/ui/frontend/src/hooks/usePolicy.ts +++ b/internal/ui/frontend/src/hooks/usePolicy.ts @@ -7,6 +7,13 @@ import { GetAllowedDirectories, AddAllowedDirectory, RemoveAllowedDirectory, + GetDenyContentKeywords, + AddDenyContentKeyword, + RemoveDenyContentKeyword, + GetContentKeywordWhitelist, + RemoveFromContentKeywordWhitelist, + GetContentKeywordBlacklist, + RemoveFromContentKeywordBlacklist, IsPolicyBypassed, SetPolicyBypassed, SaveConfig, @@ -15,24 +22,29 @@ import { export function usePolicy() { const [patterns, setPatterns] = useState([]); const [allowedDirs, setAllowedDirs] = useState([]); + const [contentKeywords, setContentKeywords] = useState([]); + const [whitelist, setWhitelist] = useState([]); + const [blacklist, setBlacklist] = useState([]); const [bypassed, setBypassed] = useState(false); useEffect(() => { GetDenyPatterns().then(setPatterns); GetAllowedDirectories().then(setAllowedDirs); + GetDenyContentKeywords().then(setContentKeywords); + GetContentKeywordWhitelist().then(setWhitelist); + GetContentKeywordBlacklist().then(setBlacklist); IsPolicyBypassed().then(setBypassed); }, []); + // Deny patterns const addPattern = useCallback(async (pattern: string) => { await AddDenyPattern(pattern); - const updated = await GetDenyPatterns(); - setPatterns(updated); + setPatterns(await GetDenyPatterns()); }, []); const removePattern = useCallback(async (pattern: string) => { await RemoveDenyPattern(pattern); - const updated = await GetDenyPatterns(); - setPatterns(updated); + setPatterns(await GetDenyPatterns()); }, []); const updatePatterns = useCallback(async (newPatterns: string[]) => { @@ -40,18 +52,41 @@ export function usePolicy() { setPatterns(newPatterns); }, []); + // Allowed directories const addDirectory = useCallback(async (dir: string) => { await AddAllowedDirectory(dir); - const updated = await GetAllowedDirectories(); - setAllowedDirs(updated); + setAllowedDirs(await GetAllowedDirectories()); }, []); const removeDirectory = useCallback(async (dir: string) => { await RemoveAllowedDirectory(dir); - const updated = await GetAllowedDirectories(); - setAllowedDirs(updated); + setAllowedDirs(await GetAllowedDirectories()); }, []); + // Content keywords + const addContentKeyword = useCallback(async (keyword: string) => { + await AddDenyContentKeyword(keyword); + setContentKeywords(await GetDenyContentKeywords()); + }, []); + + const removeContentKeyword = useCallback(async (keyword: string) => { + await RemoveDenyContentKeyword(keyword); + setContentKeywords(await GetDenyContentKeywords()); + }, []); + + // Whitelist + const removeFromWhitelist = useCallback(async (path: string) => { + await RemoveFromContentKeywordWhitelist(path); + setWhitelist(await GetContentKeywordWhitelist()); + }, []); + + // Blacklist + const removeFromBlacklist = useCallback(async (path: string) => { + await RemoveFromContentKeywordBlacklist(path); + setBlacklist(await GetContentKeywordBlacklist()); + }, []); + + // Bypass const toggleBypassed = useCallback(async () => { const next = !bypassed; await SetPolicyBypassed(next); @@ -65,6 +100,9 @@ export function usePolicy() { return { patterns, bypassed, addPattern, removePattern, updatePatterns, allowedDirs, addDirectory, removeDirectory, + contentKeywords, addContentKeyword, removeContentKeyword, + whitelist, removeFromWhitelist, + blacklist, removeFromBlacklist, toggleBypassed, save, }; } \ No newline at end of file diff --git a/internal/ui/frontend/src/types.ts b/internal/ui/frontend/src/types.ts index 71dfd33..1d457b6 100644 --- a/internal/ui/frontend/src/types.ts +++ b/internal/ui/frontend/src/types.ts @@ -35,3 +35,13 @@ export interface StoreStats { blocked_count: number; file_detections: number; } + +export interface ContentPrompt { + id: string; + session_id: string; + url: string; + matched_keyword: string; + file_paths: string[]; +} + +export type PromptAction = 'allow_once' | 'allow_always' | 'block_once' | 'block_always'; diff --git a/internal/ui/frontend/wailsjs/go/ui/App.ts b/internal/ui/frontend/wailsjs/go/ui/App.ts index 80315de..d1708da 100644 --- a/internal/ui/frontend/wailsjs/go/ui/App.ts +++ b/internal/ui/frontend/wailsjs/go/ui/App.ts @@ -46,6 +46,48 @@ export function RemoveAllowedDirectory(dir: string): Promise { return window.go.ui.App.RemoveAllowedDirectory(dir); } +// Content keywords +export function GetDenyContentKeywords(): Promise { + return window.go.ui.App.GetDenyContentKeywords(); +} + +export function SetDenyContentKeywords(keywords: string[]): Promise { + return window.go.ui.App.SetDenyContentKeywords(keywords); +} + +export function AddDenyContentKeyword(keyword: string): Promise { + return window.go.ui.App.AddDenyContentKeyword(keyword); +} + +export function RemoveDenyContentKeyword(keyword: string): Promise { + return window.go.ui.App.RemoveDenyContentKeyword(keyword); +} + +export function GetContentKeywordWhitelist(): Promise { + return window.go.ui.App.GetContentKeywordWhitelist(); +} + +export function RemoveFromContentKeywordWhitelist(path: string): Promise { + return window.go.ui.App.RemoveFromContentKeywordWhitelist(path); +} + +export function GetContentKeywordBlacklist(): Promise { + return window.go.ui.App.GetContentKeywordBlacklist(); +} + +export function RemoveFromContentKeywordBlacklist(path: string): Promise { + return window.go.ui.App.RemoveFromContentKeywordBlacklist(path); +} + +// Content prompt resolution +export function ResolveContentPrompt(promptID: string, action: string): Promise { + return window.go.ui.App.ResolveContentPrompt(promptID, action); +} + +export function ResolveContentPromptForFile(action: string, filePath: string): Promise { + return window.go.ui.App.ResolveContentPromptForFile(action, filePath); +} + export function IsPolicyBypassed(): Promise { return window.go.ui.App.IsPolicyBypassed(); }