diff --git a/internal/domain/workflow/steps.go b/internal/domain/workflow/steps.go index b5eea498d..ea5d41e0f 100644 --- a/internal/domain/workflow/steps.go +++ b/internal/domain/workflow/steps.go @@ -163,12 +163,15 @@ func StageYaegiGate() Stage { var blocking []string for _, f := range findings { + if err := f.Validate(); err != nil { + return fmt.Errorf("custom gate: %w", err) + } loc := f.File if f.Line > 0 { loc = fmt.Sprintf("%s:%d", f.File, f.Line) } msg := strings.TrimSpace(loc + ": " + f.Message) - if f.Level == "error" { + if f.Blocking() { blocking = append(blocking, msg) } tc.Log.Info("custom gate finding", "level", f.Level, "file", f.File, "line", f.Line, "message", f.Message) diff --git a/internal/domain/workflow/steps_test.go b/internal/domain/workflow/steps_test.go index 1d5a51745..74580e254 100644 --- a/internal/domain/workflow/steps_test.go +++ b/internal/domain/workflow/steps_test.go @@ -139,6 +139,31 @@ func Check(ctx gate.GateContext) []gate.Finding { } } +func TestStageYaegiGateRejectsUnknownLevel(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not installed") + } + dir := gitRepoWithOriginRef(t, "main") + writeGateGo(t, dir, `package gate + +import "github.com/samcharles93/archie-core/internal/gate" + +func Check(ctx gate.GateContext) []gate.Finding { + return []gate.Finding{{Level: "fatal", Message: "mis-typed level"}} +} +`) + if err := os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("hi\n"), 0o644); err != nil { + t.Fatal(err) + } + runGit(t, dir, "add", "-A") + runGit(t, dir, "commit", "-m", "add notes") + + tc := newYaegiGateTaskContext(t, dir) + if err := StageYaegiGate().Run(context.Background(), tc); err == nil { + t.Fatal("StageYaegiGate() = nil, want an error for an unrecognized finding level (fail closed)") + } +} + func TestStageRepoStagesNilLoaderIsNoop(t *testing.T) { tc := &TaskContext{Log: slog.New(slog.DiscardHandler)} if err := StageRepoStages().Run(context.Background(), tc); err != nil { diff --git a/internal/gate/gate.go b/internal/gate/gate.go index e58edff7d..9a0d425a4 100644 --- a/internal/gate/gate.go +++ b/internal/gate/gate.go @@ -5,6 +5,19 @@ // the like). package gate +import "fmt" + +// Level is the severity of a gate finding. LevelError blocks the gate; +// LevelWarn is advisory and logged only. +type Level string + +const ( + // LevelError blocks the gate: the task is parked instead of opening a PR. + LevelError Level = "error" + // LevelWarn is advisory and logged only. + LevelWarn Level = "warn" +) + // GateContext carries everything a custom gate function can inspect. type GateContext struct { // Diff is the unified diff of all changes against BaseRef. @@ -21,8 +34,9 @@ type GateContext struct { // Finding is one gate violation. type Finding struct { - // Level is "error" (blocks the gate) or "warn" (advisory, logged only). - Level string + // Level is the severity: LevelError blocks the gate, LevelWarn is + // advisory and logged only. + Level Level // File is the optional file path the finding applies to. File string // Line is the optional line number within File. @@ -30,12 +44,29 @@ type Finding struct { Message string } -// Blocking reports whether any finding has Level "error". +// Blocking reports whether this finding blocks the gate. +func (f Finding) Blocking() bool { + return f.Level == LevelError +} + +// Blocking reports whether any finding blocks the gate. func Blocking(findings []Finding) bool { for _, f := range findings { - if f.Level == "error" { + if f.Blocking() { return true } } return false } + +// Validate checks that the finding satisfies contract invariants. An +// unrecognized level fails closed: a script that emits a mis-typed or empty +// level is an error, never a silently non-blocking finding. +func (f Finding) Validate() error { + switch f.Level { + case LevelError, LevelWarn: + return nil + default: + return fmt.Errorf("invalid gate level %q (must be %q or %q)", f.Level, LevelError, LevelWarn) + } +} diff --git a/internal/gate/gate_test.go b/internal/gate/gate_test.go index 334e35ade..c8ae4cb0d 100644 --- a/internal/gate/gate_test.go +++ b/internal/gate/gate_test.go @@ -99,6 +99,40 @@ func TestBlocking(t *testing.T) { }) } +func TestFindingValidate(t *testing.T) { + t.Run("error is valid", func(t *testing.T) { + if err := (Finding{Level: LevelError}).Validate(); err != nil { + t.Errorf("Validate() = %v, want nil", err) + } + }) + + t.Run("warn is valid", func(t *testing.T) { + if err := (Finding{Level: LevelWarn}).Validate(); err != nil { + t.Errorf("Validate() = %v, want nil", err) + } + }) + + t.Run("unrecognized level fails closed", func(t *testing.T) { + for _, level := range []Level{"fatal", "ERROR", "Error", ""} { + if err := (Finding{Level: level}).Validate(); err == nil { + t.Errorf("Validate() = nil for level %q, want an error", level) + } + } + }) +} + +func TestFindingBlocking(t *testing.T) { + if !(Finding{Level: LevelError}).Blocking() { + t.Error("Finding{Level: LevelError}.Blocking() = false, want true") + } + if (Finding{Level: LevelWarn}).Blocking() { + t.Error("Finding{Level: LevelWarn}.Blocking() = true, want false") + } + if (Finding{Level: ""}).Blocking() { + t.Error("Finding{Level: \"\"}.Blocking() = true, want false") + } +} + func TestGateContextZeroValue(t *testing.T) { // Zero-value GateContext should not panic when accessed. var gctx GateContext diff --git a/internal/gate/gateextract/gateextract_test.go b/internal/gate/gateextract/gateextract_test.go index c8d2bc3af..fb1bf5ce6 100644 --- a/internal/gate/gateextract/gateextract_test.go +++ b/internal/gate/gateextract/gateextract_test.go @@ -19,6 +19,15 @@ func TestSymbolsContainsExpectedEntries(t *testing.T) { t.Errorf("Blocking kind = %v, want Func", v.Kind()) } + // LevelError and LevelWarn must be the exported level constants. + for _, name := range []string{"LevelError", "LevelWarn"} { + if v, ok := pkg[name]; !ok { + t.Errorf("%s not found in Symbols", name) + } else if v.Kind() != reflect.String { + t.Errorf("%s kind = %v, want String", name, v.Kind()) + } + } + // Finding must be a pointer type. if v, ok := pkg["Finding"]; !ok { t.Error("Finding not found in Symbols") @@ -26,6 +35,14 @@ func TestSymbolsContainsExpectedEntries(t *testing.T) { t.Errorf("Finding kind = %v, want Ptr", v.Kind()) } + // Level must be a pointer to the defined string type, so interpreted + // scripts can resolve Finding.Level's named type. + if v, ok := pkg["Level"]; !ok { + t.Error("Level not found in Symbols") + } else if v.Kind() != reflect.Pointer { + t.Errorf("Level kind = %v, want Ptr", v.Kind()) + } + // GateContext must be a pointer type. if v, ok := pkg["GateContext"]; !ok { t.Error("GateContext not found in Symbols") @@ -39,8 +56,11 @@ func TestSymbolsNoUnexpectedEntries(t *testing.T) { pkg := Symbols[pkgKey] expected := map[string]bool{ "Blocking": true, + "LevelError": true, + "LevelWarn": true, "Finding": true, "GateContext": true, + "Level": true, } for name := range pkg { if !expected[name] { diff --git a/internal/gate/gateextract/github_com-samcharles93-archie-core-internal-gate.go b/internal/gate/gateextract/github_com-samcharles93-archie-core-internal-gate.go index 625718ec7..c556d0d19 100644 --- a/internal/gate/gateextract/github_com-samcharles93-archie-core-internal-gate.go +++ b/internal/gate/gateextract/github_com-samcharles93-archie-core-internal-gate.go @@ -10,10 +10,13 @@ import ( func init() { Symbols["github.com/samcharles93/archie-core/internal/gate/gate"] = map[string]reflect.Value{ // function, constant and variable definitions - "Blocking": reflect.ValueOf(gate.Blocking), + "Blocking": reflect.ValueOf(gate.Blocking), + "LevelError": reflect.ValueOf(gate.LevelError), + "LevelWarn": reflect.ValueOf(gate.LevelWarn), // type definitions "Finding": reflect.ValueOf((*gate.Finding)(nil)), "GateContext": reflect.ValueOf((*gate.GateContext)(nil)), + "Level": reflect.ValueOf((*gate.Level)(nil)), } } diff --git a/internal/gateway/stream.go b/internal/gateway/stream.go index db499a170..19a5579d6 100644 --- a/internal/gateway/stream.go +++ b/internal/gateway/stream.go @@ -4,6 +4,8 @@ import ( "encoding/json" "fmt" "strings" + + "github.com/samcharles93/archie-core/internal/webhookguard" ) // toolSummaryMaxRunes bounds a rendered tool summary. Tool output is @@ -190,13 +192,7 @@ func redactToolParameters(value any, sensitive bool) any { func sensitiveParameterKey(key string) bool { normalized := strings.NewReplacer("-", "_", " ", "_").Replace(strings.ToLower(key)) - for _, marker := range []string{ - "token", "secret", "password", "passwd", "pwd", "passphrase", - "api_key", "apikey", "api_secret", "client_secret", "private_key", "secret_key", - "signing_key", "authorization", "bearer", "credential", "cookie", "session", - "access_token", "refresh_token", "id_token", "bot_token", "webhook_secret", - "x_api_key", "x_auth_token", "jwt", "oauth", "csrf", "otp", "signature", - } { + for _, marker := range webhookguard.SensitiveKeyMarkers { if strings.Contains(normalized, marker) { return true } diff --git a/internal/gateway/stream_test.go b/internal/gateway/stream_test.go index c2ba90c72..d90bec757 100644 --- a/internal/gateway/stream_test.go +++ b/internal/gateway/stream_test.go @@ -1,10 +1,35 @@ package gateway import ( + "encoding/json" "strings" "testing" + + "github.com/samcharles93/archie-core/internal/webhookguard" ) +func TestRedactionConsumersShareMarkerSet(t *testing.T) { + if len(webhookguard.SensitiveKeyMarkers) == 0 { + t.Fatal("webhookguard.SensitiveKeyMarkers is empty, want a non-empty shared set") + } + for _, marker := range webhookguard.SensitiveKeyMarkers { + if !sensitiveParameterKey(marker) { + t.Errorf("sensitiveParameterKey(%q) = false, want true (shared marker set)", marker) + } + payload, err := json.Marshal(map[string]string{marker: "secret"}) + if err != nil { + t.Fatal(err) + } + got, err := webhookguard.RedactPayload(payload) + if err != nil { + t.Fatalf("RedactPayload(%q): %v", marker, err) + } + if string(got) == string(payload) { + t.Errorf("webhookguard did not redact shared marker key %q", marker) + } + } +} + func TestSummarizeToolParameters(t *testing.T) { tests := []struct { name string diff --git a/internal/webhookguard/redact.go b/internal/webhookguard/redact.go index c90710852..4146f111e 100644 --- a/internal/webhookguard/redact.go +++ b/internal/webhookguard/redact.go @@ -10,14 +10,15 @@ import ( // redactedValue replaces a value whose key (or shape) looks sensitive. const redactedValue = "[redacted]" -// sensitiveKeyMarkers is the key-name heuristic, matching -// internal/gateway/stream.go's sensitiveParameterKey exactly so the two -// redaction paths agree on what counts as sensitive. It is intentionally +// SensitiveKeyMarkers is the key-name heuristic shared by both redaction +// paths -- webhook-capture redaction here and chat-transcript +// summarization in internal/gateway/stream.go's sensitiveParameterKey -- +// so they agree on what counts as sensitive. It is intentionally // conservative: a value whose key matches is redacted wholesale, so a marker // that is too broad (e.g. bare "key" or "auth", which would match "Key: 42" // or "author") would destroy the schema-by-example mapping use case the // captured payload exists to serve. -var sensitiveKeyMarkers = []string{ +var SensitiveKeyMarkers = []string{ "token", "secret", "password", "passwd", "pwd", "passphrase", "api_key", "apikey", "api_secret", "client_secret", "private_key", "secret_key", "signing_key", "authorization", "bearer", "credential", "cookie", "session", @@ -107,7 +108,7 @@ func sensitiveValueShape(s string) bool { func sensitiveKey(key string) bool { normalized := strings.NewReplacer("-", "_", " ", "_").Replace(strings.ToLower(key)) - for _, marker := range sensitiveKeyMarkers { + for _, marker := range SensitiveKeyMarkers { if strings.Contains(normalized, marker) { return true }