Compare commits

...
Author SHA1 Message Date
BaaRai 5bed53b6ae Merge pull request #454 from BaaRai/fix/pin-go-builder-1.26.11
build: pin the Go builder image to 1.26.11 to match go.mod
2026-11-21 20:02:20 +01:00
BaaRai a4a2ee4a51 Merge pull request #453 from NikolayGusev-astra/fix/finding-traffic-guidance-disabled
agent: state that traffic binding is off when the switch is off
2026-11-21 19:23:28 +01:00
BaaRai cc573132c4 Merge pull request #452 from Coff0xc/fix/pg-dsn-password
fix(config): encode Compose database passwords
2026-11-21 19:14:19 +01:00
BaaRai ca9aef6692 Merge pull request #446 from jackybabes/fix/install-webui-mkdir
fix(install): create server/webui before copying the frontend build
2026-11-21 19:14:02 +01:00
BaaRai 09a28a3bf8 Merge pull request #443 from jackybabes/fix/install-docker-kali
fix(install): don't run get.docker.com on unsupported distros like Kali
2026-11-21 19:13:56 +01:00
Nikolay Gusev 55e2a4d037 agent: state on the tools that traffic binding is off when the switch is off
With agent_traffic_binding disabled (the default) findingWorkflowTools strips
bind_finding_traffic from every agent toolset and removes traffic_refs /
evidence_hint_id from the report_finding and hint schemas, but the tool
descriptions keep promising the binding path: prove_goal says a finding closes
a goal once a traffic_ref is bound, and the report_finding error path says
already-registered findings can be bound later via bind_finding_traffic. An
agent then chases a tool that is not in its toolset.

Observed on a live run (v0.7.0, local OpenAI-compatible model): a worker spent
minutes on it — "the tool bind_finding_traffic must be invoked as a tool", a
bare Bash true, then grepping the transcripts and the strings of the binary.
The task registered findings with poe_level 3, zero bound traffic, and closed
no goal; a run with the switch on bound traffic and closed 4 of 6 goals.

Fix: attach binding-off notes to the same tools the capture-off notes ride on
(report_finding, add_hint / add_task_hint, prove_goal) in the disabled branch,
so the standing guidance stays empty — the contract the PG test asserts — while
the agent is told the tool and the parameters are absent, that findings stay
unverified, and that an operator can enable binding or bind manually.

Test: agent/finding_workflow_test.go asserts the notes exist on the tools and
name the absent tool; red on the planted break, green with the fix. Verified
against the PostgreSQL-dependent server test that CI runs
(TestFindingWorkflowAutoHintToPlannerAndSetting) and go test ./agent/ ./server/.
2026-11-21 20:58:25 +03:00
Coff0xc 8b4f890e61 fix(server): seal ARTEX_PG_PASSWORD with the other startup secrets
The Linux handoff test reports every name in secretEnv. The new password
variable was scrubbed but not included in that fixture, so CI reported it
unset after sealing.
2026-11-21 17:49:22 +00:00
Coff0xc ff287467aa fix(config): encode the Compose database password instead of pasting it into the URL
docker-compose.yml built ARTEX_PG_DSN by interpolating POSTGRES_PASSWORD, so
/, ?, %, @, : and spaces made the URL invalid. The server now assembles that
URL from ARTEX_PG_HOST, ARTEX_PG_PORT, ARTEX_PG_USER, ARTEX_PG_PASSWORD,
ARTEX_PG_DBNAME and ARTEX_PG_SSLMODE. An explicit ARTEX_PG_DSN still wins.
ARTEX_PG_PASSWORD is scrubbed with the other startup secrets.
2026-11-21 17:25:20 +00:00
BaaRai c65034c50f Merge pull request #448 from BaaRai/feat/traffic-capture-off-notice
feat(agent,web): surface traffic-capture-off notice in agent tool descriptions, setup, settings, and dashboard
2026-11-21 18:10:40 +01:00
BaaRai df9536b7e5 Merge pull request #447 from BaaRai/fix/neoneye-269-reopen-lessons
fix(db,agent): reopen proved goals on invalidation, preserve lesson withdrawal history, and run lesson extraction in-tx (#269)
2026-11-21 18:10:32 +01:00
BaaRai 13073ce18e fix(db): mirror SetNodeState (blocked_reason, content_version) when reopening goals (#269) 2026-11-21 17:54:21 +01:00
BaaRai 1adfc21346 perf(agent): read traffic capture setting once per findingWorkflowTools pass 2026-11-21 17:01:15 +01:00
BaaRai c3a055135d fix(db,agent): keep goal met when another valid proof remains and share invalidating status list (#269) 2026-11-21 17:01:10 +01:00
jackybabesandClaude Opus 5.5 c90e2c980c fix(install): match deb822 docker.sources across lines
In a deb822 .sources file the URIs and Suites fields are on separate
lines, so the single-line grep never matched and the broken Docker
repo was left in place. Match the URI and the distro id separately
across the whole file, and skip the check when the id is empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 15:53:05 +00:00
BaaRai b56ad38b43 feat(agent,web): explain that traffic capture is off and required for provable findings 2026-11-21 16:35:31 +01:00
BaaRai bfaec521ac test(agent,db): document and lock risk_accepted goal-proof semantics (#269) 2026-11-21 16:29:53 +01:00
BaaRai a3c082fdac fix(db): run lesson extraction inside the status and retest transaction (#269) 2026-11-21 16:22:27 +01:00
BaaRai d15166c476 fix(db): preserve rsi_lesson_evidence withdrawal history on re-confirmation (#269) 2026-11-21 16:17:07 +01:00
BaaRai 59d514e37c fix(db): reopen proved goals in the same transaction on false_positive, duplicate, or ignored (#269) 2026-11-21 16:13:30 +01:00
jackybabesandClaude Opus 5.5 b5bf99f5fb fix(install): create server/webui before copying the frontend build
server/webui isn't tracked in git, so on a fresh clone the local build
in install.sh and update.sh fails at the copy step:

  cp: cannot create directory 'server/webui/dist': No such file or directory

Both scripts now run mkdir -p server/webui before the copy. build.sh
already does the equivalent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 14:57:07 +00:00
jackybabesandClaude Opus 5.5 61478bb90b fix(install): don't run get.docker.com on unsupported distros
get.docker.com only handles a fixed set of distros. On Kali it adds a
Docker repo for "debian kali-rolling", which doesn't exist, so apt
update fails and keeps failing after the installer exits.

ensure_docker now uses get.docker.com only for the distros it
supports. Other apt-based distros install docker.io and a compose v2
package from their own repos, and the docker service is started
explicitly because Kali doesn't start services on install. A broken
docker.list left by an earlier run is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 12:59:56 +00:00
32 changed files with 1249 additions and 136 deletions
+3
View File
@@ -11,6 +11,9 @@ ARTEX_TRUSTED_PROXIES=
# Set it when ./keys is not persistent. Losing the key loses the stored secrets.
# ARTEX_SECRET_KEY=
POSTGRES_USER=artex
# The server percent-encodes this into the connection URL, so / ? % @ : and
# spaces are safe. Quote a value that contains #, and write $$ for a literal $,
# because Compose reads this file that way.
POSTGRES_PASSWORD=change-me-please
POSTGRES_DB=artex
+6
View File
@@ -2,6 +2,12 @@
All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased]
### Fixed
- **Docker Compose database passwords with URL-special characters**: `docker-compose.yml` no longer pastes `POSTGRES_PASSWORD` into `ARTEX_PG_DSN`. The server builds the URL from `ARTEX_PG_HOST`, `ARTEX_PG_PORT`, `ARTEX_PG_USER`, `ARTEX_PG_PASSWORD`, `ARTEX_PG_DBNAME` and `ARTEX_PG_SSLMODE`, percent-encoding the user and password, so `/`, `?`, `%`, `@`, `:` and spaces connect. An explicit `ARTEX_PG_DSN` still wins and is not rewritten. `ARTEX_PG_PASSWORD` is removed from the environment with the other startup secrets (#450).
## [0.7.0] - 2026-11-21
Agent-driven traffic capture (SOCKS5, transparent TCP and raw UDP), operator tampering hooks with their admin panel, the agentic injection and proof hardening from the #124 audit, LLM context telemetry and the worker cache-prefix split, capture-proxy rewrite rules, HAR import and export, and a large security batch across the interception gate, sessions, logs, the workspace file API and the model endpoint probe.
+4
View File
@@ -341,6 +341,10 @@ docker compose up -d --build
# → http://localhost:8787
```
`POSTGRES_PASSWORD` is passed to ARTEX as its own variable. The server percent-encodes it into
the connection URL, so a password may contain `/`, `?`, `%`, `@`, `:` or spaces. In `.env`, quote
a value that contains `#`, and write `$$` for a literal `$`.
The image includes a scanner toolchain (`nmap`, `nuclei`, `httpx`, `katana`, `ffuf`, `dalfox`,
`sqlmap`, `ripgrep`, `curl`, `npm`, …); `./skills` and `./data` are persisted via bind mounts.
+28
View File
@@ -277,6 +277,34 @@ func TestProveGoalRefusesFalsePositiveFinding(t *testing.T) {
}
}
// risk_accepted means a real finding with accepted risk, not an invalid one:
// it must remain eligible to prove a goal (#269).
func TestProveGoalAllowsRiskAcceptedFinding(t *testing.T) {
if findingTriageBlocksGoal(db.FindingRiskAccepted) {
t.Fatalf("findingTriageBlocksGoal(%q) = true, want false", db.FindingRiskAccepted)
}
d := testDB(t)
t.Cleanup(func() { _ = d.Close() })
task, err := d.CreateTaskWithOptions("risk-accepted goal", "verify risk_accepted finding may prove a goal", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
s := d.Exploration(task.ExplorationID)
goal := addGuardNode(t, s, db.KindGoal, map[string]any{"text": "prove auth bypass"}, "open")
rec := seedProvenFinding(t, d, task, "ex-risk-1", "https://risk.example.test/admin",
[]int64{seedFindingAsset(t, d, task, "https://risk.example.test/admin")})
if _, _, _, err := d.SetFindingStatusWithNotify(context.Background(), rec.FindingID, db.FindingRiskAccepted); err != nil {
t.Fatal(err)
}
tsx := NewToolSet(s, "planner")
tsx.SetTrafficProofChecker(func(_ context.Context, id string) (bool, error) { return id == "ex-risk-1", nil })
res := callGuardTool(t, tsx.proveGoal(), `{"goal_id":`+strconv.FormatInt(goal, 10)+`,"evidence_id":`+strconv.FormatInt(rec.NodeID, 10)+`,"reason":"accepted risk real finding"}`)
if res.IsError || nodeState(t, s, goal) != "met" || !tsx.GoalMet {
t.Fatalf("risk_accepted finding: IsError=%v state=%q GoalMet=%v %q", res.IsError, nodeState(t, s, goal), tsx.GoalMet, res.Flatten())
}
}
// factEvidenceLines keeps only substantive lines: a bare tool name or a short
// status fragment cannot tie a claim to an activity, and duplicates cost a
// lookup without adding a candidate.
+97 -4
View File
@@ -43,10 +43,82 @@ func findingTrafficBindingEnabled() bool {
return f != nil && f()
}
var (
trafficCaptureMu sync.RWMutex
trafficCaptureHook func() bool
)
// SetTrafficCaptureEnabled installs (or, with nil, removes) the hook that
// reports whether the server's global traffic capture switch is currently on.
func SetTrafficCaptureEnabled(f func() bool) {
trafficCaptureMu.Lock()
trafficCaptureHook = f
trafficCaptureMu.Unlock()
}
// TrafficCaptureEnabled returns the current hook, or nil when none is set.
func TrafficCaptureEnabled() func() bool {
trafficCaptureMu.RLock()
defer trafficCaptureMu.RUnlock()
return trafficCaptureHook
}
func trafficCaptureExplicitlyOff() bool {
f := TrafficCaptureEnabled()
return f != nil && !f()
}
const (
trafficCaptureOffProveGoalNote = "\nNote: traffic capture is currently OFF on this server, so no HTTP traffic is being recorded and findings cannot be bound to captured traffic to prove HTTP goals. Recorded findings stay visible, and non-HTTP goals can still be proved with an observed tool_output fact; enable traffic capture in System settings to make HTTP findings provable."
trafficCaptureOffReportFindingNote = "\nNote: traffic capture is currently OFF on this server, so no HTTP traffic is being recorded. Findings still save with textual/command evidence, but cannot prove goals via prove_goal until traffic capture is enabled in System settings and verified traffic is bound."
)
func trafficCaptureOffToolNote(toolName string, captureOff bool) string {
if !captureOff {
return ""
}
switch toolName {
case "prove_goal":
return trafficCaptureOffProveGoalNote
case "report_finding":
return trafficCaptureOffReportFindingNote
default:
return ""
}
}
// Automatic traffic binding off is a DIFFERENT switch from capture off: capture
// can be on while binding is off, and then the disabled branch below strips
// bind_finding_traffic and every traffic parameter from the schemas while the
// tool descriptions keep promising the binding path. An agent then chases a tool
// that is not in its toolset (observed: "the tool bind_finding_traffic must be
// invoked as a tool", a bare Bash true, then grepping the transcripts and the
// binary). These notes ride on the tool descriptions, exactly like the capture
// notes above, so the standing guidance stays empty when the feature is off.
const (
findingBindingOffProveGoalNote = "\nNote: automatic traffic binding is OFF on this server, so a finding cannot be bound to captured traffic here and cannot close an HTTP goal. Recorded findings stay visible; non-HTTP goals still close with an observed tool_output fact. An operator can enable binding (System settings) or bind captured traffic manually on the finding page, after which a bound finding closes the goal."
findingBindingOffReportFindingNote = "\nNote: automatic traffic binding is OFF on this server, so report_finding carries no traffic parameters and the bind_finding_traffic tool is not in your toolset. Findings still save with their evidence, but stay unverified and cannot prove a goal. Register a reproducible PoC in evidence as usual; do not guess traffic IDs and do not re-probe only to capture packets."
findingBindingOffHintNote = "\nNote: automatic traffic binding is OFF on this server, so hint traffic parameters are not in this schema. Keep the verified evidence and the known real traffic IDs in the hint text; the receiving task registers the finding and the operator can bind captured traffic later."
)
func findingBindingOffToolNote(toolName string) string {
switch toolName {
case "prove_goal":
return findingBindingOffProveGoalNote
case "report_finding":
return findingBindingOffReportFindingNote
case "add_hint", "add_task_hint":
return findingBindingOffHintNote
default:
return ""
}
}
// Applied after ToolResolve: user descriptions and prompts remain intact, while
// all actual reporters (including Planner and custom chat agents) see the same
// API contract. Disabled/unbound tools are never reintroduced here.
func findingWorkflowTools(agentKey string, tools []actool.CoreTool) ([]actool.CoreTool, string) {
captureOff := trafficCaptureExplicitlyOff()
if !findingTrafficBindingEnabled() {
out := make([]actool.CoreTool, 0, len(tools))
for _, tool := range tools {
@@ -56,18 +128,36 @@ func findingWorkflowTools(agentKey string, tools []actool.CoreTool) ([]actool.Co
if agentKey == "reporter" && (tool.Name() == "traffic_search" || tool.Name() == "traffic_get" || tool.Name() == "traffic_blob" || tool.Name() == "traffic_messages") {
continue
}
desc := tool.Description()
schema := tool.InputSchema()
decorated := false
switch tool.Name() {
case "report_finding", "add_hint", "add_task_hint":
// Work on a copy: toggling back on must restore the original schema.
raw, _ := json.Marshal(tool.InputSchema())
var schema map[string]any
if json.Unmarshal(raw, &schema) == nil {
stripTrafficParameters(schema)
tool = DecorateTool(tool, tool.Description(), schema)
var s map[string]any
if json.Unmarshal(raw, &s) == nil {
stripTrafficParameters(s)
schema = s
decorated = true
}
}
if note := trafficCaptureOffToolNote(tool.Name(), captureOff); note != "" {
desc += note
decorated = true
}
if note := findingBindingOffToolNote(tool.Name()); note != "" {
desc += note
decorated = true
}
if decorated {
tool = DecorateTool(tool, desc, schema)
}
out = append(out, tool)
}
// The standing guidance stays empty: the binding-off notes ride on the
// tool descriptions, so a disabled deployment keeps the same contract the
// PG test asserts (def.FindingGuidance == "").
return out, ""
}
out := append([]actool.CoreTool(nil), tools...)
@@ -83,6 +173,9 @@ func findingWorkflowTools(agentKey string, tools []actool.CoreTool) ([]actool.Co
case "get_finding_traffic", "bind_finding_traffic", "list_findings", "list_task_findings", "node_detail", "get_task_node_detail", "update_finding_report":
note = findingIDGuidance
}
if capNote := trafficCaptureOffToolNote(tool.Name(), captureOff); capNote != "" {
note += capNote
}
if note != "" {
out[i] = DecorateTool(tool, tool.Description()+note, tool.InputSchema())
}
+74
View File
@@ -39,6 +39,29 @@ func TestFindingWorkflowSharedAssemblyAndSwitch(t *testing.T) {
if strings.Contains(system[0], "traffic_refs") != on {
t.Fatalf("%s: guidance ignored switch: %v", role, on)
}
if !on {
// The switch strips the tool and the schema, so the tool descriptions
// must say so: otherwise the agent chases bind_finding_traffic, which
// is not in its toolset, and burns turns on it.
if def.FindingGuidance != "" {
t.Fatalf("%s: disabled deployment must keep the standing guidance empty, got %q", role, def.FindingGuidance)
}
noted := false
for _, tool := range out {
if !strings.Contains(tool.Description(), "automatic traffic binding is OFF") {
continue
}
noted = true
// The tool that carries traffic parameters is the one whose
// schema lost them, so it must name the absent tool.
if tool.Name() == "report_finding" && !strings.Contains(tool.Description(), "bind_finding_traffic") {
t.Fatalf("%s: report_finding note must name the absent tool", role)
}
}
if !noted {
t.Fatalf("%s: disabled deployment must state on the tools that binding is off", role)
}
}
if on && (!strings.Contains(system[0], "TCP") || !strings.Contains(system[0], "evidence_hint_id")) {
t.Fatal("missing optional/handoff contract")
}
@@ -70,3 +93,54 @@ func TestFindingWorkflowSharedAssemblyAndSwitch(t *testing.T) {
t.Fatal("reintroduced disabled tool or its guidance")
}
}
func TestFindingWorkflowToolsTrafficCaptureOffNotice(t *testing.T) {
oldPolicy, oldCapture, oldResolve, oldAugment := FindingTrafficBindingEnabled(), TrafficCaptureEnabled(), ToolResolve(), ToolAugment()
t.Cleanup(func() {
SetFindingTrafficBindingEnabled(oldPolicy)
SetTrafficCaptureEnabled(oldCapture)
SetToolResolve(oldResolve)
SetToolAugment(oldAugment)
})
SetToolAugment(nil)
SetToolResolve(nil)
ts := NewToolSet(nil, "fixture")
base := []actool.CoreTool{ts.proveGoal(), ts.addFinding(), ts.addHint()}
for _, binding := range []bool{false, true} {
SetFindingTrafficBindingEnabled(func() bool { return binding })
calls := 0
SetTrafficCaptureEnabled(func() bool {
calls++
return false
})
outOff, _, clOff := AugmentTools(t.Context(), "planner", base)
clOff()
if calls != 1 {
t.Fatalf("binding=%v: capture hook called %d times for %d tools, want 1", binding, calls, len(base))
}
for _, tool := range outOff {
desc := tool.Description()
switch tool.Name() {
case "prove_goal", "report_finding":
if !strings.Contains(desc, "traffic capture is currently OFF") {
t.Fatalf("binding=%v %s: expected capture-off notice in description, got %q", binding, tool.Name(), desc)
}
case "add_hint":
if strings.Contains(desc, "traffic capture is currently OFF") {
t.Fatalf("binding=%v add_hint: unexpected capture-off notice", binding)
}
}
}
SetTrafficCaptureEnabled(func() bool { return true })
outOn, _, clOn := AugmentTools(t.Context(), "planner", base)
clOn()
for _, tool := range outOn {
if strings.Contains(tool.Description(), "traffic capture is currently OFF") {
t.Fatalf("binding=%v %s: unexpected capture-off notice when capture is ON", binding, tool.Name())
}
}
}
}
+3 -7
View File
@@ -1103,14 +1103,10 @@ func findingPayloadStatus(n *db.Node) string {
}
// findingTriageBlocksGoal is true when the finding's triage label says it is
// not a vulnerability to close a goal on.
// not a vulnerability to close a goal on. Delegates to db.FindingStatusInvalidatesGoal
// so prove_goal and DB goal-reopen logic share one list and cannot drift (#269).
func findingTriageBlocksGoal(status string) bool {
switch status {
case db.FindingFalsePositive, db.FindingDuplicate, db.FindingIgnored:
return true
default:
return false
}
return db.FindingStatusInvalidatesGoal(status)
}
func countActionableFindings(nodes []*db.Node) int {
+39 -2
View File
@@ -157,7 +157,15 @@ func SkillDir() (string, error) {
// PostgresDSN resolves the connection string with precedence:
//
// env ARTEX_PG_DSN > config file (database.dsn, or assembled from fields)
// env ARTEX_PG_DSN
// > env ARTEX_PG_HOST / ARTEX_PG_PORT / ARTEX_PG_USER / ARTEX_PG_PASSWORD /
// ARTEX_PG_DBNAME / ARTEX_PG_SSLMODE
// > config file (database.dsn, or assembled from fields)
//
// The component variables are how Docker Compose passes a password that contains
// URL-special characters: the password stays a raw environment value, and
// buildDSN percent-encodes it. An explicit ARTEX_PG_DSN is returned unchanged,
// so a value that was already assembled by something else is not rewritten.
//
// There is NO built-in fallback: when neither source supplies a database config,
// it returns an error naming the config path it inspected, so startup fails loudly
@@ -167,6 +175,9 @@ func PostgresDSN() (dsn, source string, err error) {
if v := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN")); v != "" {
return v, "environment variable ARTEX_PG_DSN", nil
}
if d, ok, err := postgresDSNFromEnv(); ok || err != nil {
return d, "environment variables ARTEX_PG_HOST/USER/PASSWORD/DBNAME", err
}
c, err := Load()
if err != nil {
return "", "", err
@@ -178,7 +189,33 @@ func PostgresDSN() (dsn, source string, err error) {
if db.Host != "" || db.DBName != "" || db.User != "" {
return db.buildDSN(), "config file " + Path() + " (database fields)", nil
}
return "", "", fmt.Errorf("no database config found: the environment variable ARTEX_PG_DSN is not set, and config file %s provides no database (dsn or host/user/dbname). Create the config file or set the environment variable and retry", Path())
return "", "", fmt.Errorf("no database config found: ARTEX_PG_DSN is not set, ARTEX_PG_HOST/USER/PASSWORD/DBNAME are not set, and config file %s provides no database (dsn or host/user/dbname). Create the config file or set the environment variable and retry", Path())
}
// postgresDSNFromEnv assembles a URL from the component environment variables.
// ok is false when none of them is set. The password is not trimmed: a space is
// a legal character and is the case docker-compose used to break.
func postgresDSNFromEnv() (dsn string, ok bool, err error) {
host := strings.TrimSpace(os.Getenv("ARTEX_PG_HOST"))
user := strings.TrimSpace(os.Getenv("ARTEX_PG_USER"))
password := os.Getenv("ARTEX_PG_PASSWORD")
dbname := strings.TrimSpace(os.Getenv("ARTEX_PG_DBNAME"))
portStr := strings.TrimSpace(os.Getenv("ARTEX_PG_PORT"))
ssl := strings.TrimSpace(os.Getenv("ARTEX_PG_SSLMODE"))
if host == "" && user == "" && password == "" && dbname == "" && portStr == "" && ssl == "" {
return "", false, nil
}
port := 0
if portStr != "" {
n, convErr := strconv.Atoi(portStr)
if convErr != nil || n <= 0 || n > 65535 {
return "", true, fmt.Errorf("ARTEX_PG_PORT %q is not a TCP port", portStr)
}
port = n
}
return Database{
Host: host, Port: port, User: user, Password: password, DBName: dbname, SSLMode: ssl,
}.buildDSN(), true, nil
}
func (d Database) buildDSN() string {
+60
View File
@@ -1,17 +1,29 @@
package config
import (
"net/url"
"os"
"path/filepath"
"strings"
"testing"
)
func clearPGComponentEnv(t *testing.T) {
t.Helper()
for _, k := range []string{
"ARTEX_PG_HOST", "ARTEX_PG_PORT", "ARTEX_PG_USER", "ARTEX_PG_PASSWORD",
"ARTEX_PG_DBNAME", "ARTEX_PG_SSLMODE",
} {
t.Setenv(k, "")
}
}
func TestPostgresDSNPrecedence(t *testing.T) {
dir := t.TempDir()
cfgPath := filepath.Join(dir, "config.json")
os.WriteFile(cfgPath, []byte(`{"database":{"host":"10.1.2.3","port":6000,"user":"u","password":"p","dbname":"d","sslmode":"require"}}`), 0o644)
t.Setenv("ARTEX_CONFIG", cfgPath)
clearPGComponentEnv(t)
// no env DSN → built from config file fields
t.Setenv("ARTEX_PG_DSN", "")
@@ -42,6 +54,53 @@ func TestPostgresDSNPrecedence(t *testing.T) {
}
}
func TestPostgresDSNEncodesComponentPassword(t *testing.T) {
clearPGComponentEnv(t)
t.Setenv("ARTEX_PG_DSN", "")
t.Setenv("ARTEX_CONFIG", filepath.Join(t.TempDir(), "nope.json"))
const password = "p/ss w@rd?#%"
t.Setenv("ARTEX_PG_HOST", "postgres")
t.Setenv("ARTEX_PG_PORT", "5432")
t.Setenv("ARTEX_PG_USER", "artex")
t.Setenv("ARTEX_PG_PASSWORD", password)
t.Setenv("ARTEX_PG_DBNAME", "artex")
t.Setenv("ARTEX_PG_SSLMODE", "disable")
got, source, err := PostgresDSN()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(source, "ARTEX_PG_HOST") {
t.Fatalf("source %q", source)
}
u, err := url.Parse(got)
if err != nil {
t.Fatalf("parse %q: %v", got, err)
}
pw, ok := u.User.Password()
if !ok || pw != password || u.User.Username() != "artex" || u.Host != "postgres:5432" || u.Path != "/artex" {
t.Fatalf("dsn %q decoded user=%q password=%q ok=%v host=%q path=%q", got, u.User.Username(), pw, ok, u.Host, u.Path)
}
if u.Query().Get("sslmode") != "disable" {
t.Fatalf("sslmode %q", u.RawQuery)
}
if strings.Contains(got, password) {
t.Fatalf("password left raw in %q", got)
}
// An explicit URL is not rewritten, even when the component password is set.
t.Setenv("ARTEX_PG_DSN", "postgres://already/set")
if got, _, err = PostgresDSN(); err != nil || got != "postgres://already/set" {
t.Fatalf("explicit DSN got %q err %v", got, err)
}
t.Setenv("ARTEX_PG_DSN", "")
t.Setenv("ARTEX_PG_PORT", "nope")
if _, _, err = PostgresDSN(); err == nil || !strings.Contains(err.Error(), "ARTEX_PG_PORT") {
t.Fatalf("bad port: %v", err)
}
}
// A config file that exists but is not valid JSON must fail loudly, not run with
// defaults (or report "no database config") as if the file were absent.
func TestRedactMasksEveryDSNPasswordForm(t *testing.T) {
@@ -66,6 +125,7 @@ func TestMalformedConfigIsAnError(t *testing.T) {
os.WriteFile(cfgPath, []byte(`{"database":{"host":"h","password":"a"b","dbname":"d"},"skill_dir":"/s"}`), 0o644)
t.Setenv("ARTEX_CONFIG", cfgPath)
t.Setenv("ARTEX_PG_DSN", "")
clearPGComponentEnv(t)
t.Setenv("ARTEX_SKILL_DIR", "")
if _, _, err := PostgresDSN(); err == nil || !strings.Contains(err.Error(), "parse config file") {
+3 -2
View File
@@ -102,8 +102,9 @@ func coordinateWithSchemaMigration(tx *sql.Tx) error {
}
// DSN resolves the PostgreSQL connection string and reports where it came from.
// Precedence: env ARTEX_PG_DSN > config file (config.json). There is no
// built-in default — it errors if neither source is configured.
// Precedence: env ARTEX_PG_DSN > ARTEX_PG_HOST/USER/PASSWORD/DBNAME > config
// file (config.json). There is no built-in default — it errors if no source
// is configured.
func DSN() (dsn, source string, err error) {
return config.PostgresDSN()
}
+5 -3
View File
@@ -282,12 +282,14 @@ func (d *DB) FinishFindingRetest(id int64, status, reason string) error {
return err
}
}
if finalStatus == "completed" {
if err := syncLessonsForFindingTx(context.Background(), tx, findingID); err != nil {
return err
}
}
if err := tx.Commit(); err != nil {
return err
}
if finalStatus == "completed" {
d.syncLessonsForFinding(context.Background(), findingID)
}
return nil
}
+30 -1
View File
@@ -750,7 +750,36 @@ func (d *DB) DeleteFindingsByTask(taskID int64) (int64, error) {
// do not care about notifications (parameter validation, retest flows) can
// drive the status on their own.
func (d *DB) SetFindingStatus(id int64, status string) (int64, error) {
return d.setFindingCol(id, "status", "status", status)
ctx := context.Background()
tx, err := d.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
var nodeID sql.NullInt64
err = tx.QueryRowContext(ctx, `UPDATE findings SET status=$1 WHERE id=$2 RETURNING node_id`, status, id).Scan(&nodeID)
if err == sql.ErrNoRows {
return 0, nil
}
if err != nil {
return 0, err
}
if nodeID.Valid {
if _, err := tx.ExecContext(ctx, `UPDATE exploration_nodes
SET payload = jsonb_set(payload, '{status}', to_jsonb($1::text))
WHERE id = $2`, status, nodeID.Int64); err != nil {
return 0, err
}
if FindingStatusInvalidatesGoal(status) {
if err := reopenGoalsProvedByNodeTx(ctx, tx, nodeID.Int64); err != nil {
return 0, err
}
}
}
if err := tx.Commit(); err != nil {
return 0, err
}
return 1, nil
}
// SetFindingReportState updates one finding's report stage and mirrors it onto
+281
View File
@@ -0,0 +1,281 @@
package db
import (
"context"
"testing"
)
func TestFindingStatusReopensProvedGoals(t *testing.T) {
d := notifyTestDB(t)
ctx := context.Background()
newTaskWithProvedGoal := func(t *testing.T, label string) (taskID int64, es *ExplorationStore, findingID, findingNodeID, goalID int64) {
t.Helper()
task, err := d.CreateTaskWithOptions("reopen-"+label, "goal "+label, TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
es = d.Exploration(task.ExplorationID)
goalID, err = es.AddNode(KindGoal, map[string]any{"text": "prove " + label}, 0, "open", "goals", nil)
if err != nil {
t.Fatal(err)
}
rec, err := es.RecordFinding(ctx, RecordFindingInput{
TaskID: task.ID,
ExplorationID: task.ExplorationID,
VulnClass: "sqli",
Name: "finding " + label,
Severity: "high",
Summary: "summary " + label,
Worker: "worker-1",
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM rsi_lessons WHERE id IN (SELECT lesson_id FROM rsi_lesson_evidence WHERE source_kind='finding' AND source_id=$1)`, rec.FindingID)
})
if err := es.Link(rec.NodeID, RelProves, goalID); err != nil {
t.Fatal(err)
}
if err := es.SetNodeState(goalID, "met"); err != nil {
t.Fatal(err)
}
return task.ID, es, rec.FindingID, rec.NodeID, goalID
}
assertGoalState := func(t *testing.T, es *ExplorationStore, goalID int64, want string) {
t.Helper()
n, err := es.GetNode(goalID)
if err != nil || n == nil {
t.Fatalf("GetNode(%d): %v", goalID, err)
}
if n.State != want {
t.Fatalf("goal %d state = %q, want %q", goalID, n.State, want)
}
}
assertProvesEdgeKept := func(t *testing.T, fromID, toID int64) {
t.Helper()
var cnt int
if err := d.QueryRow(`SELECT COUNT(*) FROM exploration_edges WHERE src_id=$1 AND dst_id=$2 AND rel=$3`, fromID, toID, RelProves).Scan(&cnt); err != nil {
t.Fatal(err)
}
if cnt != 1 {
t.Fatalf("proves edge (%d -> %d) count = %d, want 1 (must be preserved for history)", fromID, toID, cnt)
}
}
goalContentVersion := func(t *testing.T, goalID int64) int {
t.Helper()
var v int
if err := d.QueryRow(`SELECT content_version FROM exploration_nodes WHERE id=$1`, goalID).Scan(&v); err != nil {
t.Fatalf("SELECT content_version(%d): %v", goalID, err)
}
return v
}
t.Run("single_status_path_reopens_for_fp_duplicate_ignored", func(t *testing.T) {
for _, status := range []string{FindingFalsePositive, FindingDuplicate, FindingIgnored} {
t.Run(status, func(t *testing.T) {
_, es, fid, fnid, gid := newTaskWithProvedGoal(t, "single-"+status)
vBefore := goalContentVersion(t, gid)
_, found, _, err := d.SetFindingStatusWithNotify(ctx, fid, status)
if err != nil || !found {
t.Fatalf("SetFindingStatusWithNotify(%s): found=%v err=%v", status, found, err)
}
assertGoalState(t, es, gid, "open")
if vAfter := goalContentVersion(t, gid); vAfter != vBefore+1 {
t.Fatalf("goal %d content_version = %d, want %d (bumped on reopen)", gid, vAfter, vBefore+1)
}
assertProvesEdgeKept(t, fnid, gid)
})
}
})
t.Run("bulk_status_path_reopens_all_proved_goals", func(t *testing.T) {
_, es1, fid1, fnid1, gid1 := newTaskWithProvedGoal(t, "bulk-1")
_, es2, fid2, fnid2, gid2 := newTaskWithProvedGoal(t, "bulk-2")
res, err := d.SetFindingStatusesWithNotify(ctx, []int64{fid1, fid2}, FindingFalsePositive)
if err != nil || len(res) != 2 {
t.Fatalf("SetFindingStatusesWithNotify: res=%+v err=%v", res, err)
}
assertGoalState(t, es1, gid1, "open")
assertGoalState(t, es2, gid2, "open")
assertProvesEdgeKept(t, fnid1, gid1)
assertProvesEdgeKept(t, fnid2, gid2)
})
t.Run("retest_path_uses_same_tx_semantics", func(t *testing.T) {
_, es, fid, fnid, gid := newTaskWithProvedGoal(t, "retest")
// Retest concluding "fixed" calls SetFindingStatusTx(FindingFixed): goal stays met.
rt, conv, _, err := d.CreateFindingRetest(ctx, fid, "test")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM rsi_lessons WHERE id IN (SELECT lesson_id FROM rsi_lesson_evidence WHERE source_kind='retest' AND source_id=$1)`, rt.ID)
_ = d.DeleteConversation(conv.ID)
})
if _, err := d.StartFindingRetest(ctx, rt.ID); err != nil {
t.Fatal(err)
}
if err := d.RecordFindingRetestResult(ctx, conv.ID, "fixed", "patched", "verified 403"); err != nil {
t.Fatal(err)
}
if err := d.FinishFindingRetest(rt.ID, "completed", ""); err != nil {
t.Fatal(err)
}
assertGoalState(t, es, gid, "met")
// In-transaction rollback check: SetFindingStatusTx(FindingFalsePositive) reopens inside
// the same tx, and rolling back the tx leaves the goal met.
tx, err := d.BeginTx(ctx, nil)
if err != nil {
t.Fatal(err)
}
if _, found, changed, _, err := SetFindingStatusTx(ctx, tx, fid, FindingFalsePositive); err != nil || !found || !changed {
tx.Rollback()
t.Fatalf("SetFindingStatusTx: found=%v changed=%v err=%v", found, changed, err)
}
var stateInTx string
if err := tx.QueryRowContext(ctx, `SELECT state FROM exploration_nodes WHERE id=$1`, gid).Scan(&stateInTx); err != nil {
tx.Rollback()
t.Fatal(err)
}
if stateInTx != "open" {
tx.Rollback()
t.Fatalf("goal state inside tx = %q, want open", stateInTx)
}
_ = tx.Rollback()
assertGoalState(t, es, gid, "met")
assertProvesEdgeKept(t, fnid, gid)
})
t.Run("finding_that_never_proved_a_goal_does_not_touch_other_goals", func(t *testing.T) {
taskID, es, _, fnid1, gid1 := newTaskWithProvedGoal(t, "unlinked")
rec2, err := es.RecordFinding(ctx, RecordFindingInput{
TaskID: taskID,
ExplorationID: es.ID(),
VulnClass: "xss",
Name: "unlinked finding",
Severity: "medium",
Summary: "never proved any goal",
Worker: "worker-1",
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM rsi_lessons WHERE id IN (SELECT lesson_id FROM rsi_lesson_evidence WHERE source_kind='finding' AND source_id=$1)`, rec2.FindingID)
})
if _, found, _, err := d.SetFindingStatusWithNotify(ctx, rec2.FindingID, FindingFalsePositive); err != nil || !found {
t.Fatalf("SetFindingStatusWithNotify(unlinked): found=%v err=%v", found, err)
}
assertGoalState(t, es, gid1, "met")
assertProvesEdgeKept(t, fnid1, gid1)
})
t.Run("risk_accepted_keeps_proved_goal_met", func(t *testing.T) {
_, es, fid, fnid, gid := newTaskWithProvedGoal(t, "risk-accepted")
if _, found, _, err := d.SetFindingStatusWithNotify(ctx, fid, FindingRiskAccepted); err != nil || !found {
t.Fatalf("SetFindingStatusWithNotify(risk_accepted): found=%v err=%v", found, err)
}
assertGoalState(t, es, gid, "met")
assertProvesEdgeKept(t, fnid, gid)
})
t.Run("stays_met_when_another_valid_finding_proves_goal", func(t *testing.T) {
taskID, es, fidA, fnidA, gid := newTaskWithProvedGoal(t, "multi-finding-A")
recB, err := es.RecordFinding(ctx, RecordFindingInput{
TaskID: taskID,
ExplorationID: es.ID(),
VulnClass: "sqli",
Name: "finding B",
Severity: "high",
Summary: "independent confirmed finding",
Worker: "worker-2",
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM rsi_lessons WHERE id IN (SELECT lesson_id FROM rsi_lesson_evidence WHERE source_kind='finding' AND source_id=$1)`, recB.FindingID)
})
if _, found, _, err := d.SetFindingStatusWithNotify(ctx, recB.FindingID, FindingConfirmed); err != nil || !found {
t.Fatalf("confirm finding B: found=%v err=%v", found, err)
}
if err := es.Link(recB.NodeID, RelProves, gid); err != nil {
t.Fatal(err)
}
// Invalidating A while confirmed B still proves the goal must keep the goal met.
if _, found, _, err := d.SetFindingStatusWithNotify(ctx, fidA, FindingFalsePositive); err != nil || !found {
t.Fatalf("invalidate finding A: found=%v err=%v", found, err)
}
assertGoalState(t, es, gid, "met")
assertProvesEdgeKept(t, fnidA, gid)
assertProvesEdgeKept(t, recB.NodeID, gid)
// Once B is also invalidated, no valid proof remains and the goal reopens.
if _, found, _, err := d.SetFindingStatusWithNotify(ctx, recB.FindingID, FindingFalsePositive); err != nil || !found {
t.Fatalf("invalidate finding B: found=%v err=%v", found, err)
}
assertGoalState(t, es, gid, "open")
assertProvesEdgeKept(t, fnidA, gid)
assertProvesEdgeKept(t, recB.NodeID, gid)
})
t.Run("stays_met_when_observed_tool_output_fact_proves_goal", func(t *testing.T) {
_, es, fidA, fnidA, gid := newTaskWithProvedGoal(t, "finding-and-fact")
factID, err := es.AddNode(KindFact, map[string]any{
"summary": "admin shell confirmed",
"confidence": "observed",
"source": "tool_output",
"provenance": "activity_verified",
}, 0, "confirmed", "worker-1", nil)
if err != nil {
t.Fatal(err)
}
if err := es.Link(factID, RelProves, gid); err != nil {
t.Fatal(err)
}
if _, found, _, err := d.SetFindingStatusWithNotify(ctx, fidA, FindingFalsePositive); err != nil || !found {
t.Fatalf("invalidate finding A: found=%v err=%v", found, err)
}
assertGoalState(t, es, gid, "met")
assertProvesEdgeKept(t, fnidA, gid)
assertProvesEdgeKept(t, factID, gid)
})
t.Run("reopens_when_remaining_fact_fails_prove_goal_gate", func(t *testing.T) {
cases := []struct {
name string
payload map[string]any
}{
{"inferred_fact", map[string]any{"summary": "guess", "confidence": "inferred", "source": "tool_output"}},
{"target_response_fact", map[string]any{"summary": "banner", "confidence": "observed", "source": "target_response"}},
{"unverified_fact", map[string]any{"summary": "paraphrase", "confidence": "observed", "source": "tool_output", "provenance": "unverified"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, es, fidA, fnidA, gid := newTaskWithProvedGoal(t, "invalid-fact-"+tc.name)
factID, err := es.AddNode(KindFact, tc.payload, 0, "confirmed", "worker-1", nil)
if err != nil {
t.Fatal(err)
}
if err := es.Link(factID, RelProves, gid); err != nil {
t.Fatal(err)
}
if _, found, _, err := d.SetFindingStatusWithNotify(ctx, fidA, FindingFalsePositive); err != nil || !found {
t.Fatalf("invalidate finding A: found=%v err=%v", found, err)
}
assertGoalState(t, es, gid, "open")
assertProvesEdgeKept(t, fnidA, gid)
assertProvesEdgeKept(t, factID, gid)
})
}
})
}
+135 -52
View File
@@ -6,8 +6,8 @@ import (
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"unicode/utf8"
)
@@ -63,9 +63,39 @@ func lessonDedupeKey(kind string, categoryID, companyID int64, cue, action strin
return hex.EncodeToString(sum[:])
}
func taskLessonScope(ctx context.Context, d *DB, taskID int64) (categoryID int64, companyIDs []int64, err error) {
type sqlExecQuerier interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
// lessonSyncTxTestHook is nil in production; tests set it to inject an
// extraction failure inside a status or retest transaction.
var lessonSyncTxTestHook func(ctx context.Context, tx *sql.Tx, taskID int64) error
func taskCompanyIDsQ(ctx context.Context, q sqlExecQuerier, taskID int64) ([]int64, error) {
rows, err := q.QueryContext(ctx, `
SELECT company_id FROM task_scope
WHERE task_id=$1 AND kind='company' AND company_id IS NOT NULL
ORDER BY id`, taskID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
out = append(out, id)
}
return out, rows.Err()
}
func taskLessonScopeQ(ctx context.Context, q sqlExecQuerier, taskID int64) (categoryID int64, companyIDs []int64, err error) {
var cat sql.NullInt64
err = d.QueryRowContext(ctx,
err = q.QueryRowContext(ctx,
`SELECT category_id FROM tasks WHERE id=$1 AND deleted_at IS NULL`, taskID).
Scan(&cat)
if err != nil {
@@ -74,7 +104,7 @@ func taskLessonScope(ctx context.Context, d *DB, taskID int64) (categoryID int64
if cat.Valid {
categoryID = cat.Int64
}
companyIDs, err = d.TaskCompanyIDsContext(ctx, taskID)
companyIDs, err = taskCompanyIDsQ(ctx, q, taskID)
if err != nil {
return 0, nil, err
}
@@ -84,6 +114,10 @@ func taskLessonScope(ctx context.Context, d *DB, taskID int64) (categoryID int64
return categoryID, companyIDs, nil
}
func taskLessonScope(ctx context.Context, d *DB, taskID int64) (categoryID int64, companyIDs []int64, err error) {
return taskLessonScopeQ(ctx, d.DB, taskID)
}
// lessonExtractCompanyID is the company written onto a new lesson. The row has
// one company_id. Scope only when the task has exactly one company. Zero
// companies → generic (NULL). ExtractLessonsForTask still retracts when there
@@ -107,7 +141,22 @@ func lessonExtractCompanyID(companyIDs []int64) int64 {
// not gain a lesson, but a reversed disposition still withdraws evidence written
// while it had one company. Returns the number of distinct lessons written.
func (d *DB) ExtractLessonsForTask(ctx context.Context, taskID int64) (int, error) {
categoryID, companyIDs, err := taskLessonScope(ctx, d, taskID)
return extractLessonsForTaskQ(ctx, d.DB, taskID)
}
// ExtractLessonsForTaskTx runs lesson extraction/retraction inside the caller's
// transaction so status changes and lesson updates commit or roll back together.
func ExtractLessonsForTaskTx(ctx context.Context, tx *sql.Tx, taskID int64) (int, error) {
if lessonSyncTxTestHook != nil {
if err := lessonSyncTxTestHook(ctx, tx, taskID); err != nil {
return 0, err
}
}
return extractLessonsForTaskQ(ctx, tx, taskID)
}
func extractLessonsForTaskQ(ctx context.Context, q sqlExecQuerier, taskID int64) (int, error) {
categoryID, companyIDs, err := taskLessonScopeQ(ctx, q, taskID)
if err != nil {
return 0, err
}
@@ -117,7 +166,18 @@ func (d *DB) ExtractLessonsForTask(ctx context.Context, taskID int64) (int, erro
companyID := lessonExtractCompanyID(companyIDs)
// Only a completed retest with a verdict is an outcome. A pending, running,
// failed or stopped retest can carry a staged verdict that never finished.
rows, err := d.QueryContext(ctx, `
// Buffer rows before writing so a single-connection *sql.Tx is never busy.
type findingRow struct {
findingID int64
vulnclass string
name string
summary string
severity string
status string
retestID int64
verdict string
}
rows, err := q.QueryContext(ctx, `
SELECT f.id, f.vulnclass, f.name, f.summary, f.severity, f.status,
COALESCE(r.id,0), COALESCE(r.verdict,'')
FROM findings f
@@ -131,16 +191,25 @@ func (d *DB) ExtractLessonsForTask(ctx context.Context, taskID int64) (int, erro
if err != nil {
return 0, err
}
defer rows.Close()
touched := map[int64]bool{}
var findings []findingRow
for rows.Next() {
var findingID int64
var vulnclass, name, summary, severity, status, verdict string
var retestID int64
if err := rows.Scan(&findingID, &vulnclass, &name, &summary, &severity, &status, &retestID, &verdict); err != nil {
var fr findingRow
if err := rows.Scan(&fr.findingID, &fr.vulnclass, &fr.name, &fr.summary, &fr.severity, &fr.status, &fr.retestID, &fr.verdict); err != nil {
rows.Close()
return 0, err
}
findings = append(findings, fr)
}
if err := rows.Err(); err != nil {
rows.Close()
return 0, err
}
rows.Close()
touched := map[int64]bool{}
for _, fr := range findings {
findingID, vulnclass, name, summary, severity, status, retestID, verdict :=
fr.findingID, fr.vulnclass, fr.name, fr.summary, fr.severity, fr.status, fr.retestID, fr.verdict
cue := lessonText(vulnclass, lessonCueMax)
if cue == "" {
cue = lessonText(name, lessonCueMax)
@@ -162,17 +231,16 @@ func (d *DB) ExtractLessonsForTask(ctx context.Context, taskID int64) (int, erro
if cue == "" || action == "" || sourceID == 0 {
return nil // evidence gate: no write without cue + action + source
}
id, err := d.upsertLesson(ctx, lessonDedupeKey(kind, categoryID, companyID, cue, action),
id, err := upsertLessonQ(ctx, q, lessonDedupeKey(kind, categoryID, companyID, cue, action),
kind, cue, action, categoryID, companyID)
if err != nil {
return err
}
if _, err := d.ExecContext(ctx, `
if _, err := q.ExecContext(ctx, `
INSERT INTO rsi_lesson_evidence(lesson_id,source_kind,source_id,detail)
VALUES($1,$2,$3,$4)
ON CONFLICT (lesson_id, source_kind, source_id) DO UPDATE SET
detail=EXCLUDED.detail,
withdrawn_at=NULL`,
ON CONFLICT (lesson_id, source_kind, source_id) WHERE withdrawn_at IS NULL
DO UPDATE SET detail=EXCLUDED.detail`,
id, sourceKind, sourceID, lessonText(detail, lessonDetailMax)); err != nil {
return err
}
@@ -200,7 +268,7 @@ func (d *DB) ExtractLessonsForTask(ctx context.Context, taskID int64) (int, erro
}
}
}
if err := d.retractLessonEvidence(ctx, "finding", findingID, "negative", ""); err != nil {
if err := retractLessonEvidenceQ(ctx, q, "finding", findingID, "negative", ""); err != nil {
return 0, err
}
case "false_positive", "duplicate", "ignored", "risk_accepted":
@@ -218,7 +286,7 @@ func (d *DB) ExtractLessonsForTask(ctx context.Context, taskID int64) (int, erro
suffix := " (prior " + status + ")"
room := lessonActionMax - utf8.RuneCountInString(prefix) - utf8.RuneCountInString(suffix)
action := prefix + lessonText(label, room) + suffix
if err := d.retractLessonEvidence(ctx, "finding", findingID, "negative", lessonText(action, lessonActionMax)); err != nil {
if err := retractLessonEvidenceQ(ctx, q, "finding", findingID, "negative", lessonText(action, lessonActionMax)); err != nil {
return 0, err
}
if write {
@@ -226,23 +294,23 @@ func (d *DB) ExtractLessonsForTask(ctx context.Context, taskID int64) (int, erro
return 0, err
}
}
if err := d.retractLessonEvidence(ctx, "finding", findingID, "positive", ""); err != nil {
if err := retractLessonEvidenceQ(ctx, q, "finding", findingID, "positive", ""); err != nil {
return 0, err
}
if err := d.retractFindingRetestEvidence(ctx, findingID, "positive"); err != nil {
if err := retractFindingRetestEvidenceQ(ctx, q, findingID, "positive"); err != nil {
return 0, err
}
if err := d.retractFindingRetestEvidence(ctx, findingID, "caution"); err != nil {
if err := retractFindingRetestEvidenceQ(ctx, q, findingID, "caution"); err != nil {
return 0, err
}
}
}
return len(touched), rows.Err()
return len(touched), nil
}
func (d *DB) upsertLesson(ctx context.Context, key, kind, cue, action string, categoryID, companyID int64) (int64, error) {
func upsertLessonQ(ctx context.Context, q sqlExecQuerier, key, kind, cue, action string, categoryID, companyID int64) (int64, error) {
var id int64
err := d.QueryRowContext(ctx, `
err := q.QueryRowContext(ctx, `
INSERT INTO rsi_lessons(dedupe_key,kind,cue,action,category_id,company_id)
VALUES($1,$2,$3,$4,NULLIF($5,0),NULLIF($6,0))
ON CONFLICT (dedupe_key) DO UPDATE SET
@@ -260,14 +328,14 @@ func (d *DB) upsertLesson(ctx context.Context, key, kind, cue, action string, ca
return id, err
}
// retractLessonEvidence withdraws this source from lessons of fromKind and
// retractLessonEvidenceQ withdraws this source from lessons of fromKind and
// retires any of those lessons that now have zero live evidence. The row stays,
// with withdrawn_at set, so the lesson still names what it rested on. Shared
// lessons that still have other live evidence stay active. A non-empty
// keepAction spares lessons with that action, compared without case as the
// dedupe key does.
func (d *DB) retractLessonEvidence(ctx context.Context, sourceKind string, sourceID int64, fromKind, keepAction string) error {
rows, err := d.QueryContext(ctx, `
func retractLessonEvidenceQ(ctx context.Context, q sqlExecQuerier, sourceKind string, sourceID int64, fromKind, keepAction string) error {
rows, err := q.QueryContext(ctx, `
UPDATE rsi_lesson_evidence e
SET withdrawn_at=now()
FROM rsi_lessons l
@@ -285,13 +353,13 @@ func (d *DB) retractLessonEvidence(ctx context.Context, sourceKind string, sourc
if err != nil {
return err
}
return d.retireLessonsIfEmpty(ctx, ids)
return retireLessonsIfEmptyQ(ctx, q, ids)
}
// retractFindingRetestEvidence withdraws every retest of this finding from
// retractFindingRetestEvidenceQ withdraws every retest of this finding from
// lessons of fromKind, not only the latest row.
func (d *DB) retractFindingRetestEvidence(ctx context.Context, findingID int64, fromKind string) error {
rows, err := d.QueryContext(ctx, `
func retractFindingRetestEvidenceQ(ctx context.Context, q sqlExecQuerier, findingID int64, fromKind string) error {
rows, err := q.QueryContext(ctx, `
UPDATE rsi_lesson_evidence e
SET withdrawn_at=now()
FROM rsi_lessons l, finding_retests r
@@ -309,7 +377,7 @@ func (d *DB) retractFindingRetestEvidence(ctx context.Context, findingID int64,
if err != nil {
return err
}
return d.retireLessonsIfEmpty(ctx, ids)
return retireLessonsIfEmptyQ(ctx, q, ids)
}
func collectLessonIDs(rows *sql.Rows) ([]int64, error) {
@@ -332,11 +400,11 @@ func collectLessonIDs(rows *sql.Rows) ([]int64, error) {
return ids, nil
}
func (d *DB) retireLessonsIfEmpty(ctx context.Context, ids []int64) error {
func retireLessonsIfEmptyQ(ctx context.Context, q sqlExecQuerier, ids []int64) error {
if len(ids) == 0 {
return nil
}
_, err := d.ExecContext(ctx, `
_, err := q.ExecContext(ctx, `
UPDATE rsi_lessons l
SET status='retired', updated_at=now()
WHERE l.id=ANY($1::bigint[])
@@ -424,32 +492,47 @@ func (d *DB) LogLessonUsage(ctx context.Context, taskID int64, lessonIDs []int64
return nil
}
// syncLessonsForFinding re-runs extraction for the finding's task after a
// disposition or retest has committed. A failure is logged and does not undo
// the status change. Terminal-status extraction still runs later.
func (d *DB) syncLessonsForFinding(ctx context.Context, findingID int64) {
// syncLessonsForFindingTx re-runs extraction for the finding's task inside the
// caller's transaction so a failure rolls back the status or retest change and
// never leaves a stale lesson selectable (#269).
func syncLessonsForFindingTx(ctx context.Context, tx *sql.Tx, findingID int64) error {
var taskID sql.NullInt64
err := d.QueryRowContext(ctx, `SELECT task_id FROM findings WHERE id=$1`, findingID).Scan(&taskID)
if err != nil || !taskID.Valid || taskID.Int64 == 0 {
return
err := tx.QueryRowContext(ctx, `SELECT task_id FROM findings WHERE id=$1`, findingID).Scan(&taskID)
if errors.Is(err, sql.ErrNoRows) {
return nil
}
if _, err := d.ExtractLessonsForTask(ctx, taskID.Int64); err != nil {
log.Printf("[rsi] lesson extraction failed for task %d: %v", taskID.Int64, err)
if err != nil {
return err
}
if !taskID.Valid || taskID.Int64 == 0 {
return nil
}
_, err = ExtractLessonsForTaskTx(ctx, tx, taskID.Int64)
return err
}
// syncLessonsForTasks re-runs extraction once per task.
func (d *DB) syncLessonsForTasks(ctx context.Context, taskIDs []int64) {
// syncLessonsForFindingsTx re-runs extraction once per distinct task for all
// changed findings inside the caller's transaction.
func syncLessonsForFindingsTx(ctx context.Context, tx *sql.Tx, findingIDs []int64) error {
seen := map[int64]bool{}
for _, taskID := range taskIDs {
if taskID == 0 || seen[taskID] {
for _, fid := range findingIDs {
var taskID sql.NullInt64
err := tx.QueryRowContext(ctx, `SELECT task_id FROM findings WHERE id=$1`, fid).Scan(&taskID)
if errors.Is(err, sql.ErrNoRows) {
continue
}
seen[taskID] = true
if _, err := d.ExtractLessonsForTask(ctx, taskID); err != nil {
log.Printf("[rsi] lesson extraction failed for task %d: %v", taskID, err)
if err != nil {
return err
}
if !taskID.Valid || taskID.Int64 == 0 || seen[taskID.Int64] {
continue
}
seen[taskID.Int64] = true
if _, err := ExtractLessonsForTaskTx(ctx, tx, taskID.Int64); err != nil {
return err
}
}
return nil
}
// RenderLessons builds the prompt block. The text is data, not instructions:
+222
View File
@@ -2,6 +2,8 @@ package db
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"testing"
@@ -1482,3 +1484,223 @@ func lessonStatusSupport(t *testing.T, d *DB, lessonID int64) (status string, su
}
return status, support
}
// Re-confirming a previously withdrawn finding must NOT clear withdrawn_at on
// the old evidence row: the withdrawal row stays for history and re-confirmation
// inserts a new live row (#269).
func TestReconfirmingFindingPreservesWithdrawalHistory(t *testing.T) {
d := notifyTestDB(t)
ctx := context.Background()
task, err := d.CreateTaskWithOptions("withdraw-history", "test withdrawal history", TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
es := d.Exploration(task.ExplorationID)
rec, err := es.RecordFinding(ctx, RecordFindingInput{
TaskID: task.ID,
ExplorationID: task.ExplorationID,
VulnClass: "ssrf",
Name: "SSRF on webhook",
Severity: "high",
Summary: "SSRF on webhook endpoint",
Worker: "worker-1",
})
if err != nil {
t.Fatal(err)
}
fid := rec.FindingID
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM rsi_lessons WHERE id IN (SELECT lesson_id FROM rsi_lesson_evidence WHERE source_kind='finding' AND source_id=$1)`, fid)
})
// 1. Confirm -> positive lesson created with 1 live evidence row.
if _, _, _, err := d.SetFindingStatusWithNotify(ctx, fid, FindingConfirmed); err != nil {
t.Fatal(err)
}
var lessonID, firstRowID int64
if err := d.QueryRow(`SELECT e.lesson_id, e.id
FROM rsi_lesson_evidence e JOIN rsi_lessons l ON l.id=e.lesson_id
WHERE l.kind='positive' AND e.source_kind='finding' AND e.source_id=$1 AND e.withdrawn_at IS NULL`,
fid).Scan(&lessonID, &firstRowID); err != nil {
t.Fatalf("positive evidence row: %v", err)
}
// 2. Flip to false_positive -> firstRowID gets withdrawn_at set.
if _, _, _, err := d.SetFindingStatusWithNotify(ctx, fid, FindingFalsePositive); err != nil {
t.Fatal(err)
}
var withdrawnAt1 sql.NullTime
if err := d.QueryRow(`SELECT withdrawn_at FROM rsi_lesson_evidence WHERE id=$1`, firstRowID).Scan(&withdrawnAt1); err != nil {
t.Fatal(err)
}
if !withdrawnAt1.Valid {
t.Fatalf("expected firstRowID=%d to have withdrawn_at set after false_positive", firstRowID)
}
// 3. Re-confirm -> old withdrawal row stays untouched, new live row is inserted.
if _, _, _, err := d.SetFindingStatusWithNotify(ctx, fid, FindingConfirmed); err != nil {
t.Fatal(err)
}
var withdrawnAt2 sql.NullTime
if err := d.QueryRow(`SELECT withdrawn_at FROM rsi_lesson_evidence WHERE id=$1`, firstRowID).Scan(&withdrawnAt2); err != nil {
t.Fatal(err)
}
if !withdrawnAt2.Valid || !withdrawnAt2.Time.Equal(withdrawnAt1.Time) {
t.Fatalf("old withdrawal row %d was altered: got %v, want %v", firstRowID, withdrawnAt2, withdrawnAt1)
}
var secondRowID int64
if err := d.QueryRow(`SELECT id FROM rsi_lesson_evidence
WHERE lesson_id=$1 AND source_kind='finding' AND source_id=$2 AND withdrawn_at IS NULL`,
lessonID, fid).Scan(&secondRowID); err != nil {
t.Fatalf("new live evidence row missing after re-confirm: %v", err)
}
if secondRowID == firstRowID {
t.Fatalf("re-confirm reused old row %d instead of inserting a new live row", firstRowID)
}
// 4. Repeat extraction is idempotent: still 1 live + 1 withdrawn row.
if _, err := d.ExtractLessonsForTask(ctx, task.ID); err != nil {
t.Fatal(err)
}
var totalRows, liveRows, withdrawnRows int
if err := d.QueryRow(`SELECT COUNT(*), COUNT(*) FILTER (WHERE withdrawn_at IS NULL), COUNT(*) FILTER (WHERE withdrawn_at IS NOT NULL)
FROM rsi_lesson_evidence WHERE lesson_id=$1 AND source_kind='finding' AND source_id=$2`,
lessonID, fid).Scan(&totalRows, &liveRows, &withdrawnRows); err != nil {
t.Fatal(err)
}
if totalRows != 2 || liveRows != 1 || withdrawnRows != 1 {
t.Fatalf("evidence rows = total %d live %d withdrawn %d, want 2 / 1 / 1", totalRows, liveRows, withdrawnRows)
}
if status, support := lessonStatusSupport(t, d, lessonID); status != "candidate" || support != 1 {
t.Fatalf("lesson status=%s support=%d, want candidate / 1", status, support)
}
}
// Lesson extraction now runs inside the same transaction as status changes and
// retest completion (#269). If extraction fails, the status / retest write
// rolls back atomically so the DB never ends up with a flipped finding status
// and a stale selectable lesson.
func TestLessonExtractionFailureRollsBackStatusAndRetest(t *testing.T) {
d := notifyTestDB(t)
ctx := context.Background()
task, err := d.CreateTaskWithOptions("lesson-tx-rollback", "test lesson extraction tx rollback", TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
es := d.Exploration(task.ExplorationID)
rec, err := es.RecordFinding(ctx, RecordFindingInput{
TaskID: task.ID,
ExplorationID: task.ExplorationID,
VulnClass: "sqli",
Name: "SQLi in filter",
Severity: "high",
Summary: "Boolean SQLi in filter param",
Worker: "worker-1",
})
if err != nil {
t.Fatal(err)
}
fid := rec.FindingID
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM rsi_lessons WHERE id IN (SELECT lesson_id FROM rsi_lesson_evidence WHERE source_kind='finding' AND source_id=$1)`, fid)
})
// Seed a confirmed finding and its positive lesson.
if _, _, _, err := d.SetFindingStatusWithNotify(ctx, fid, FindingConfirmed); err != nil {
t.Fatal(err)
}
var posLessonID int64
if err := d.QueryRow(`SELECT e.lesson_id
FROM rsi_lesson_evidence e JOIN rsi_lessons l ON l.id=e.lesson_id
WHERE l.kind='positive' AND e.source_kind='finding' AND e.source_id=$1 AND e.withdrawn_at IS NULL`,
fid).Scan(&posLessonID); err != nil {
t.Fatalf("positive lesson missing: %v", err)
}
injected := errors.New("injected lesson extraction failure")
prevHook := lessonSyncTxTestHook
t.Cleanup(func() { lessonSyncTxTestHook = prevHook })
// 1. Single status path: failure during lesson extraction rolls back status.
lessonSyncTxTestHook = func(ctx context.Context, tx *sql.Tx, taskID int64) error { return injected }
if _, _, _, err := d.SetFindingStatusWithNotify(ctx, fid, FindingFalsePositive); !errors.Is(err, injected) {
t.Fatalf("single status err=%v, want %v", err, injected)
}
f, err := d.GetFinding(fid)
if err != nil {
t.Fatal(err)
}
if f.Status != FindingConfirmed {
t.Fatalf("single status leaked %q after rollback, want %q", f.Status, FindingConfirmed)
}
if status, support := lessonStatusSupport(t, d, posLessonID); status != "candidate" || support != 1 {
t.Fatalf("positive lesson after single rollback: status=%s support=%d, want candidate / 1", status, support)
}
// 2. Bulk status path: failure during lesson extraction rolls back status.
if _, err := d.SetFindingStatusesWithNotify(ctx, []int64{fid}, FindingFalsePositive); !errors.Is(err, injected) {
t.Fatalf("bulk status err=%v, want %v", err, injected)
}
f, err = d.GetFinding(fid)
if err != nil {
t.Fatal(err)
}
if f.Status != FindingConfirmed {
t.Fatalf("bulk status leaked %q after rollback, want %q", f.Status, FindingConfirmed)
}
// 3. Retest path: failure during lesson extraction rolls back both retest
// completion and the finding status transition.
lessonSyncTxTestHook = nil
retest, conv, _, err := d.CreateFindingRetest(ctx, fid, "verify fix")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteConversation(conv.ID) })
if _, err := d.StartFindingRetest(ctx, retest.ID); err != nil {
t.Fatal(err)
}
if err := d.RecordFindingRetestResult(ctx, conv.ID, "fixed", "patched", "verified 400 on payload"); err != nil {
t.Fatal(err)
}
lessonSyncTxTestHook = func(ctx context.Context, tx *sql.Tx, taskID int64) error { return injected }
if err := d.FinishFindingRetest(retest.ID, "completed", ""); !errors.Is(err, injected) {
t.Fatalf("FinishFindingRetest err=%v, want %v", err, injected)
}
f, err = d.GetFinding(fid)
if err != nil {
t.Fatal(err)
}
if f.Status != FindingConfirmed {
t.Fatalf("retest status leaked %q after rollback, want %q", f.Status, FindingConfirmed)
}
var retestStatus string
if err := d.QueryRow(`SELECT status FROM finding_retests WHERE id=$1`, retest.ID).Scan(&retestStatus); err != nil {
t.Fatal(err)
}
if retestStatus == "completed" {
t.Fatalf("retest status committed %q despite lesson extraction rollback", retestStatus)
}
// 4. Once extraction succeeds, the status flip and lesson retirement commit together.
lessonSyncTxTestHook = nil
if _, _, _, err := d.SetFindingStatusWithNotify(ctx, fid, FindingFalsePositive); err != nil {
t.Fatal(err)
}
f, err = d.GetFinding(fid)
if err != nil {
t.Fatal(err)
}
if f.Status != FindingFalsePositive {
t.Fatalf("status=%q after retry, want %q", f.Status, FindingFalsePositive)
}
if status, support := lessonStatusSupport(t, d, posLessonID); status != "retired" || support != 0 {
t.Fatalf("positive lesson after FP commit: status=%s support=%d, want retired / 0", status, support)
}
}
+14 -5
View File
@@ -139,9 +139,10 @@ func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration {
}{{1, llmRecordsMigration}, {2, llmUsageMigration}, {3, "0003_task_scope_icp_index.sql"}, {4, "0004_llm_usage_ts_index.sql"},
{5, "0005_traffic_rewrite_rules.sql"}, {6, "0006_activity_outbox.sql"}, {7, "0007_finding_report_state.sql"},
{8, "0008_traffic_evidence_rewrite_flag.sql"}, {9, "0009_llm_context.sql"}, {10, "0010_dashboard_usage_indexes.sql"},
{11, "0011_traffic_tamper_hooks.sql"}, {12, "0012_lesson_withdrawn.sql"}}
{11, "0011_traffic_tamper_hooks.sql"}, {12, "0012_lesson_withdrawn.sql"},
{13, "0013_lesson_evidence_history.sql"}}
if len(applied) != len(want) {
t.Fatalf("schema_migrations = %+v, want versions 1 to 12", applied)
t.Fatalf("schema_migrations = %+v, want versions 1 to 13", applied)
}
for i, w := range want {
content, err := fs.ReadFile(migrationsFS(), w.name)
@@ -432,10 +433,11 @@ func TestLessonWithdrawnMigrationKeepsExistingEvidence(t *testing.T) {
}
// The migration file alone adds the column to a table without it.
for _, q := range []string{
`DROP INDEX IF EXISTS uq_rsi_lesson_evidence_live`,
`ALTER TABLE rsi_lesson_evidence DROP COLUMN withdrawn_at`,
string(migrationSQL),
`ALTER TABLE rsi_lesson_evidence DROP COLUMN withdrawn_at`,
`DELETE FROM schema_migrations WHERE version=12`,
`DELETE FROM schema_migrations WHERE version IN (12, 13)`,
`INSERT INTO rsi_lessons(dedupe_key,kind,cue,action,status)
VALUES ('legacy-lesson','positive','xss','Confirmed xss: legacy','adopted')`,
`INSERT INTO rsi_lesson_evidence(lesson_id,source_kind,source_id,detail)
@@ -479,8 +481,15 @@ func TestLessonWithdrawnMigrationKeepsExistingEvidence(t *testing.T) {
}
check(d)
before := readApplied(t, d)
if last := before[len(before)-1]; last.version != 12 || last.name != migrationName {
t.Fatalf("last applied migration = %+v, want 0012", last)
has12 := false
for _, m := range before {
if m.version == 12 && m.name == migrationName {
has12 = true
break
}
}
if !has12 {
t.Fatalf("applied migrations = %+v, missing 0012", before)
}
d.Close()
@@ -0,0 +1,22 @@
-- Keep withdrawal history on rsi_lesson_evidence (#269): replace the composite
-- primary key (lesson_id, source_kind, source_id) with a surrogate id and a
-- partial unique index over live rows (withdrawn_at IS NULL). Re-confirming a
-- previously withdrawn finding inserts a new live row while preserving the old
-- withdrawal row and its withdrawn_at timestamp.
ALTER TABLE rsi_lesson_evidence ADD COLUMN IF NOT EXISTS id BIGSERIAL;
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM pg_constraint
WHERE conrelid = 'rsi_lesson_evidence'::regclass
AND contype = 'p'
AND conname = 'rsi_lesson_evidence_pkey'
AND array_length(conkey, 1) > 1
) THEN
ALTER TABLE rsi_lesson_evidence DROP CONSTRAINT rsi_lesson_evidence_pkey;
ALTER TABLE rsi_lesson_evidence ADD PRIMARY KEY (id);
END IF;
END $$;
CREATE UNIQUE INDEX IF NOT EXISTS uq_rsi_lesson_evidence_live
ON rsi_lesson_evidence(lesson_id, source_kind, source_id)
WHERE withdrawn_at IS NULL;
+89 -19
View File
@@ -502,15 +502,19 @@ func assetDisplayName(typ, domain, ip, url, appName, bundleID string) string {
// already succeeded and the caller must not report an error for it.
func (d *DB) SetFindingStatusWithNotify(ctx context.Context, id int64, status string) (from string, found bool, notified bool, err error) {
err = d.WithEvidenceTx(ctx, func(tx *sql.Tx) error {
var changed bool
var txErr error
from, found, _, notified, txErr = SetFindingStatusTx(ctx, tx, id, status)
return txErr
from, found, changed, notified, txErr = SetFindingStatusTx(ctx, tx, id, status)
if txErr != nil {
return txErr
}
if found && changed {
return syncLessonsForFindingTx(ctx, tx, id)
}
return nil
})
if err != nil {
return from, found, notified, err
}
if found && from != status {
d.syncLessonsForFinding(ctx, id)
return from, found, false, err
}
return from, found, notified, nil
}
@@ -532,33 +536,94 @@ type FindingStatusBatchResult struct {
func (d *DB) SetFindingStatusesWithNotify(ctx context.Context, ids []int64, status string) ([]FindingStatusBatchResult, error) {
out := make([]FindingStatusBatchResult, 0, len(ids))
err := d.WithEvidenceTx(ctx, func(tx *sql.Tx) error {
changedIDs := make([]int64, 0, len(ids))
for _, id := range ids {
from, found, changed, notified, err := SetFindingStatusTx(ctx, tx, id, status)
if err != nil {
return err
}
if changed {
changedIDs = append(changedIDs, id)
}
out = append(out, FindingStatusBatchResult{ID: id, From: from, Found: found, Changed: changed, Notified: notified})
}
return nil
return syncLessonsForFindingsTx(ctx, tx, changedIDs)
})
if err != nil {
return nil, err
}
taskIDs := make([]int64, 0, len(out))
for _, r := range out {
if !r.Changed {
continue
}
var taskID sql.NullInt64
if err := d.QueryRowContext(ctx, `SELECT task_id FROM findings WHERE id=$1`, r.ID).Scan(&taskID); err != nil || !taskID.Valid {
continue
}
taskIDs = append(taskIDs, taskID.Int64)
}
d.syncLessonsForTasks(ctx, taskIDs)
return out, nil
}
// GoalInvalidatingFindingStatuses is the single source of truth for finding
// triage statuses that mean "not a valid vulnerability" and therefore cannot
// prove or keep a goal met (#269). Both db goal-reopen logic and agent
// prove_goal checks use this list so they cannot drift.
//
// FindingRiskAccepted is deliberately excluded: it represents a real finding
// whose risk is accepted, not an invalid one, so it may prove a goal and must
// never reopen one.
var GoalInvalidatingFindingStatuses = []string{
FindingFalsePositive,
FindingDuplicate,
FindingIgnored,
}
// FindingStatusInvalidatesGoal reports whether a finding disposition means the
// finding is not a valid vulnerability and therefore cannot prove or keep a
// goal met.
func FindingStatusInvalidatesGoal(status string) bool {
s := strings.ToLower(strings.TrimSpace(status))
for _, inv := range GoalInvalidatingFindingStatuses {
if s == inv {
return true
}
}
return false
}
// reopenGoalsProvedByNodeTx resets any goal node proved by nodeID back to open
// inside the caller's transaction, unless another valid proof still exists for
// that goal (a finding whose status is not in GoalInvalidatingFindingStatuses,
// or an observed non-target_response non-unverified fact matching prove_goal's
// gate). All proves edges are preserved for history; only the goal state changes.
func reopenGoalsProvedByNodeTx(ctx context.Context, tx *sql.Tx, nodeID int64) error {
_, err := tx.ExecContext(ctx, `
UPDATE exploration_nodes g
SET state = 'open',
blocked_reason = NULL,
content_version = content_version + 1
FROM exploration_edges e
WHERE e.src_id = $1
AND e.rel = $2
AND g.id = e.dst_id
AND g.kind = $3
AND g.state = 'met'
AND NOT EXISTS (
SELECT 1
FROM exploration_edges pe
JOIN exploration_nodes src ON src.id = pe.src_id
WHERE pe.dst_id = g.id
AND pe.rel = $2
AND src.id <> $1
AND (
(src.kind = $4 AND EXISTS (
SELECT 1
FROM findings f
WHERE f.node_id = src.id
AND NOT (LOWER(BTRIM(f.status)) = ANY($6::text[]))
))
OR
(src.kind = $5
AND LOWER(BTRIM(COALESCE(src.payload->>'confidence', ''))) = 'observed'
AND LOWER(BTRIM(COALESCE(src.payload->>'source', ''))) <> 'target_response'
AND LOWER(BTRIM(COALESCE(src.payload->>'provenance', ''))) <> 'unverified')
)
)`,
nodeID, RelProves, KindGoal, KindFinding, KindFact, GoalInvalidatingFindingStatuses)
return err
}
// SetFindingStatusTx updates a finding's status and registers a status-change delivery
// event inside the **caller's transaction**.
//
@@ -602,6 +667,11 @@ FROM findings WHERE id=$1 FOR UPDATE`, id).
WHERE id = $2`, status, nodeID.Int64); err != nil {
return from, true, false, false, err
}
if FindingStatusInvalidatesGoal(status) {
if err := reopenGoalsProvedByNodeTx(ctx, tx, nodeID.Int64); err != nil {
return from, true, false, false, err
}
}
}
var assets []int64
_ = json.Unmarshal(assetIDs, &assets)
+8 -6
View File
@@ -1560,19 +1560,21 @@ CREATE TABLE IF NOT EXISTS rsi_lessons (
CREATE INDEX IF NOT EXISTS idx_rsi_lessons_scope ON rsi_lessons(company_id, category_id, status);
CREATE INDEX IF NOT EXISTS idx_rsi_lessons_kind ON rsi_lessons(kind, updated_at DESC);
-- One row per (lesson, source). The primary key makes extraction idempotent:
-- a second run for the same task adds nothing and cannot inflate support.
-- withdrawn_at keeps a retracted source on the row. Support and selection
-- count only rows that are still live.
-- Live evidence is unique per (lesson, source) via uq_rsi_lesson_evidence_live,
-- making repeated extraction idempotent without inflating support. Withdrawn
-- rows keep withdrawn_at set for history; re-confirming inserts a new live row.
CREATE TABLE IF NOT EXISTS rsi_lesson_evidence (
id BIGSERIAL PRIMARY KEY,
lesson_id BIGINT NOT NULL REFERENCES rsi_lessons(id) ON DELETE CASCADE,
source_kind TEXT NOT NULL,
source_id BIGINT NOT NULL,
detail TEXT NOT NULL DEFAULT '',
withdrawn_at TIMESTAMPTZ,
PRIMARY KEY (lesson_id, source_kind, source_id)
withdrawn_at TIMESTAMPTZ
);
ALTER TABLE rsi_lesson_evidence ADD COLUMN IF NOT EXISTS withdrawn_at TIMESTAMPTZ;
CREATE UNIQUE INDEX IF NOT EXISTS uq_rsi_lesson_evidence_live
ON rsi_lesson_evidence(lesson_id, source_kind, source_id)
WHERE withdrawn_at IS NULL;
-- What was shown to which task, and in which mode (shadow = logged but not
-- injected; inject = appended to the planner/worker system prompt).
+9 -1
View File
@@ -31,7 +31,15 @@ services:
postgres:
condition: service_healthy
environment:
ARTEX_PG_DSN: postgres://${POSTGRES_USER:-artex}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-artex}?sslmode=disable
# Parts, not a pasted URL. PostgresDSN percent-encodes the password, so a
# value with / ? % @ : or a space still connects. ARTEX_PG_DSN, when set,
# would override these and is responsible for its own escaping.
ARTEX_PG_HOST: postgres
ARTEX_PG_PORT: "5432"
ARTEX_PG_USER: ${POSTGRES_USER:-artex}
ARTEX_PG_PASSWORD: ${POSTGRES_PASSWORD:?Please set POSTGRES_PASSWORD in .env}
ARTEX_PG_DBNAME: ${POSTGRES_DB:-artex}
ARTEX_PG_SSLMODE: disable
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
OPENAI_API_KEY: ${OPENAI_API_KEY:-}
ARTEX_LLM_PROVIDER: ${ARTEX_LLM_PROVIDER:-}
+1 -1
View File
@@ -32,7 +32,7 @@ boundary and trusted proxies. No password or token value is ever logged there.
| Setting | Resolution order | Code |
| --- | --- | --- |
| Config file | `ARTEX_CONFIG` → `./config.json` → `config.json` next to the binary | `config.Path` |
| PostgreSQL DSN | `ARTEX_PG_DSN` → `database.dsn` → assembled `host/port/user/password/dbname` | `config.PostgresDSN` |
| PostgreSQL DSN | `ARTEX_PG_DSN` → `ARTEX_PG_HOST` / `ARTEX_PG_PORT` / `ARTEX_PG_USER` / `ARTEX_PG_PASSWORD` / `ARTEX_PG_DBNAME` / `ARTEX_PG_SSLMODE` → `database.dsn` → assembled `host/port/user/password/dbname` | `config.PostgresDSN` |
| Skill directory | `ARTEX_SKILL_DIR` → `skill_dir` → `<binary dir>/skills` | `config.SkillDir` |
| JWT / secret key directory | `ARTEX_JWT_KEY_DIR` → `<binary dir>` (never the browsable data dir) | `config.KeyDir` |
| Secret encryption key | `ARTEX_SECRET_KEY` → `<key dir>/secret.key` → newly generated key file | `db.InitSecrets` |
+50 -2
View File
@@ -29,8 +29,10 @@ ensure_docker(){
case "$(uname -s)" in
Linux)
if [ "$(ask 'Install Docker automatically? (y/n)' y)" = y ]; then
curl -fsSL https://get.docker.com | sh
install_docker_linux
sudo usermod -aG docker "$USER" || true
docker compose version >/dev/null 2>&1 || sudo docker compose version >/dev/null 2>&1 \
|| die "docker installed but 'docker compose' is unavailable; install the compose v2 plugin and retry"
ok "Docker installed (re-login required for the group change to take effect)"
else
die "please install docker yourself and retry"
@@ -40,6 +42,52 @@ ensure_docker(){
esac
}
# install_docker_linux uses get.docker.com only on the distros it supports. That
# script keys its repo URL off /etc/os-release ID + codename, so on derivatives
# such as Kali it writes a repo for a nonexistent release (debian kali-rolling)
# and leaves apt broken. Other apt-based distros get the distro's own packages.
install_docker_linux(){
local id="" id_like=""
if [ -r /etc/os-release ]; then
id="$(. /etc/os-release && echo "${ID:-}")"
id_like="$(. /etc/os-release && echo "${ID_LIKE:-}")"
fi
case "$id" in
ubuntu|debian|raspbian|centos|fedora|rhel|sles)
curl -fsSL https://get.docker.com | sh
return ;;
esac
command -v apt-get >/dev/null 2>&1 \
|| die "automatic Docker install is not supported on '${id:-unknown}'; please install docker + the compose plugin yourself and retry"
info "'${id:-unknown}' (like: ${id_like:-n/a}) is not supported by get.docker.com; installing from the distro's apt repos"
# Drop a broken repo left by an earlier get.docker.com run (it fails every apt update).
# Match the URI and the distro id anywhere in the file: in a one-line .list entry
# they share a line, but in a deb822 .sources file the URIs and Suites fields are
# on separate lines. -w keeps "kali" matching inside "kali-rolling".
local f
for f in /etc/apt/sources.list.d/docker.list /etc/apt/sources.list.d/docker.sources; do
if [ -n "$id" ] && [ -f "$f" ] \
&& grep -qF "download.docker.com/linux/debian" "$f" 2>/dev/null \
&& grep -qwF "$id" "$f" 2>/dev/null; then
warn "removing broken Docker repo $f"
sudo rm -f "$f"
fi
done
sudo apt-get update
sudo apt-get install -y docker.io
# The compose v2 package name varies across Debian derivatives; take the first that exists.
local p
for p in docker-compose-plugin docker-compose-v2 docker-compose; do
if apt-cache madison "$p" 2>/dev/null | grep -q .; then
sudo apt-get install -y "$p" && break
fi
done
# Kali (and some others) don't start services on package install.
if command -v systemctl >/dev/null 2>&1; then
sudo systemctl enable --now docker || true
fi
}
# ── 1) All-Docker ───────────────────────────────
install_docker(){
ensure_docker
@@ -107,7 +155,7 @@ JSON
if command -v npm >/dev/null 2>&1; then
info "building frontend static assets..."
( cd web && npm ci --ignore-scripts && npm run build:static )
rm -rf server/webui/dist && cp -r web/out server/webui/dist
rm -rf server/webui/dist && mkdir -p server/webui && cp -r web/out server/webui/dist
info "compiling embedded single binary..."
CGO_ENABLED=0 go build -tags embedui -trimpath -o artex ./cmd/artex
else
+1
View File
@@ -223,6 +223,7 @@ func seedPrompts(pg *db.DB) {
// and default params get injected. MCP/skill/host tools have no row and pass through.
func wireTools(pg *db.DB, domainReg map[string]actool.CoreTool) {
agent.SetFindingTrafficBindingEnabled(func() bool { return pg.GetBool(settingAgentTrafficBinding, false) })
agent.SetTrafficCaptureEnabled(func() bool { return pg.GetBool(settingTrafficCapture, false) })
// Seed the built-in domain tools (first-insert only; DO NOTHING preserves edits).
// No startup prune: rows we didn't seed are left alone so future user-defined
// custom tools (system=false, added via the UI) survive restarts.
+4 -2
View File
@@ -3,7 +3,9 @@ package server
import "os"
// secretEnv lists the credentials read from the environment only at startup:
// ARTEX_PG_DSN and ARTEX_SECRET_KEY by NewManager, the API keys by agent.FromEnv inside New.
// ARTEX_PG_DSN and ARTEX_PG_PASSWORD by NewManager (the password is a separate
// variable so Docker Compose does not paste it into a URL), ARTEX_SECRET_KEY,
// and the API keys by agent.FromEnv inside New.
// agent.FromEnv also reads ARTEX_LLM_PROXY and ARTEX_LLM_BASE_URL: both are URLs that
// can carry credentials in their userinfo (http://user:pass@proxy:3128). The archive
// store also captures ARTEX_ARCHIVE_S3_* credentials during New, before the scrub,
@@ -16,7 +18,7 @@ import "os"
// credentials or config file, or from the instance metadata service, are not in
// the environment: the scrub does not hide them from child processes.
var secretEnv = []string{
"ARTEX_PG_DSN", "ARTEX_SECRET_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY",
"ARTEX_PG_DSN", "ARTEX_PG_PASSWORD", "ARTEX_SECRET_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY",
"ARTEX_LLM_PROXY", "ARTEX_LLM_BASE_URL",
"ARTEX_ARCHIVE_S3_ACCESS_KEY_ID", "ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "ARTEX_ARCHIVE_S3_SESSION_TOKEN",
"AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY", "AWS_SECRET_KEY", "AWS_SESSION_TOKEN",
+3 -2
View File
@@ -13,8 +13,9 @@ import (
// Sealing the server environment. ScrubSecretEnv removes the secrets from the Go
// environment, but the kernel keeps the environment block the process was executed
// with: /proc/<pid>/environ still shows ARTEX_PG_DSN, ARTEX_SECRET_KEY and the API
// keys to any process that can read it. SealProcessEnv re-executes the server once,
// with: /proc/<pid>/environ still shows ARTEX_PG_DSN, ARTEX_PG_PASSWORD,
// ARTEX_SECRET_KEY and the API keys to any process that can read it.
// SealProcessEnv re-executes the server once,
// with those variables left out of the block; the values travel to the new image
// through an inherited pipe and are put back into the Go environment there, so the
// readers that run next see the same configuration.
+1
View File
@@ -51,6 +51,7 @@ func TestSealedEnvironmentHandoff(t *testing.T) {
}
want := map[string]string{
"ARTEX_PG_DSN": "postgres://artex:p@ss@db.internal/artex?sslmode=disable\nsecond line\twith tab",
"ARTEX_PG_PASSWORD": "p/ss w@rd?#%",
"ARTEX_SECRET_KEY": "",
"ANTHROPIC_API_KEY": "sk-ant-test",
"OPENAI_API_KEY": "=leading-equals",
+1 -1
View File
@@ -57,7 +57,7 @@ update_local(){
if command -v npm >/dev/null 2>&1; then
info "Rebuilding frontend static assets…"
( cd web && npm ci --ignore-scripts && npm run build:static )
rm -rf server/webui/dist && cp -r web/out server/webui/dist
rm -rf server/webui/dist && mkdir -p server/webui && cp -r web/out server/webui/dist
info "Recompiling the embedded single binary…"
CGO_ENABLED=0 go build -tags embedui -trimpath -o artex ./cmd/artex
else
+3
View File
@@ -139,6 +139,9 @@ export default function SetupPage() {
>
{loading ? t("Saving...") : t("Set password and sign in")}
</Button>
<p className="rounded-md border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
{t("Traffic capture is off by default. Enable it in System settings after setup if you need provable HTTP findings — captured traffic is required for findings to prove goals.")}
</p>
</form>
)}
</div>
+26 -14
View File
@@ -572,7 +572,9 @@ export default function DashboardPage() {
<span>{t("Recording")}</span>
</>
) : (
<span>{t("Capture is off")}</span>
<Link href="/system/settings" className="text-amber-500 hover:underline">
{t("Capture is off · required for provable findings")}
</Link>
)}
</CardContent>
</Card>
@@ -1164,19 +1166,29 @@ export default function DashboardPage() {
</Badge>
</div>
<div className="flex items-center justify-between rounded-lg border bg-muted/20 px-3 py-2">
<div className="text-[10px] text-muted-foreground">{t("Traffic capture")}</div>
<Badge
variant="outline"
className={cn(
"text-[10px]",
settings?.traffic_capture
? "border-violet-500/30 bg-violet-500/10 text-violet-400"
: "text-muted-foreground",
)}
>
{settings?.traffic_capture ? t("On") : t("Off")}
</Badge>
<div className="rounded-lg border bg-muted/20 px-3 py-2">
<div className="flex items-center justify-between">
<div className="text-[10px] text-muted-foreground">{t("Traffic capture")}</div>
<Badge
variant="outline"
className={cn(
"text-[10px]",
settings?.traffic_capture
? "border-violet-500/30 bg-violet-500/10 text-violet-400"
: "border-amber-500/30 bg-amber-500/10 text-amber-500",
)}
>
{settings?.traffic_capture ? t("On") : t("Off")}
</Badge>
</div>
{settings && !settings.traffic_capture && (
<p className="mt-1.5 text-[10px] leading-relaxed text-amber-500">
{t("Traffic capture is off: findings stay recorded, but captured HTTP traffic is required for provable findings.")}{" "}
<Link href="/system/settings" className="underline">
{t("Enable in settings")}
</Link>
</p>
)}
</div>
{activeProfile && (
+17 -10
View File
@@ -320,16 +320,23 @@ export default function SystemSettingsPage() {
)}
</CardDescription>
</CardHeader>
<CardContent className="flex items-center justify-between gap-4">
<Label htmlFor="traffic-capture" className="text-sm font-normal text-muted-foreground">
{trafficCapture ? t("On · recording traffic and injecting proxy") : t("Off · no recording, no proxy injection")}
</Label>
<Switch
id="traffic-capture"
checked={trafficCapture}
disabled={!loaded || saving}
onCheckedChange={toggleTraffic}
/>
<CardContent className="space-y-2.5">
<div className="flex items-center justify-between gap-4">
<Label htmlFor="traffic-capture" className="text-sm font-normal text-muted-foreground">
{trafficCapture ? t("On · recording traffic and injecting proxy") : t("Off · no recording, no proxy injection")}
</Label>
<Switch
id="traffic-capture"
checked={trafficCapture}
disabled={!loaded || saving}
onCheckedChange={toggleTraffic}
/>
</div>
{loaded && !trafficCapture && (
<p className="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-600 dark:text-amber-400">
{t("Traffic capture is off: findings stay recorded, but captured HTTP traffic is required for provable findings.")}
</p>
)}
</CardContent>
</Card>
+5 -1
View File
@@ -2709,5 +2709,9 @@
"Hashes": "Özetler",
"Masked (HMAC)": "Maskeli (HMAC)",
"Resulting request": "Ortaya çıkan istek",
"Resulting response": "Ortaya çıkan yanıt"
"Resulting response": "Ortaya çıkan yanıt",
"Traffic capture is off by default. Enable it in System settings after setup if you need provable HTTP findings — captured traffic is required for findings to prove goals.": "Trafik yakalama varsayılan olarak kapalıdır. Kanıtlanabilir HTTP bulguları gerekiyorsa kurulumdan sonra Sistem ayarlarından etkinleştirin — bulguların hedefleri kanıtlaması için yakalanmış trafik gereklidir.",
"Capture is off · required for provable findings": "Yakalama kapalı · kanıtlanabilir bulgular için gerekli",
"Traffic capture is off: findings stay recorded, but captured HTTP traffic is required for provable findings.": "Trafik yakalama kapalı: bulgular kaydedilmeye devam eder ancak kanıtlanabilir bulgular için yakalanmış HTTP trafiği gereklidir.",
"Enable in settings": "Ayarlardan etkinleştir"
}
+5 -1
View File
@@ -2709,5 +2709,9 @@
"Hashes": "哈希",
"Masked (HMAC)": "已脱敏 (HMAC)",
"Resulting request": "结果请求",
"Resulting response": "结果响应"
"Resulting response": "结果响应",
"Traffic capture is off by default. Enable it in System settings after setup if you need provable HTTP findings — captured traffic is required for findings to prove goals.": "流量捕获默认关闭。如需可证明的 HTTP 漏洞发现,请在初始化后前往系统设置开启——漏洞证明目标需要已捕获的 HTTP 流量。",
"Capture is off · required for provable findings": "捕获已关闭 · 可证明漏洞所需",
"Traffic capture is off: findings stay recorded, but captured HTTP traffic is required for provable findings.": "流量捕获已关闭:漏洞仍会被记录,但证明目标需要已捕获的 HTTP 流量。",
"Enable in settings": "前往设置开启"
}