mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 22:53:55 +08:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fadfa2e12 | ||
|
|
b43ce18d63 | ||
|
|
54df82114d | ||
|
|
5b70bab668 | ||
|
|
3c9366868b | ||
|
|
a0cb6cc2b7 | ||
|
|
2e78f528cc | ||
|
|
4bbf2129b8 | ||
|
|
82297a045f | ||
|
|
6956c412bc |
@@ -40,7 +40,6 @@ All notable changes to this project are documented in this file. The format is b
|
||||
### Added
|
||||
|
||||
- **The task page links to the task's files.** A folder button in the task header opens Workspace at `tasks/<id>`, where the task's agents write their output, instead of browsing there by hand. In the Sessions tab, a worker whose folder exists (`tasks/<id>/i<intent id>`) gets a folder button next to it that opens that folder.
|
||||
- **The task page links to the task's files.** A folder button in the task header opens Workspace at `tasks/<id>`, where the task's agents write their output, instead of browsing there by hand.
|
||||
- **The Workspace file sheet previews files.** Opening a file in Workspace now shows a Preview tab next to the editor: Markdown is rendered, JSON and HTML/XML are shown with line numbers and highlighting, other text with line numbers, and PNG, JPEG, GIF, WebP, BMP, ICO and AVIF images are shown inline (up to 10 MiB, fetched through `/api/workspace/download`). SVG is shown as source, never rendered. Text over 200,000 characters or 5,000 lines is shown as plain text so the page stays responsive; text over the server's 2 MiB read limit shows its last 256 KB, fetched with a `Range` request and scrolled to the end; binary files still offer a download. The sheet also gets the 672 px width it asked for: a Tailwind specificity clash held it at 384 px.
|
||||
|
||||
- **Kubernetes sandbox backend for `artex-runner`.** With `ARTEX_RUNNER_BACKEND=kubernetes` each task runs in a worker pod behind its own egress-proxy pod, created through the Kubernetes API with no container runtime socket. The worker runs as uid/gid 10001 with `runAsNonRoot`, a read-only root filesystem, all capabilities dropped, `seccomp: RuntimeDefault`, no service-account token and no service links, and mounts only its task directory. Per-task NetworkPolicies are created before the pods and deleted after them: the worker can reach only its own proxy, and the proxy only cluster DNS, public addresses and the task's scope CIDRs. No scope opens the cluster's own ranges, the API server or cloud metadata: set `ARTEX_KUBE_CLUSTER_CIDRS` to the pod, service and node CIDRs, plus the API server endpoint addresses when they lie outside them as on managed clusters (without it, private scope CIDRs are dropped). The runner waits until the policies are in effect before the first command, runs commands through `pods/exec`, and re-adopts task pods after a restart.
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func BenchmarkRedactCleanURL(b *testing.B) {
|
||||
dsn := "postgres://artex:secretpass@127.0.0.1:5432/artex?sslmode=disable"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if got := Redact(dsn); got == "" {
|
||||
b.Fatal("empty")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRedactTokenQuery(b *testing.B) {
|
||||
dsn := "postgres://artex:secretpass@127.0.0.1:5432/artex?sslmode=disable&token=abc123&api_key=xyz"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if got := Redact(dsn); got == "" {
|
||||
b.Fatal("empty")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRedactLibpq(b *testing.B) {
|
||||
dsn := "host=127.0.0.1 port=5432 user=artex password=secretpass dbname=artex sslmode=disable"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if got := Redact(dsn); got == "" {
|
||||
b.Fatal("empty")
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
-130
@@ -254,97 +254,18 @@ func (d Database) buildDSN() string {
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// isASCIIWord reports whether c matches regex \w ([A-Za-z0-9_]).
|
||||
func isASCIIWord(c byte) bool {
|
||||
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_'
|
||||
}
|
||||
|
||||
// hasNonASCII reports whether s holds a byte outside ASCII.
|
||||
func hasNonASCII(s string) bool {
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] >= 0x80 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// libpqPassword is the regexp keyword matcher. Unicode case folding can change a
|
||||
// keyword's byte length (ſ folds to s, the Kelvin sign K to k), which the byte
|
||||
// scanner below cannot model, so any input holding a non-ASCII byte uses it.
|
||||
// libpqPassword matches the libpq secret keywords: password, and sslpassword
|
||||
// (the passphrase of an encrypted client key), in any letter case.
|
||||
var libpqPassword = regexp.MustCompile(`(?i)\b((?:ssl)?password)\s*=\s*`)
|
||||
|
||||
// findLibpqPassword locates the next occurrence of (?i)\b((?:ssl)?password)\s*=\s*
|
||||
// in s, returning (start, keyEnd, valStart, ok). ASCII input takes the byte
|
||||
// scanner; a non-ASCII byte falls back to the regexp for the reason above.
|
||||
func findLibpqPassword(s string) (start, keyEnd, valStart int, ok bool) {
|
||||
if hasNonASCII(s) {
|
||||
loc := libpqPassword.FindStringSubmatchIndex(s)
|
||||
if loc == nil {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
return loc[0], loc[3], loc[1], true
|
||||
}
|
||||
const pwLen = len("password")
|
||||
for i := 0; i+pwLen < len(s); i++ {
|
||||
if i > 0 && isASCIIWord(s[i-1]) {
|
||||
continue
|
||||
}
|
||||
kStart := i
|
||||
kEnd := i
|
||||
switch s[i] {
|
||||
case 's', 'S':
|
||||
if i+3+pwLen < len(s) && strings.EqualFold(s[i:i+3+pwLen], "sslpassword") {
|
||||
kEnd = i + 3 + pwLen
|
||||
}
|
||||
case 'p', 'P':
|
||||
if strings.EqualFold(s[i:i+pwLen], "password") {
|
||||
kEnd = i + pwLen
|
||||
}
|
||||
}
|
||||
if kEnd == kStart {
|
||||
continue
|
||||
}
|
||||
j := kEnd
|
||||
for j < len(s) && (s[j] == ' ' || s[j] == '\t' || s[j] == '\r' || s[j] == '\n' || s[j] == '\f') {
|
||||
j++
|
||||
}
|
||||
if j >= len(s) || s[j] != '=' {
|
||||
continue
|
||||
}
|
||||
j++
|
||||
for j < len(s) && (s[j] == ' ' || s[j] == '\t' || s[j] == '\r' || s[j] == '\n' || s[j] == '\f') {
|
||||
j++
|
||||
}
|
||||
return kStart, kEnd, j, true
|
||||
}
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
|
||||
// isDSNSecretParam reports whether a URL query parameter carries a secret.
|
||||
func isDSNSecretParam(key string) bool {
|
||||
if hasNonASCII(key) {
|
||||
// Unicode case folding can change the byte length of a word (the Kelvin
|
||||
// sign K folds to k), so the length switch below cannot decide.
|
||||
key = strings.ToLower(key)
|
||||
}
|
||||
switch len(key) {
|
||||
case 5:
|
||||
return strings.EqualFold(key, "token")
|
||||
case 6:
|
||||
return strings.EqualFold(key, "apikey") || strings.EqualFold(key, "secret")
|
||||
case 7:
|
||||
return strings.EqualFold(key, "api_key") || strings.EqualFold(key, "api-key")
|
||||
case 8:
|
||||
return strings.EqualFold(key, "password") || strings.EqualFold(key, "id_token")
|
||||
case 10:
|
||||
return strings.EqualFold(key, "auth_token") || strings.EqualFold(key, "auth-token")
|
||||
case 11:
|
||||
return strings.EqualFold(key, "sslpassword")
|
||||
case 12:
|
||||
return strings.EqualFold(key, "access_token") || strings.EqualFold(key, "access-token")
|
||||
case 13:
|
||||
return strings.EqualFold(key, "refresh_token") || strings.EqualFold(key, "client_secret") || strings.EqualFold(key, "client-secret")
|
||||
switch strings.ToLower(key) {
|
||||
case "password", "sslpassword",
|
||||
"token", "access_token", "access-token", "auth_token", "auth-token", "refresh_token", "id_token",
|
||||
"api_key", "api-key", "apikey",
|
||||
"secret", "client_secret", "client-secret":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
@@ -354,24 +275,16 @@ func isDSNSecretParam(key string) bool {
|
||||
// including escaped whitespace and quotes. An unterminated quoted value consumes
|
||||
// the rest of the input: malformed configuration must not reveal its secret.
|
||||
func redactKeywordPasswords(dsn string) string {
|
||||
start, keyEnd, i, ok := findLibpqPassword(dsn)
|
||||
if !ok {
|
||||
return dsn
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(dsn))
|
||||
for {
|
||||
out.WriteString(dsn[:start])
|
||||
key := dsn[start:keyEnd]
|
||||
if hasNonASCII(key) {
|
||||
// Keep the spelling: a Unicode keyword's byte length does not say
|
||||
// which keyword it is.
|
||||
out.WriteString(strings.ToLower(key) + "=****")
|
||||
} else if keyEnd-start == len("sslpassword") {
|
||||
out.WriteString("sslpassword=****")
|
||||
} else {
|
||||
out.WriteString("password=****")
|
||||
loc := libpqPassword.FindStringSubmatchIndex(dsn)
|
||||
if loc == nil {
|
||||
out.WriteString(dsn)
|
||||
return out.String()
|
||||
}
|
||||
out.WriteString(dsn[:loc[0]])
|
||||
out.WriteString(strings.ToLower(dsn[loc[2]:loc[3]]) + "=****")
|
||||
i := loc[1]
|
||||
var quote byte
|
||||
if i < len(dsn) && (dsn[i] == '\'' || dsn[i] == '"') {
|
||||
quote = dsn[i]
|
||||
@@ -392,18 +305,13 @@ func redactKeywordPasswords(dsn string) string {
|
||||
break
|
||||
}
|
||||
} else {
|
||||
if c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' || c == '\f' {
|
||||
if strings.ContainsRune(" \t\r\n\v\f", rune(c)) {
|
||||
break
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
dsn = dsn[i:]
|
||||
start, keyEnd, i, ok = findLibpqPassword(dsn)
|
||||
if !ok {
|
||||
out.WriteString(dsn)
|
||||
return out.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,9 +320,9 @@ func redactKeywordPasswords(dsn string) string {
|
||||
// password contains an unencoded '#', '/' or '?'. Any such '@' fails closed: a
|
||||
// split password cannot be told apart from a harmless '@' in a query value.
|
||||
func hasSplitUserinfoPassword(u *url.URL) bool {
|
||||
return strings.IndexByte(u.Fragment, '@') >= 0 ||
|
||||
strings.IndexByte(u.Path, '@') >= 0 ||
|
||||
strings.IndexByte(u.RawQuery, '@') >= 0
|
||||
return strings.Contains(u.Fragment, "@") ||
|
||||
strings.Contains(u.Path, "@") ||
|
||||
strings.Contains(u.RawQuery, "@")
|
||||
}
|
||||
|
||||
// Redact is a log-safe view of a PostgreSQL DSN. It masks URL userinfo
|
||||
@@ -438,36 +346,33 @@ func Redact(dsn string) string {
|
||||
u.User = url.UserPassword(u.User.Username(), "****")
|
||||
}
|
||||
}
|
||||
if u.RawQuery != "" {
|
||||
q, qerr := url.ParseQuery(u.RawQuery)
|
||||
if qerr != nil {
|
||||
return u.Scheme + "://[redacted]"
|
||||
}
|
||||
masked := false
|
||||
for k := range q {
|
||||
if isDSNSecretParam(k) {
|
||||
q[k] = []string{"****"}
|
||||
masked = true
|
||||
}
|
||||
}
|
||||
if masked {
|
||||
u.RawQuery = q.Encode()
|
||||
q, qerr := url.ParseQuery(u.RawQuery)
|
||||
if qerr != nil {
|
||||
return u.Scheme + "://[redacted]"
|
||||
}
|
||||
masked := false
|
||||
for k := range q {
|
||||
if isDSNSecretParam(k) {
|
||||
q[k] = []string{"****"}
|
||||
masked = true
|
||||
}
|
||||
}
|
||||
if masked {
|
||||
u.RawQuery = q.Encode()
|
||||
}
|
||||
return u.String()
|
||||
}
|
||||
// A URL whose password has an unencoded # / ? or % does not parse; its
|
||||
// password still runs from the first : after the scheme to the last @.
|
||||
if i := strings.Index(dsn, "://"); i >= 0 {
|
||||
if at := strings.LastIndexByte(dsn, '@'); at > i {
|
||||
if c := strings.IndexByte(dsn[i+3:at], ':'); c >= 0 {
|
||||
if at := strings.LastIndex(dsn, "@"); at > i {
|
||||
if c := strings.Index(dsn[i+3:at], ":"); c >= 0 {
|
||||
dsn = dsn[:i+3+c+1] + "****" + dsn[at:]
|
||||
}
|
||||
}
|
||||
}
|
||||
trimmed := strings.TrimSpace(dsn)
|
||||
if len(trimmed) >= len("postgres://") && (strings.EqualFold(trimmed[:len("postgres://")], "postgres://") ||
|
||||
(len(trimmed) >= len("postgresql://") && strings.EqualFold(trimmed[:len("postgresql://")], "postgresql://"))) {
|
||||
lower := strings.ToLower(strings.TrimSpace(dsn))
|
||||
if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") {
|
||||
// Fail closed: a malformed URL (e.g. raw '%' in password or bad port) may
|
||||
// carry user:pass@ that keyword=value redaction will not match.
|
||||
return "postgres://[redacted]"
|
||||
|
||||
@@ -161,27 +161,6 @@ func TestRedactMasksEveryDSNPasswordForm(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A non-ASCII letter can case-fold to an ASCII one and change a keyword's byte
|
||||
// length: ſ folds to s and the Kelvin sign K to k. The byte scanner cannot read
|
||||
// those spellings, so they must keep the regex and lowercase behaviour that
|
||||
// masked them before.
|
||||
func TestRedactUnicodeCaseFoldedSecrets(t *testing.T) {
|
||||
cases := []struct{ in, secret string }{
|
||||
{"host=db.example paſſword=SECRET_ONE dbname=app", "SECRET_ONE"},
|
||||
{"host=db.example sslpaſſword=SECRET_TWO dbname=app", "SECRET_TWO"},
|
||||
{"postgres://u@db.example/app?to\u212Aen=SECRET_THREE", "SECRET_THREE"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := Redact(c.in); strings.Contains(got, c.secret) {
|
||||
t.Errorf("Redact(%q)=%q still contains %q", c.in, got, c.secret)
|
||||
}
|
||||
}
|
||||
// The non-ASCII keyword keeps its spelling in the mask, as before.
|
||||
if got := Redact("host=db.example paſſword=SECRET_ONE"); got != "host=db.example paſſword=****" {
|
||||
t.Errorf("Redact kept spelling: got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedConfigIsAnError(t *testing.T) {
|
||||
cfgPath := filepath.Join(t.TempDir(), "config.json")
|
||||
// What install.sh used to write for a password containing a double quote.
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Property 1: Fast findLibpqPassword scanner exact equivalence with the original
|
||||
// (?i)\b((?:ssl)?password)\s*=\s* regex across 5,000 generated inputs.
|
||||
func TestPropertyLibpqScannerEquivalence(t *testing.T) {
|
||||
re := regexp.MustCompile(`(?i)\b((?:ssl)?password)\s*=\s*`)
|
||||
rng := rand.New(rand.NewPCG(656, 1014))
|
||||
tokens := []string{
|
||||
"host=db", "user=u", "password=", "PASSWORD = ", "SslPassword\t=\n",
|
||||
"xpassword=1", "my_sslpassword=2", "password", "sslpassword", " ", "\t", "=", "'sec'", `"sec"`, "secret",
|
||||
// A Unicode letter that folds to an ASCII one changes the keyword's byte
|
||||
// length; the scanner must fall back to the regex on such input.
|
||||
"paſſword=", "sslpaſſword = ", "paſſword='sec'",
|
||||
}
|
||||
for range 5000 {
|
||||
var sb strings.Builder
|
||||
for range 1 + rng.IntN(6) {
|
||||
sb.WriteString(tokens[rng.IntN(len(tokens))])
|
||||
}
|
||||
s := sb.String()
|
||||
loc := re.FindStringSubmatchIndex(s)
|
||||
start, keyEnd, valStart, ok := findLibpqPassword(s)
|
||||
if loc == nil {
|
||||
if ok {
|
||||
t.Fatalf("scanner matched %q at (%d,%d,%d) but regex did not", s, start, keyEnd, valStart)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !ok || start != loc[0] || keyEnd != loc[3] || valStart != loc[1] {
|
||||
t.Fatalf("mismatch on %q: scanner=(%d,%d,%d,%v) regex=(%d,%d,%d)",
|
||||
s, start, keyEnd, valStart, ok, loc[0], loc[3], loc[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 2: Historical bugs #656, #1014, #1019:
|
||||
// High-entropy secrets with arbitrary delimiter chars (#, /, ?, @, %, ;, ', ", \, space)
|
||||
// MUST NEVER appear in Redact(dsn), and Redact MUST be idempotent.
|
||||
func TestPropertyRedactNonLeakageAndIdempotence(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(1014, 1019))
|
||||
delims := []string{"#", "/", "?", "@", "%", "%ZZ", ";", "'", `"`, `\`, " ", "=", ":"}
|
||||
secretParams := []string{
|
||||
"password", "sslpassword", "token", "access_token", "access-token",
|
||||
"auth_token", "auth-token", "refresh_token", "id_token",
|
||||
"api_key", "api-key", "apikey", "secret", "client_secret", "client-secret",
|
||||
}
|
||||
randCase := func(s string) string {
|
||||
b := []byte(s)
|
||||
for i := range b {
|
||||
if b[i] >= 'a' && b[i] <= 'z' && rng.IntN(2) == 1 {
|
||||
b[i] -= 'a' - 'A'
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
for i := range 1000 {
|
||||
// Secret marker split around a hostile delimiter.
|
||||
tag := fmt.Sprintf("SEC%06d", i)
|
||||
d := delims[rng.IntN(len(delims))]
|
||||
pw := "p" + d + tag
|
||||
scheme := "postgres"
|
||||
if rng.IntN(2) == 1 {
|
||||
scheme = "postgresql"
|
||||
}
|
||||
if rng.IntN(4) == 0 {
|
||||
scheme = strings.ToUpper(scheme)
|
||||
}
|
||||
|
||||
// 1) Userinfo password (including split passwords with #, /, ?, @, %ZZ).
|
||||
u1 := fmt.Sprintf("%s://artex:%s@db.example:5432/app?sslmode=require", scheme, pw)
|
||||
out1 := Redact(u1)
|
||||
if strings.Contains(out1, tag) {
|
||||
t.Fatalf("userinfo secret leaked: in=%q out=%q", u1, out1)
|
||||
}
|
||||
if out1b := Redact(out1); out1b != out1 {
|
||||
t.Fatalf("Redact not idempotent on %q: once=%q twice=%q", u1, out1, out1b)
|
||||
}
|
||||
|
||||
// 2) Secret query parameter (any case, optional malformed sibling).
|
||||
pk := randCase(secretParams[rng.IntN(len(secretParams))])
|
||||
u2 := fmt.Sprintf("%s://artex@db.example:5432/app?sslmode=disable&%s=%s", scheme, pk, tag)
|
||||
out2 := Redact(u2)
|
||||
if strings.Contains(out2, tag) {
|
||||
t.Fatalf("query secret leaked: in=%q out=%q", u2, out2)
|
||||
}
|
||||
if out2b := Redact(out2); out2b != out2 {
|
||||
t.Fatalf("Redact not idempotent on %q: once=%q twice=%q", u2, out2, out2b)
|
||||
}
|
||||
|
||||
// 3) libpq keyword=value password / sslpassword (bare, single-quoted, double-quoted).
|
||||
kw := randCase("password")
|
||||
if rng.IntN(2) == 1 {
|
||||
kw = randCase("sslpassword")
|
||||
}
|
||||
var u3 string
|
||||
switch rng.IntN(3) {
|
||||
case 0:
|
||||
u3 = fmt.Sprintf("host=db.example %s=%s dbname=app", kw, tag)
|
||||
case 1:
|
||||
u3 = fmt.Sprintf("host=db.example %s='a\\' %s' dbname=app", kw, tag)
|
||||
default:
|
||||
u3 = fmt.Sprintf(`host=db.example %s="unterminated %s`, kw, tag)
|
||||
}
|
||||
out3 := Redact(u3)
|
||||
if strings.Contains(out3, tag) {
|
||||
t.Fatalf("libpq secret leaked: in=%q out=%q", u3, out3)
|
||||
}
|
||||
if out3b := Redact(out3); out3b != out3 {
|
||||
t.Fatalf("Redact not idempotent on %q: once=%q twice=%q", u3, out3, out3b)
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-45
@@ -87,21 +87,11 @@ func (w *argvWalk) step() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// parseBashCommand extracts the "command" field from a Bash tool input and
|
||||
// parses it once with the Bash parser. Callers reuse the resulting *syntax.File
|
||||
// across both decoded text rules and compound argv rules.
|
||||
func parseBashCommand(input []byte) (*syntax.File, string, bool) {
|
||||
var in struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
if json.Unmarshal(input, &in) != nil || strings.TrimSpace(in.Command) == "" {
|
||||
return nil, "", false
|
||||
}
|
||||
f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(in.Command), "")
|
||||
if err != nil {
|
||||
return nil, "", false
|
||||
}
|
||||
return f, in.Command, true
|
||||
// argvCompoundMatches reports whether any command executed within a Bash tool
|
||||
// call matches or may match the deny/ask prefix rule tokens. See
|
||||
// argvCompoundMatch.
|
||||
func argvCompoundMatches(tokens []string, toolName string, input []byte) bool {
|
||||
return argvCompoundMatch(tokens, toolName, input) != argvNoMatch
|
||||
}
|
||||
|
||||
// argvCompoundMatch matches the deny/ask prefix rule tokens against every
|
||||
@@ -117,19 +107,17 @@ func argvCompoundMatch(tokens []string, toolName string, input []byte) argvMatch
|
||||
if toolName != "Bash" || len(tokens) == 0 {
|
||||
return argvNoMatch
|
||||
}
|
||||
f, _, ok := parseBashCommand(input)
|
||||
if !ok {
|
||||
var in struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
if json.Unmarshal(input, &in) != nil {
|
||||
return argvNoMatch
|
||||
}
|
||||
return argvCompoundMatchFile(tokens, f)
|
||||
}
|
||||
|
||||
func argvCompoundMatchFile(tokens []string, f *syntax.File) argvMatch {
|
||||
if f == nil || len(tokens) == 0 {
|
||||
if strings.TrimSpace(in.Command) == "" {
|
||||
return argvNoMatch
|
||||
}
|
||||
w := &argvWalk{rule: tokens}
|
||||
if bashFileMatchesArgv(w, f, 0) {
|
||||
if bashCommandMatchesArgv(w, in.Command, 0) {
|
||||
return argvMatched
|
||||
}
|
||||
if w.possible {
|
||||
@@ -138,19 +126,30 @@ func argvCompoundMatchFile(tokens []string, f *syntax.File) argvMatch {
|
||||
return argvNoMatch
|
||||
}
|
||||
|
||||
// bashDecodedInputFromAST returns the input of a Bash call with its command
|
||||
// replaced by the commands the shell runs, joined by "; ", each word decoded as
|
||||
// callWordOf decodes it (backslash escapes, line continuations, single and
|
||||
// double quotes, $'...'), so a text rule written for "rm -rf" also meets
|
||||
// r\m -rf. A word that holds an expansion is kept as written.
|
||||
func bashDecodedInputFromAST(input []byte, f *syntax.File) (string, bool) {
|
||||
if f == nil {
|
||||
// bashDecodedInput returns the input of a Bash call with its command replaced
|
||||
// by the commands the shell runs, joined by "; ", each word decoded as callWordOf
|
||||
// decodes it (backslash escapes, line continuations, single and double quotes,
|
||||
// $'...'), so a text rule written for "rm -rf" also meets r\m -rf. A word
|
||||
// that holds an expansion is kept as written. ok is false for another tool, or
|
||||
// when the command is empty or does not parse.
|
||||
func bashDecodedInput(toolName string, input []byte) (string, bool) {
|
||||
if toolName != "Bash" {
|
||||
return "", false
|
||||
}
|
||||
var cmdIn struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
if json.Unmarshal(input, &cmdIn) != nil || strings.TrimSpace(cmdIn.Command) == "" {
|
||||
return "", false
|
||||
}
|
||||
var in map[string]json.RawMessage
|
||||
if json.Unmarshal(input, &in) != nil {
|
||||
return "", false
|
||||
}
|
||||
f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(cmdIn.Command), "")
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
printer := syntax.NewPrinter()
|
||||
var cmds []string
|
||||
syntax.Walk(f, func(n syntax.Node) bool {
|
||||
@@ -188,17 +187,7 @@ func bashDecodedInputFromAST(input []byte, f *syntax.File) (string, bool) {
|
||||
delete(in, k)
|
||||
}
|
||||
}
|
||||
cmdJSON := bytes.TrimSpace(buf.Bytes())
|
||||
if len(in) == 0 {
|
||||
// Common case: {"command":"..."} with no sibling fields.
|
||||
var out strings.Builder
|
||||
out.Grow(len(cmdJSON) + 13)
|
||||
out.WriteString(`{"command":`)
|
||||
out.Write(cmdJSON)
|
||||
out.WriteByte('}')
|
||||
return out.String(), true
|
||||
}
|
||||
in["command"] = bytes.Clone(cmdJSON)
|
||||
in["command"] = bytes.Clone(bytes.TrimSpace(buf.Bytes()))
|
||||
buf.Reset()
|
||||
if enc.Encode(in) != nil {
|
||||
return "", false
|
||||
@@ -215,10 +204,6 @@ func bashCommandMatchesArgv(w *argvWalk, command string, depth int) bool {
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return bashFileMatchesArgv(w, f, depth)
|
||||
}
|
||||
|
||||
func bashFileMatchesArgv(w *argvWalk, f *syntax.File, depth int) bool {
|
||||
outer := w.stdin
|
||||
defer func() { w.stdin = outer }()
|
||||
piped := map[*syntax.Stmt]*argvFeed{}
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func benchRuleSet() []db.InterceptRule {
|
||||
return []db.InterceptRule{
|
||||
{ID: 1, Name: "[built-in] Recursive force delete rm -rf", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)\brm\b.{0,80}(?:-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*|-[a-z]*r[a-z]*(?:\s+-+[a-z][a-z-]*)*?\s+-+[a-z]*f[a-z]*|-[a-z]*f[a-z]*(?:\s+-+[a-z][a-z-]*)*?\s+-+[a-z]*r[a-z]*|--recursive|--no-preserve-root)`},
|
||||
{ID: 2, Name: "[built-in] Delete critical system directories", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `\brm\b[^"'\n]{0,60}["'\s](/|/etc|/bin|/usr|/boot|/var|/lib|/sys|/proc|/dev|/sbin|/root)`},
|
||||
{ID: 3, Name: "[built-in] Disk formatting mkfs", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\bmkfs\b`},
|
||||
{ID: 4, Name: "[built-in] Overwrite disk device dd", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\bdd\b[^|\n]{0,100}\bof=\s*/dev/[a-zA-Z]`},
|
||||
{ID: 5, Name: "[built-in] Fork bomb", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `:\(\)\s*\{[^}]*:\|:`},
|
||||
{ID: 6, Name: "[built-in] Shutdown / reboot", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\b(?:shutdown|reboot|halt|poweroff|init\s+[06])\b`},
|
||||
{ID: 7, Name: "[built-in] Kill all processes", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\bkill\s+-9\s+-1\b|\bkillall\s+-9\b`},
|
||||
{ID: 8, Name: "[built-in] Disk wipe shred / wipe", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\b(?:shred|wipe)\b[^|\n]{0,80}/dev/[a-zA-Z]`},
|
||||
{ID: 9, Name: "[built-in] Flush firewall rules", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `\biptables\s+(?:-F|--flush)\b|\bnft\s+flush\s+ruleset\b`},
|
||||
{ID: 10, Name: "[built-in] SQL DROP", Enabled: true, Priority: 90, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `(?i)\bDROP\s+(?:DATABASE|TABLE|SCHEMA|INDEX|VIEW|TABLESPACE|USER|ROLE)\b`},
|
||||
{ID: 11, Name: "[built-in] SQL TRUNCATE", Enabled: true, Priority: 90, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `(?i)\bTRUNCATE\s+(?:TABLE\s+)?\w`},
|
||||
{ID: 12, Name: "[built-in] MongoDB drop", Enabled: true, Priority: 90, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `(?i)\.(?:dropDatabase|dropCollection|drop)\s*\(`},
|
||||
{ID: 13, Name: "[built-in] Redis FLUSH", Enabled: true, Priority: 90, MatchTarget: "tool_input", MatchType: "regex", Action: "deny", Pattern: `(?i)\b(?:FLUSHALL|FLUSHDB)\b`},
|
||||
{ID: 14, Name: "[built-in] curl/wget DELETE", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)\bcurl\b[^|\n&;"]{0,300}(?:-X\s*DELETE|--request\s+DELETE|-XDELETE)|\bwget\b[^|\n&;"]{0,300}--method[=\s]+DELETE`},
|
||||
{ID: 15, Name: "[built-in] Python HTTP DELETE", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)\b(?:requests|httpx|aiohttp|urllib\.request)\.delete\s*\(|session\.delete\s*\(|client\.delete\s*\(`},
|
||||
{ID: 16, Name: "[built-in] JS HTTP DELETE", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)axios\.delete\s*\(|method\s*[:=]\s*['"]DELETE['"]`},
|
||||
{ID: 17, Name: "[built-in] Bulk clear/wipe paths", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)/(?:clear|wipe|flush|purge|truncate|drop|destroy|factory[-_]reset|reset[-_]all)(?:[/?#"'\s]|$)`},
|
||||
{ID: 18, Name: "[built-in] Delete-style paths", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "regex", Action: "deny",
|
||||
Pattern: `(?i)/(?:(?:delete|remove|unlink|erase|destroy)[-\w]*|del)(?:[/?#"'\s]|$)`},
|
||||
{ID: 19, Name: "deny git push", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["git","push"]`},
|
||||
{ID: 20, Name: "deny kubectl delete", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["kubectl","delete"]`},
|
||||
{ID: 21, Name: "deny terraform destroy", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["terraform","destroy"]`},
|
||||
{ID: 22, Name: "deny docker rm", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["docker","rm"]`},
|
||||
{ID: 23, Name: "deny aws s3 rm", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["aws","s3","rm"]`},
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMatchBash23RulesBenign(b *testing.B) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest(benchRuleSet())
|
||||
in := []byte(`{"command":"curl -s -H 'Accept: application/json' https://app.example.com/api/v1/health | jq .status"}`)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if _, ok := ic.Match("Bash", in); ok {
|
||||
b.Fatal("unexpected match")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMatchBash23RulesMatch(b *testing.B) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest(benchRuleSet())
|
||||
in := []byte(`{"command":"r\\m -r -f /tmp/work"}`)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if dec, ok := ic.Match("Bash", in); !ok || dec.Action != "deny" {
|
||||
b.Fatalf("expected deny, got ok=%v dec=%+v", ok, dec)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMatchBashArgvCompound(b *testing.B) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest([]db.InterceptRule{
|
||||
{ID: 1, Name: "deny git push", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["git","push"]`},
|
||||
{ID: 2, Name: "deny kubectl delete", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["kubectl","delete"]`},
|
||||
{ID: 3, Name: "deny terraform destroy", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["terraform","destroy"]`},
|
||||
{ID: 4, Name: "deny docker rm", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["docker","rm"]`},
|
||||
{ID: 5, Name: "deny aws s3 rm", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["aws","s3","rm"]`},
|
||||
{ID: 6, Name: "deny helm uninstall", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["helm","uninstall"]`},
|
||||
{ID: 7, Name: "deny psql drop", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["psql"]`},
|
||||
{ID: 8, Name: "deny rsync", Enabled: true, Priority: 70, MatchTarget: "tool_input", MatchType: "argv", Action: "deny", Pattern: `["rsync"]`},
|
||||
})
|
||||
in := []byte(`{"command":"sudo -u app env FOO=1 timeout 30 curl -s https://app.example.com/api | jq .items"}`)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if _, ok := ic.Match("Bash", in); ok {
|
||||
b.Fatal("unexpected match")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkExtractTargetsPlain(b *testing.B) {
|
||||
in := []byte(`{"command":"ls -la /workspace && grep -rn TODO src/ && wc -l README"}`)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if ts := ExtractTargets("Bash", in); len(ts) != 0 {
|
||||
b.Fatalf("unexpected targets: %+v", ts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkExtractTargetsURLAndIP(b *testing.B) {
|
||||
in := []byte(`{"command":"curl -A Chrome/156.0.0.0 -H 'Accept: application/json' https://api.example.com:8443/v1/users 192.0.2.10:8080"}`)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if ts := ExtractTargets("Bash", in); len(ts) != 2 {
|
||||
b.Fatalf("want 2 targets, got %d: %+v", len(ts), ts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkNormalizeTargetDomain(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if t, ok := NormalizeTarget("https://api.example.com:8443/v1/users"); !ok || t.Host != "api.example.com" {
|
||||
b.Fatalf("unexpected target: %+v ok=%v", t, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
-286
@@ -19,7 +19,6 @@ import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"regexp"
|
||||
"regexp/syntax"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -28,7 +27,6 @@ import (
|
||||
|
||||
"github.com/Autumn-27/artex/config"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
shsyntax "mvdan.cc/sh/v3/syntax"
|
||||
)
|
||||
|
||||
// ctxKey is the unexported context key type to avoid collisions.
|
||||
@@ -122,166 +120,15 @@ func TargetScopeFromContext(ctx context.Context) (s TargetScope, ok bool) {
|
||||
// ask rule whose pattern does not compile: it matches every call, as a deny.
|
||||
type compiledRule struct {
|
||||
db.InterceptRule
|
||||
re *regexp.Regexp
|
||||
reNeedles []string // sound necessary lowercase-ASCII disjunction: if non-empty, a match must contain at least one needle
|
||||
argv []string
|
||||
bad bool
|
||||
allowOK bool
|
||||
configDigest string
|
||||
}
|
||||
|
||||
// extractRegexNeedles derives a sound necessary condition from a Perl regex:
|
||||
// if it returns a non-empty slice of lowercase ASCII strings, then any string
|
||||
// matched by the regex is guaranteed to contain at least one of those needles
|
||||
// when ASCII-lowercased. Returning nil means "unconstrained" (always run re).
|
||||
//
|
||||
// Soundness proof by structural induction on syntax.Regexp:
|
||||
// - OpLiteral (pure ASCII, no non-ASCII fold targets like 'k'/'s' under FoldCase):
|
||||
// every match must contain strings.ToLower(lit) (for FoldCase, only literals
|
||||
// whose runes cannot fold from non-ASCII are used, or we check ASCII-only
|
||||
// needles after full strings.ToLower). Since Go's strings.ToLower maps
|
||||
// Kelvin 'K'→'k' and long-s 'ſ'→'ſ' (wait: 'ſ' does NOT map to 's' under
|
||||
// strings.ToLower!), under FoldCase we skip literals containing 's' or 'k'
|
||||
// only if non-ASCII exists; even simpler, matchState only applies the
|
||||
// prefilter when the subject is pure ASCII (<0x80), where Unicode folding
|
||||
// cannot match any non-ASCII rune!
|
||||
// - OpCapture / OpPlus / OpRepeat(Min>=1): necessary condition of child holds.
|
||||
// - OpConcat: every child must match, so the most selective child's necessary
|
||||
// condition (fewest needles, breaking ties by longest min-needle) holds.
|
||||
// - OpAlternate: one branch must match, so the union of all branches' needle
|
||||
// sets holds (if every branch is constrained and total <= maxNeedles).
|
||||
// - All other ops return nil (unconstrained).
|
||||
func extractRegexNeedles(pattern string) []string {
|
||||
ast, err := syntax.Parse(pattern, syntax.Perl)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return regexASTNeedles(ast.Simplify())
|
||||
}
|
||||
|
||||
const maxPrefilterNeedles = 12
|
||||
|
||||
func regexASTNeedles(re *syntax.Regexp) []string {
|
||||
if re == nil {
|
||||
return nil
|
||||
}
|
||||
switch re.Op {
|
||||
case syntax.OpLiteral:
|
||||
if len(re.Rune) == 0 {
|
||||
return nil
|
||||
}
|
||||
buf := make([]byte, 0, len(re.Rune))
|
||||
for _, r := range re.Rune {
|
||||
if r >= 0x80 {
|
||||
return nil
|
||||
}
|
||||
c := byte(r)
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
buf = append(buf, c)
|
||||
}
|
||||
return []string{string(buf)}
|
||||
case syntax.OpCapture, syntax.OpPlus:
|
||||
if len(re.Sub) == 1 {
|
||||
return regexASTNeedles(re.Sub[0])
|
||||
}
|
||||
case syntax.OpRepeat:
|
||||
if re.Min >= 1 && len(re.Sub) == 1 {
|
||||
return regexASTNeedles(re.Sub[0])
|
||||
}
|
||||
case syntax.OpConcat:
|
||||
var best []string
|
||||
bestScore := -1
|
||||
for _, sub := range re.Sub {
|
||||
ns := regexASTNeedles(sub)
|
||||
if len(ns) == 0 {
|
||||
continue
|
||||
}
|
||||
minLen := len(ns[0])
|
||||
for _, n := range ns[1:] {
|
||||
if len(n) < minLen {
|
||||
minLen = len(n)
|
||||
}
|
||||
}
|
||||
// Prefer single-needle filters first, then longer minimum needle length.
|
||||
score := minLen*100 - len(ns)*20
|
||||
if best == nil || score > bestScore {
|
||||
best = ns
|
||||
bestScore = score
|
||||
}
|
||||
}
|
||||
return best
|
||||
case syntax.OpAlternate:
|
||||
if len(re.Sub) == 0 {
|
||||
return nil
|
||||
}
|
||||
var union []string
|
||||
for _, sub := range re.Sub {
|
||||
ns := regexASTNeedles(sub)
|
||||
if len(ns) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, n := range ns {
|
||||
if !slices.Contains(union, n) {
|
||||
union = append(union, n)
|
||||
if len(union) > maxPrefilterNeedles {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return union
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func asciiLower(s string) (lower string, isASCII bool) {
|
||||
hasUpper := false
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 0x80 {
|
||||
return "", false
|
||||
}
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
hasUpper = true
|
||||
}
|
||||
}
|
||||
if !hasUpper {
|
||||
return s, true
|
||||
}
|
||||
b := make([]byte, len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
b[i] = c
|
||||
}
|
||||
return string(b), true
|
||||
}
|
||||
|
||||
func needlesMayMatch(lower string, needles []string) bool {
|
||||
for _, n := range needles {
|
||||
if strings.Contains(lower, n) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ruleConfigDigest(r db.InterceptRule) string {
|
||||
configJSON, _ := json.Marshal(r)
|
||||
return digestInput(configJSON)
|
||||
re *regexp.Regexp
|
||||
argv []string
|
||||
bad bool
|
||||
}
|
||||
|
||||
// compileRule prepares a rule for matching. ok is false for a rule whose
|
||||
// pattern does not compile; see loadLocked for what happens to it.
|
||||
func compileRule(r db.InterceptRule) (compiledRule, bool) {
|
||||
cr := compiledRule{
|
||||
InterceptRule: r,
|
||||
configDigest: ruleConfigDigest(r),
|
||||
}
|
||||
cr := compiledRule{InterceptRule: r}
|
||||
switch r.MatchType {
|
||||
case "regex":
|
||||
re, err := regexp.Compile(r.Pattern)
|
||||
@@ -289,14 +136,12 @@ func compileRule(r db.InterceptRule) (compiledRule, bool) {
|
||||
return cr, false
|
||||
}
|
||||
cr.re = re
|
||||
cr.reNeedles = extractRegexNeedles(r.Pattern)
|
||||
case "argv":
|
||||
tokens, err := ParseArgvPattern(r.Pattern)
|
||||
if err != nil {
|
||||
return cr, false
|
||||
}
|
||||
cr.argv = tokens
|
||||
cr.allowOK = r.Action == "allow" && CheckArgvAllow(tokens) == nil
|
||||
}
|
||||
return cr, true
|
||||
}
|
||||
@@ -485,7 +330,6 @@ func (i *Interceptor) loadLocked() error {
|
||||
// A deny or ask rule that cannot be evaluated must not fail open.
|
||||
cr.bad, cr.Action = true, "deny"
|
||||
cr.Message = "intercept rule [" + r.Name + "] has a pattern that does not compile; calls are blocked until the rule is fixed or disabled"
|
||||
cr.configDigest = ruleConfigDigest(cr.InterceptRule)
|
||||
}
|
||||
out = append(out, cr)
|
||||
}
|
||||
@@ -864,85 +708,6 @@ func judgeActionLabel(action string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// matchState caches per-call derived views of a tool invocation (raw string
|
||||
// subject, parsed Bash AST, decoded Bash JSON input, and argv allow prefix) so
|
||||
// evaluating N rules parses and decodes the call at most once.
|
||||
type matchState struct {
|
||||
toolName string
|
||||
input []byte
|
||||
rawReady bool
|
||||
rawInput string
|
||||
rawLowerOK bool
|
||||
rawLower string
|
||||
toolLowerOK bool
|
||||
toolLower string
|
||||
toolReady bool
|
||||
bashReady bool
|
||||
bashFile *shsyntax.File
|
||||
bashCmd string
|
||||
bashOK bool
|
||||
decReady bool
|
||||
decInput string
|
||||
decLowerOK bool
|
||||
decLower string
|
||||
decOK bool
|
||||
prefixReady bool
|
||||
prefix []string
|
||||
prefixOK bool
|
||||
}
|
||||
|
||||
func (m *matchState) rawSubject() (string, string, bool) {
|
||||
if !m.rawReady {
|
||||
m.rawInput = string(m.input)
|
||||
m.rawLower, m.rawLowerOK = asciiLower(m.rawInput)
|
||||
m.rawReady = true
|
||||
}
|
||||
return m.rawInput, m.rawLower, m.rawLowerOK
|
||||
}
|
||||
|
||||
func (m *matchState) toolSubject() (string, string, bool) {
|
||||
if !m.toolReady {
|
||||
m.toolLower, m.toolLowerOK = asciiLower(m.toolName)
|
||||
m.toolReady = true
|
||||
}
|
||||
return m.toolName, m.toolLower, m.toolLowerOK
|
||||
}
|
||||
|
||||
func (m *matchState) bashAST() (*shsyntax.File, bool) {
|
||||
if !m.bashReady {
|
||||
m.bashReady = true
|
||||
if m.toolName == "Bash" {
|
||||
m.bashFile, m.bashCmd, m.bashOK = parseBashCommand(m.input)
|
||||
}
|
||||
}
|
||||
return m.bashFile, m.bashOK
|
||||
}
|
||||
|
||||
func (m *matchState) decodedInput() (string, string, bool, bool) {
|
||||
if !m.decReady {
|
||||
m.decReady = true
|
||||
if f, ok := m.bashAST(); ok {
|
||||
m.decInput, m.decOK = bashDecodedInputFromAST(m.input, f)
|
||||
if m.decOK {
|
||||
m.decLower, m.decLowerOK = asciiLower(m.decInput)
|
||||
}
|
||||
}
|
||||
}
|
||||
return m.decInput, m.decLower, m.decLowerOK, m.decOK
|
||||
}
|
||||
|
||||
func (m *matchState) argvAllowPrefix() ([]string, bool) {
|
||||
if !m.prefixReady {
|
||||
m.prefixReady = true
|
||||
if _, ok := m.bashAST(); ok {
|
||||
if p, err := ArgvPrefix(m.bashCmd); err == nil {
|
||||
m.prefix, m.prefixOK = p, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return m.prefix, m.prefixOK
|
||||
}
|
||||
|
||||
// Match evaluates the rule list (priority DESC) against a tool call.
|
||||
// Returns (Decision, true) for the first matching enabled rule, or
|
||||
// (Decision{}, false) if no rule matches. When the rules cannot be loaded it
|
||||
@@ -956,17 +721,28 @@ func (i *Interceptor) Match(toolName string, input []byte) (Decision, bool) {
|
||||
if err != nil {
|
||||
return storeUnreadableDecision(), true
|
||||
}
|
||||
ms := matchState{toolName: toolName, input: input}
|
||||
var possible *Decision
|
||||
for idx := range rules {
|
||||
r := rules[idx]
|
||||
m := ruleMatchState(r, &ms)
|
||||
for _, r := range rules {
|
||||
m := ruleMatch(r, toolName, input)
|
||||
if m == argvPossible && possible == nil {
|
||||
d := possibleArgvDecision(r)
|
||||
possible = &d
|
||||
}
|
||||
if m == argvMatched && (possible == nil || r.Action == "deny") {
|
||||
return persistenceDecision(r), true
|
||||
msg := r.Message
|
||||
if msg == "" {
|
||||
msg = defaultMessage(r.Action, r.Name)
|
||||
}
|
||||
configJSON, _ := json.Marshal(r.InterceptRule)
|
||||
return Decision{
|
||||
RuleName: r.Name, ConfigDigest: digestInput(configJSON),
|
||||
Action: r.Action,
|
||||
Message: msg,
|
||||
RuleID: r.ID,
|
||||
TimeoutEnabled: r.TimeoutEnabled,
|
||||
TimeoutSeconds: r.TimeoutSeconds,
|
||||
TimeoutAction: r.TimeoutAction,
|
||||
}, true
|
||||
}
|
||||
}
|
||||
if possible != nil {
|
||||
@@ -992,20 +768,16 @@ func possibleArgvDecision(r compiledRule) Decision {
|
||||
return d
|
||||
}
|
||||
|
||||
// ruleMatchState is ruleMatchesState, keeping apart a deny or ask argv rule
|
||||
// that may match from one that matches.
|
||||
func ruleMatchState(r compiledRule, ms *matchState) argvMatch {
|
||||
// ruleMatch is ruleMatches, keeping apart a deny or ask argv rule that may
|
||||
// match from one that matches.
|
||||
func ruleMatch(r compiledRule, toolName string, input []byte) argvMatch {
|
||||
if !r.bad && r.MatchType == "argv" && (r.Action == "deny" || r.Action == "ask") {
|
||||
if r.MatchTarget != "tool_input" {
|
||||
return argvNoMatch
|
||||
}
|
||||
f, ok := ms.bashAST()
|
||||
if !ok {
|
||||
return argvNoMatch
|
||||
}
|
||||
return argvCompoundMatchFile(r.argv, f)
|
||||
return argvCompoundMatch(r.argv, toolName, input)
|
||||
}
|
||||
if ruleMatchesState(r, ms) {
|
||||
if ruleMatches(r, toolName, input) {
|
||||
return argvMatched
|
||||
}
|
||||
return argvNoMatch
|
||||
@@ -1035,15 +807,21 @@ func (i *Interceptor) MatchBuiltin(toolName string, input []byte) (Decision, boo
|
||||
if err != nil {
|
||||
return storeUnreadableDecision(), true
|
||||
}
|
||||
ms := matchState{toolName: toolName, input: input}
|
||||
for idx := range rules {
|
||||
r := rules[idx]
|
||||
if r.Action != "deny" || !strings.HasPrefix(r.Name, builtinRulePrefix) || !ruleMatchesState(r, &ms) {
|
||||
for _, r := range rules {
|
||||
if r.Action != "deny" || !strings.HasPrefix(r.Name, builtinRulePrefix) || !ruleMatches(r, toolName, input) {
|
||||
continue
|
||||
}
|
||||
d := persistenceDecision(r)
|
||||
d.TimeoutEnabled, d.TimeoutSeconds, d.TimeoutAction = false, 0, ""
|
||||
return d, true
|
||||
msg := r.Message
|
||||
if msg == "" {
|
||||
msg = defaultMessage(r.Action, r.Name)
|
||||
}
|
||||
configJSON, _ := json.Marshal(r.InterceptRule)
|
||||
return Decision{
|
||||
RuleName: r.Name, ConfigDigest: digestInput(configJSON),
|
||||
Action: r.Action,
|
||||
Message: msg,
|
||||
RuleID: r.ID,
|
||||
}, true
|
||||
}
|
||||
return Decision{}, false
|
||||
}
|
||||
@@ -1073,7 +851,7 @@ func (i *Interceptor) SetRulesForTest(rules []db.InterceptRule) {
|
||||
i.mu.Unlock()
|
||||
}
|
||||
|
||||
func ruleMatchesState(r compiledRule, ms *matchState) bool {
|
||||
func ruleMatches(r compiledRule, toolName string, input []byte) bool {
|
||||
if r.bad {
|
||||
return true
|
||||
}
|
||||
@@ -1083,34 +861,28 @@ func ruleMatchesState(r compiledRule, ms *matchState) bool {
|
||||
// exact derived prefix and denylist enforcement. Deny and ask rules
|
||||
// walk every call in a compound Bash command, stripping known wrappers
|
||||
// and recursing into eval / shell -c payloads. One that may match
|
||||
// counts as a match here; Match asks for it instead (ruleMatchState).
|
||||
// counts as a match here; Match asks for it instead (ruleMatch).
|
||||
if r.Action == "allow" {
|
||||
if !r.allowOK || r.MatchTarget != "tool_input" {
|
||||
if CheckArgvAllow(r.argv) != nil {
|
||||
return false
|
||||
}
|
||||
prefix, ok := ms.argvAllowPrefix()
|
||||
return ok && slices.Equal(prefix, r.argv)
|
||||
return r.MatchTarget == "tool_input" && argvRuleMatches(r.argv, toolName, input)
|
||||
}
|
||||
if r.Action == "deny" || r.Action == "ask" {
|
||||
if r.MatchTarget != "tool_input" {
|
||||
return false
|
||||
}
|
||||
f, ok := ms.bashAST()
|
||||
return ok && argvCompoundMatchFile(r.argv, f) != argvNoMatch
|
||||
return r.MatchTarget == "tool_input" && argvCompoundMatches(r.argv, toolName, input)
|
||||
}
|
||||
return false
|
||||
}
|
||||
var subject, lower string
|
||||
var lowerOK bool
|
||||
var subject string
|
||||
switch r.MatchTarget {
|
||||
case "tool_name":
|
||||
subject, lower, lowerOK = ms.toolSubject()
|
||||
subject = toolName
|
||||
case "tool_input":
|
||||
subject, lower, lowerOK = ms.rawSubject()
|
||||
subject = string(input)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if textRuleMatchesFast(r, subject, lower, lowerOK) {
|
||||
if textRuleMatches(r, subject) {
|
||||
return true
|
||||
}
|
||||
// Bash runs a command only after it removes quotes and backslashes and
|
||||
@@ -1120,20 +892,14 @@ func ruleMatchesState(r compiledRule, ms *matchState) bool {
|
||||
if r.MatchTarget != "tool_input" || (r.Action != "deny" && r.Action != "ask") {
|
||||
return false
|
||||
}
|
||||
decoded, decLower, decLowerOK, ok := ms.decodedInput()
|
||||
return ok && textRuleMatchesFast(r, decoded, decLower, decLowerOK)
|
||||
decoded, ok := bashDecodedInput(toolName, input)
|
||||
return ok && textRuleMatches(r, decoded)
|
||||
}
|
||||
|
||||
// textRuleMatchesFast checks the sound ASCII needle prefilter before running RE2.
|
||||
func textRuleMatchesFast(r compiledRule, subject, lower string, lowerOK bool) bool {
|
||||
// textRuleMatches matches a regex or string rule against subject.
|
||||
func textRuleMatches(r compiledRule, subject string) bool {
|
||||
if r.MatchType == "regex" {
|
||||
if r.re == nil {
|
||||
return false
|
||||
}
|
||||
if lowerOK && len(r.reNeedles) > 0 && !needlesMayMatch(lower, r.reNeedles) {
|
||||
return false
|
||||
}
|
||||
return r.re.MatchString(subject)
|
||||
return r.re != nil && r.re.MatchString(subject)
|
||||
}
|
||||
return strings.Contains(subject, r.Pattern)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
@@ -35,11 +36,10 @@ func (i *Interceptor) MatchPersistence(toolName string, input []byte) (Decision,
|
||||
if err != nil {
|
||||
return storeUnreadableDecision(), true
|
||||
}
|
||||
ms := matchState{toolName: toolName, input: input}
|
||||
var ask *compiledRule
|
||||
for idx := range rules {
|
||||
r := rules[idx]
|
||||
if !ruleMatchesState(r, &ms) {
|
||||
if !ruleMatches(r, toolName, input) {
|
||||
continue
|
||||
}
|
||||
if r.Action == "deny" {
|
||||
@@ -60,12 +60,9 @@ func persistenceDecision(r compiledRule) Decision {
|
||||
if msg == "" {
|
||||
msg = defaultMessage(r.Action, r.Name)
|
||||
}
|
||||
digest := r.configDigest
|
||||
if digest == "" {
|
||||
digest = ruleConfigDigest(r.InterceptRule)
|
||||
}
|
||||
configJSON, _ := json.Marshal(r.InterceptRule)
|
||||
return Decision{
|
||||
RuleName: r.Name, ConfigDigest: digest,
|
||||
RuleName: r.Name, ConfigDigest: digestInput(configJSON),
|
||||
Action: r.Action,
|
||||
Message: msg,
|
||||
RuleID: r.ID,
|
||||
|
||||
@@ -1,321 +0,0 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"golang.org/x/net/idna"
|
||||
)
|
||||
|
||||
// Property 1: Soundness of extractRegexNeedles prefilter.
|
||||
// Invariant: for any regex pattern and ASCII subject s, if the prefilter says
|
||||
// no needle matches asciiLower(s), then re.MatchString(s) MUST be false.
|
||||
func TestPropertyRegexPrefilterSoundness(t *testing.T) {
|
||||
patterns := []string{
|
||||
`(?i)\brm\b.{0,80}(?:-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*|--recursive|--no-preserve-root)`,
|
||||
`\brm\b[^"'\n]{0,60}["'\s](/|/etc|/bin|/usr|/boot|/var|/lib|/sys|/proc|/dev|/sbin|/root)`,
|
||||
`\bmkfs\b`,
|
||||
`\bdd\b[^|\n]{0,100}\bof=\s*/dev/[a-zA-Z]`,
|
||||
`:\(\)\s*\{[^}]*:\|:`,
|
||||
`\b(?:shutdown|reboot|halt|poweroff|init\s+[06])\b`,
|
||||
`\bkill\s+-9\s+-1\b|\bkillall\s+-9\b`,
|
||||
`\b(?:shred|wipe)\b[^|\n]{0,80}/dev/[a-zA-Z]`,
|
||||
`\biptables\s+(?:-F|--flush)\b|\bnft\s+flush\s+ruleset\b`,
|
||||
`(?i)\bDROP\s+(?:DATABASE|TABLE|SCHEMA|INDEX|VIEW|TABLESPACE|USER|ROLE)\b`,
|
||||
`(?i)\bTRUNCATE\s+(?:TABLE\s+)?\w`,
|
||||
`(?i)\.(?:dropDatabase|dropCollection|drop)\s*\(`,
|
||||
`(?i)\b(?:FLUSHALL|FLUSHDB)\b`,
|
||||
`(?i)\bcurl\b[^|\n&;"]{0,300}(?:-X\s*DELETE|--request\s+DELETE|-XDELETE)|\bwget\b[^|\n&;"]{0,300}--method[=\s]+DELETE`,
|
||||
`(?i)\b(?:requests|httpx|aiohttp|urllib\.request)\.delete\s*\(|session\.delete\s*\(|client\.delete\s*\(`,
|
||||
`(?i)axios\.delete\s*\(|method\s*[:=]\s*['"]DELETE['"]`,
|
||||
`(?i)/(?:clear|wipe|flush|purge|truncate|drop|destroy|factory[-_]reset|reset[-_]all)(?:[/?#"'\s]|$)`,
|
||||
`(?i)/(?:(?:delete|remove|unlink|erase|destroy)[-\w]*|del)(?:[/?#"'\s]|$)`,
|
||||
`foo+bar`,
|
||||
`(alpha|beta|gamma){2,4}`,
|
||||
`(?:a|b)?c`,
|
||||
`.*`,
|
||||
`^$`,
|
||||
}
|
||||
rng := rand.New(rand.NewPCG(42, 99))
|
||||
vocab := []string{
|
||||
"rm", "RM", "-rf", "/etc", "mkfs", "dd", "of=", "/dev/sda", ":(){:|:&};:",
|
||||
"shutdown", "reboot", "kill -9 -1", "iptables -F", "DROP TABLE", "truncate x",
|
||||
".drop(", "FLUSHALL", "curl", "-X", "DELETE", "wget", "--method=DELETE",
|
||||
"requests.delete(", "axios.delete(", "/clear", "/delete", "foobar", "alpha", "beta",
|
||||
"echo", "hello", " ", "/", "-", "'", `"`, ";", "|", "\n", "k", "K", "s", "S",
|
||||
}
|
||||
for _, pat := range patterns {
|
||||
re := regexp.MustCompile(pat)
|
||||
needles := extractRegexNeedles(pat)
|
||||
for range 500 {
|
||||
var sb strings.Builder
|
||||
n := rng.IntN(8) + 1
|
||||
for range n {
|
||||
sb.WriteString(vocab[rng.IntN(len(vocab))])
|
||||
}
|
||||
s := sb.String()
|
||||
lower, ok := asciiLower(s)
|
||||
if ok && len(needles) > 0 && !needlesMayMatch(lower, needles) {
|
||||
if re.MatchString(s) {
|
||||
t.Fatalf("SOUNDNESS VIOLATION: pattern=%q needles=%v rejected %q but regexp matched", pat, needles, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 2: Fast ASCII hostname path equivalence with idna.Lookup.ToASCII +
|
||||
// NormalizeTarget idempotence + IPv4 form equivalence (fixes a5000882, f67f7ef4).
|
||||
func TestPropertyNormalizeTargetInvariants(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(101, 202))
|
||||
chars := "abcdefghijklmnopqrstuvwxyz0123456789.-_ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
|
||||
// 2a: isPlainLowerASCIIHost(h) => idna.Lookup.ToASCII(h) == h
|
||||
for range 5000 {
|
||||
n := rng.IntN(40) + 1
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = chars[rng.IntN(len(chars))]
|
||||
}
|
||||
h := string(b)
|
||||
if isPlainLowerASCIIHost(h) {
|
||||
got, err := idna.Lookup.ToASCII(h)
|
||||
if err != nil || got != h {
|
||||
t.Fatalf("isPlainLowerASCIIHost(%q)=true, but idna.Lookup.ToASCII=%q err=%v", h, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2b: IPv4 dotted / decimal / hex / octal / mapped-IPv6 all canonicalize identically.
|
||||
for range 500 {
|
||||
o0, o1, o2, o3 := rng.IntN(256), rng.IntN(256), rng.IntN(256), rng.IntN(256)
|
||||
want := fmt.Sprintf("%d.%d.%d.%d", o0, o1, o2, o3)
|
||||
u32 := uint32(o0)<<24 | uint32(o1)<<16 | uint32(o2)<<8 | uint32(o3)
|
||||
port := rng.IntN(65535) + 1
|
||||
forms := []string{
|
||||
fmt.Sprintf("http://%s:%d/path", want, port),
|
||||
fmt.Sprintf("http://%d:%d/path", u32, port),
|
||||
fmt.Sprintf("http://0x%08x:%d/path", u32, port),
|
||||
fmt.Sprintf("http://0%o.0%o.0%o.0%o:%d/path", o0, o1, o2, o3, port),
|
||||
fmt.Sprintf("http://[::ffff:%s]:%d/path", want, port),
|
||||
}
|
||||
for _, f := range forms {
|
||||
got, ok := NormalizeTarget(f)
|
||||
if !ok || got.Kind != TargetIP || got.Host != want || got.Port != port {
|
||||
t.Fatalf("NormalizeTarget(%q) = (%+v, %v), want {ip %s %d}", f, got, ok, want, port)
|
||||
}
|
||||
// Idempotence: normalizing canonical string reproduces the exact same Target.
|
||||
got2, ok2 := NormalizeTarget(got.String())
|
||||
if !ok2 || got2 != got {
|
||||
t.Fatalf("NormalizeTarget not idempotent on %q: first=%+v second=(%+v,%v)", f, got, got2, ok2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 3: Historical bug #984 (fc94b108, 52d1b3af, 3559d0c8):
|
||||
// shell-expansion, /dev/tcp, IP:port, and CIDR shapes ALWAYS extract as targets,
|
||||
// while plain User-Agent/version shapes NEVER extract as bare IPv4 targets.
|
||||
func TestPropertyVersionSkipVsRealTargets(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(984, 984))
|
||||
uaNames := []string{"Chrome", "Edg", "Firefox", "Go-http-client", "app", "Safari"}
|
||||
for range 300 {
|
||||
ip := fmt.Sprintf("%d.%d.%d.%d", 1+rng.IntN(220), rng.IntN(256), rng.IntN(256), 1+rng.IntN(254))
|
||||
port := 1 + rng.IntN(65535)
|
||||
prefixLen := 8 + rng.IntN(25)
|
||||
mustExtract := []string{
|
||||
fmt.Sprintf("curl ${x-%s}", ip),
|
||||
fmt.Sprintf("curl ${x:-%s}", ip),
|
||||
fmt.Sprintf("curl ${!x-%s}", ip),
|
||||
fmt.Sprintf("exec 3<>'/dev/'tcp/%s/%d", ip, port),
|
||||
fmt.Sprintf("exec 3<>/dev/''udp/%s/%d", ip, port),
|
||||
fmt.Sprintf("curl tcp/%s:%d", ip, port),
|
||||
fmt.Sprintf("nmap net/%s/%d", ip, prefixLen),
|
||||
fmt.Sprintf("curl //%s:%d/test", ip, port),
|
||||
}
|
||||
for _, cmd := range mustExtract {
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
ts := ExtractTargets("Bash", raw)
|
||||
found := false
|
||||
for _, tgt := range ts {
|
||||
if tgt.Kind == TargetIP && tgt.Host == ip {
|
||||
found = true
|
||||
}
|
||||
if tgt.Kind == TargetCIDR {
|
||||
if p, err := netip.ParsePrefix(tgt.Host); err == nil {
|
||||
if a, err := netip.ParseAddr(ip); err == nil && p.Contains(a) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("#984 property violated: %q failed to extract %s (got %+v)", cmd, ip, ts)
|
||||
}
|
||||
}
|
||||
|
||||
ua := uaNames[rng.IntN(len(uaNames))]
|
||||
mustSkip := []string{
|
||||
fmt.Sprintf("curl -A %s/%s echo", ua, ip),
|
||||
fmt.Sprintf("curl -H 'User-Agent: %s/%s' echo", ua, ip),
|
||||
fmt.Sprintf("echo %s-%s", ua, ip),
|
||||
}
|
||||
for _, cmd := range mustSkip {
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
if ts := ExtractTargets("Bash", raw); len(ts) != 0 {
|
||||
t.Fatalf("#984 property violated: version token %q extracted targets %+v", cmd, ts)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 4: Historical bug #849 / #863 (5dc46272, dc3e75c3, 3d15d568):
|
||||
// Python/JS subscripts never extract as IPv6, while real bracketed IPv6 always does.
|
||||
func TestPropertyBracketSubscriptVsIPv6(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(849, 863))
|
||||
idents := []string{"d", "arr", "items_1", "data", "res"}
|
||||
for range 200 {
|
||||
id := idents[rng.IntN(len(idents))]
|
||||
k := rng.IntN(9) + 1
|
||||
subscripts := []string{
|
||||
fmt.Sprintf("python3 -c 'print(%s[::%d])'", id, k),
|
||||
fmt.Sprintf("python3 -c 'print(%s[%d][::%d])'", id, k, k),
|
||||
fmt.Sprintf("python3 -c 'print(%s()[::%d])'", id, k),
|
||||
}
|
||||
for _, cmd := range subscripts {
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
if ts := ExtractTargets("Bash", raw); len(ts) != 0 {
|
||||
t.Fatalf("#849 property violated: subscript %q extracted %+v", cmd, ts)
|
||||
}
|
||||
}
|
||||
|
||||
port := 1 + rng.IntN(65535)
|
||||
realV6 := fmt.Sprintf("curl -g http://[2001:db8::%x]:%d/", k, port)
|
||||
raw, _ := json.Marshal(map[string]string{"command": realV6})
|
||||
ts := ExtractTargets("Bash", raw)
|
||||
want := Target{Kind: TargetIP, Host: fmt.Sprintf("2001:db8::%x", k), Port: port}
|
||||
if len(ts) != 1 || ts[0] != want {
|
||||
t.Fatalf("#849 property violated: %q extracted %+v, want [%+v]", realV6, ts, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 5: Historical bug #1013 (c9a0bbac):
|
||||
// Case-insensitive and duplicate JSON "command" keys ALWAYS produce the exact
|
||||
// same Match verdict as canonical {"command": <effectiveCommand>}.
|
||||
func TestPropertyCaseInsensitiveJSONCommandParity(t *testing.T) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest(benchRuleSet())
|
||||
rng := rand.New(rand.NewPCG(1013, 1013))
|
||||
cmds := []string{
|
||||
`r\m -r -f /tmp/x`,
|
||||
`r''m -rf /etc/passwd`,
|
||||
`curl -X DELETE https://example.com/a`,
|
||||
`echo hello world`,
|
||||
`git push origin main`,
|
||||
`sudo env FOO=1 kubectl delete pod x`,
|
||||
}
|
||||
randCase := func(s string) string {
|
||||
b := []byte(s)
|
||||
for i := range b {
|
||||
if rng.IntN(2) == 1 {
|
||||
b[i] -= 'a' - 'A'
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
for range 300 {
|
||||
cmd := cmds[rng.IntN(len(cmds))]
|
||||
canon, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
wantDec, wantOK := ic.Match("Bash", canon)
|
||||
|
||||
cmdJSON, _ := json.Marshal(cmd)
|
||||
key := randCase("command")
|
||||
variant := []byte(fmt.Sprintf(`{"command":"echo harmless",%q:%s}`, key, string(cmdJSON)))
|
||||
gotDec, gotOK := ic.Match("Bash", variant)
|
||||
if gotOK != wantOK || gotDec.Action != wantDec.Action || gotDec.RuleName != wantDec.RuleName {
|
||||
t.Fatalf("#1013 parity violated for key=%q cmd=%q: got=(%v,%q,%q) want=(%v,%q,%q)",
|
||||
key, cmd, gotOK, gotDec.Action, gotDec.RuleName, wantOK, wantDec.Action, wantDec.RuleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 6: Historical bug #990 (d785c7d9, bbdb064a, da00bf7c, 8f0b73f5):
|
||||
// Argv deny rule MUST deny any wrapped/quoted invocation and MUST NOT return
|
||||
// ok=false on opaque dynamic shell execution.
|
||||
func TestPropertyArgvFailClosedWrappersAndDynamic(t *testing.T) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest([]db.InterceptRule{
|
||||
{ID: 1, Name: "deny targetcmd", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["rm"]`, Action: "deny"},
|
||||
})
|
||||
rng := rand.New(rand.NewPCG(990, 990))
|
||||
wrappers := []string{
|
||||
"sudo", "sudo -u root", "env FOO=1", "timeout 10", "nice -n 5",
|
||||
"nohup", "setsid", "command", "exec", "stdbuf -oL",
|
||||
}
|
||||
obfuscated := []string{`rm`, `r''m`, `r""m`, `r\m`, `/bin/rm`, `/usr/bin/r\m`}
|
||||
|
||||
for range 200 {
|
||||
depth := 1 + rng.IntN(3)
|
||||
var parts []string
|
||||
for range depth {
|
||||
parts = append(parts, wrappers[rng.IntN(len(wrappers))])
|
||||
}
|
||||
parts = append(parts, obfuscated[rng.IntN(len(obfuscated))], "-rf", "/tmp/x")
|
||||
cmd := strings.Join(parts, " ")
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
dec, ok := ic.Match("Bash", raw)
|
||||
if !ok || dec.Action != "deny" {
|
||||
t.Fatalf("#990 wrapper bypass: %q -> ok=%v action=%q", cmd, ok, dec.Action)
|
||||
}
|
||||
}
|
||||
|
||||
dynamic := []string{
|
||||
`CMD=rm; $CMD -rf /tmp/x`,
|
||||
`echo cm0gLXJmIC90bXAvWA== | base64 -d | sh`,
|
||||
`sh -c "$(echo cm0gLXJmIC90bXAvWA== | base64 -d)"`,
|
||||
`eval "$(echo cm0gLXJmIC90bXAvWA== | base64 -d)"`,
|
||||
`bash <(echo cm0gLXJmIC90bXAvWA== | base64 -d)`,
|
||||
`bash <<< "$(echo cm0gLXJmIC90bXAvWA== | base64 -d)"`,
|
||||
`source <(echo cm0gLXJmIC90bXAvWA== | base64 -d)`,
|
||||
`echo cm0gLXJmIC90bXAvWA== | base64 -d | xargs sh -c`,
|
||||
}
|
||||
for _, cmd := range dynamic {
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
dec, ok := ic.Match("Bash", raw)
|
||||
if !ok || (dec.Action != "ask" && dec.Action != "deny") {
|
||||
t.Fatalf("#990 dynamic fail-closed violated: %q -> ok=%v action=%q", cmd, ok, dec.Action)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 7: Historical bug #687 (44ea93a2, b8ca0054, df30888f):
|
||||
// Curl attached and spaced body/method flags are always classified as mutating.
|
||||
func TestPropertyStatefulGuardCurlMutating(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(687, 687))
|
||||
methods := []string{"POST", "PUT", "PATCH", "DELETE", "post", "delete"}
|
||||
flags := []string{
|
||||
"-dfoo=bar", "-d foo=bar", "--data=foo=bar", "--data-raw=x",
|
||||
"-Ffile=@a", "-T/tmp/a", "--json={}", "--upload-file=/tmp/a",
|
||||
}
|
||||
for range 100 {
|
||||
m := methods[rng.IntN(len(methods))]
|
||||
for _, cmd := range []string{
|
||||
fmt.Sprintf("curl -X %s https://app.example.com/items", m),
|
||||
fmt.Sprintf("curl -X%s https://app.example.com/items", m),
|
||||
fmt.Sprintf("curl --request=%s https://app.example.com/items", m),
|
||||
fmt.Sprintf("curl %s https://app.example.com/items", flags[rng.IntN(len(flags))]),
|
||||
} {
|
||||
raw, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
if _, mutating := ClassifyHTTPAction("Bash", raw, "", ""); !mutating {
|
||||
t.Fatalf("#687 property violated: %q classified as non-mutating", cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,7 @@ type StatefulTargetGuard struct {
|
||||
leases map[string]mutationLease // taskID+"\x00"+host -> lease entry
|
||||
baselines map[string]bool // taskID+"\x00"+host -> true once read-only GET completed
|
||||
now func() time.Time
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewStatefulTargetGuard() *StatefulTargetGuard {
|
||||
@@ -126,6 +127,16 @@ func (g *StatefulTargetGuard) SetClock(fn func() time.Time) {
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetTTL overrides the lease heartbeat TTL on this guard instance (0 = read env).
|
||||
func (g *StatefulTargetGuard) SetTTL(d time.Duration) {
|
||||
if g == nil {
|
||||
return
|
||||
}
|
||||
g.mu.Lock()
|
||||
g.ttl = d
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
func (g *StatefulTargetGuard) clockNow() time.Time {
|
||||
if g.now != nil {
|
||||
return g.now().UTC()
|
||||
@@ -134,6 +145,9 @@ func (g *StatefulTargetGuard) clockNow() time.Time {
|
||||
}
|
||||
|
||||
func (g *StatefulTargetGuard) effectiveTTL() time.Duration {
|
||||
if g != nil && g.ttl > 0 {
|
||||
return g.ttl
|
||||
}
|
||||
return StatefulLeaseTTL()
|
||||
}
|
||||
|
||||
|
||||
+9
-71
@@ -47,7 +47,7 @@ func NormalizeTarget(raw string) (Target, bool) {
|
||||
def, isURL := 0, false
|
||||
if i := strings.Index(raw, "://"); i > 0 {
|
||||
isURL = true
|
||||
def = schemePorts[toLowerFast(raw[:i])]
|
||||
def = schemePorts[strings.ToLower(raw[:i])]
|
||||
raw = raw[i+3:]
|
||||
if end := strings.IndexAny(raw, "/?#"); end >= 0 {
|
||||
raw = raw[:end]
|
||||
@@ -71,7 +71,7 @@ func NormalizeTarget(raw string) (Target, bool) {
|
||||
case strings.Count(raw, ":") == 1:
|
||||
host, port, _ = strings.Cut(raw, ":")
|
||||
}
|
||||
if isURL && !strings.HasPrefix(raw, "[") && strings.IndexByte(host, '%') >= 0 {
|
||||
if isURL && !strings.HasPrefix(raw, "[") {
|
||||
// A client decodes a percent-encoded host before it resolves it.
|
||||
if decoded, err := url.PathUnescape(host); err == nil {
|
||||
host = decoded
|
||||
@@ -90,58 +90,16 @@ func NormalizeTarget(raw string) (Target, bool) {
|
||||
return t, ok
|
||||
}
|
||||
|
||||
// toLowerFast avoids allocating when s is already lowercase ASCII.
|
||||
func toLowerFast(s string) string {
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'A' && c <= 'Z' || c >= 0x80 {
|
||||
return strings.ToLower(s)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// isPlainLowerASCIIHost reports whether h is a non-empty lowercase ASCII DNS
|
||||
// name containing no punycode labels ("xn--"), for which idna.Lookup.ToASCII is
|
||||
// guaranteed to be the identity function.
|
||||
func isPlainLowerASCIIHost(h string) bool {
|
||||
if len(h) == 0 || len(h) > 253 {
|
||||
return false
|
||||
}
|
||||
labelStart := 0
|
||||
for i := 0; i <= len(h); i++ {
|
||||
if i == len(h) || h[i] == '.' {
|
||||
labelLen := i - labelStart
|
||||
if labelLen == 0 || labelLen > 63 {
|
||||
return false
|
||||
}
|
||||
if h[labelStart] == '-' || h[i-1] == '-' {
|
||||
return false
|
||||
}
|
||||
if labelLen >= 4 && h[labelStart] == 'x' && h[labelStart+1] == 'n' && h[labelStart+2] == '-' && h[labelStart+3] == '-' {
|
||||
return false
|
||||
}
|
||||
labelStart = i + 1
|
||||
continue
|
||||
}
|
||||
c := h[i]
|
||||
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// normalizeHost returns the kind and the canonical form of a host. numeric
|
||||
// accepts the forms of an IPv4 address that are not dotted decimal
|
||||
// (2130706433, 0x7f000001, 0177.0.0.1, 127.1), which a URL host may use; in
|
||||
// free text they would turn every number into an address.
|
||||
func normalizeHost(raw string, numeric bool) (kind, host string, ok bool) {
|
||||
h := strings.TrimSuffix(toLowerFast(strings.TrimSpace(raw)), ".")
|
||||
h := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(raw)), ".")
|
||||
if h == "" {
|
||||
return "", "", false
|
||||
}
|
||||
if strings.IndexByte(h, '/') >= 0 {
|
||||
if strings.Contains(h, "/") {
|
||||
p, err := netip.ParsePrefix(h)
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
@@ -151,14 +109,11 @@ func normalizeHost(raw string, numeric bool) (kind, host string, ok bool) {
|
||||
if a, err := netip.ParseAddr(h); err == nil {
|
||||
return TargetIP, a.Unmap().WithZone("").String(), true
|
||||
}
|
||||
if numeric && h[0] >= '0' && h[0] <= '9' {
|
||||
if numeric {
|
||||
if a, ok := parseIPv4Forms(h); ok {
|
||||
return TargetIP, a.String(), true
|
||||
}
|
||||
}
|
||||
if isPlainLowerASCIIHost(h) {
|
||||
return TargetDomain, h, true
|
||||
}
|
||||
// A name the profile refuses is kept as written: it then fails to resolve and
|
||||
// the call is blocked, instead of passing as a call without a target.
|
||||
if name, err := hostProfile.ToASCII(h); err == nil && name != "" {
|
||||
@@ -171,29 +126,12 @@ func normalizeHost(raw string, numeric bool) (kind, host string, ok bool) {
|
||||
// parts, each decimal, hex (0x) or octal (leading 0), the last one filling the
|
||||
// remaining bytes.
|
||||
func parseIPv4Forms(s string) (netip.Addr, bool) {
|
||||
if s == "" || s[0] < '0' || s[0] > '9' {
|
||||
parts := strings.Split(s, ".")
|
||||
if len(parts) > 4 {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
var parts [4]string
|
||||
nParts := 0
|
||||
rem := s
|
||||
for {
|
||||
if nParts == 4 {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
dot := strings.IndexByte(rem, '.')
|
||||
if dot < 0 {
|
||||
parts[nParts] = rem
|
||||
nParts++
|
||||
break
|
||||
}
|
||||
parts[nParts] = rem[:dot]
|
||||
nParts++
|
||||
rem = rem[dot+1:]
|
||||
}
|
||||
var v uint64
|
||||
for n := 0; n < nParts; n++ {
|
||||
p := parts[n]
|
||||
for n, p := range parts {
|
||||
base := 10
|
||||
switch {
|
||||
case strings.HasPrefix(p, "0x"):
|
||||
@@ -205,7 +143,7 @@ func parseIPv4Forms(s string) (netip.Addr, bool) {
|
||||
if err != nil {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
if n < nParts-1 {
|
||||
if n < len(parts)-1 {
|
||||
if x > 255 {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
|
||||
+122
-191
@@ -17,7 +17,7 @@ const executeExtraTool = "ExecuteExtraTool"
|
||||
// tool (its input is a query), the file and session tools, and the platform's
|
||||
// domain tools, which read and write the platform's own records. Every name
|
||||
// that is not listed here is scanned, so a tool added later is gated by default.
|
||||
var noTargetTools = strSet(
|
||||
var noTargetTools = toolSet(
|
||||
"web_search",
|
||||
"Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep",
|
||||
"TodoWrite", "sleep", "TaskOutput", "TaskStop", "TaskList",
|
||||
@@ -48,6 +48,14 @@ var noTargetTools = strSet(
|
||||
"traffic_search", "traffic_get", "traffic_blob", "traffic_messages",
|
||||
)
|
||||
|
||||
func toolSet(names ...string) map[string]bool {
|
||||
m := make(map[string]bool, len(names))
|
||||
for _, n := range names {
|
||||
m[n] = true
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// ExtractTargets returns the network targets a tool call declares in its
|
||||
// input, normalised and without duplicates, in order of appearance.
|
||||
//
|
||||
@@ -206,46 +214,13 @@ func (l *targetList) scan(s string) {
|
||||
if s == "" {
|
||||
return
|
||||
}
|
||||
var dotCount, colonCount int
|
||||
var hasLBracket, hasRBracket, hasSlash, hasNonASCII bool
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] >= 0x80 {
|
||||
hasNonASCII = true
|
||||
}
|
||||
switch s[i] {
|
||||
case '.':
|
||||
dotCount++
|
||||
case ':':
|
||||
colonCount++
|
||||
case '[':
|
||||
hasLBracket = true
|
||||
case ']':
|
||||
hasRBracket = true
|
||||
case '/':
|
||||
hasSlash = true
|
||||
}
|
||||
}
|
||||
canURL := colonCount > 0 && hasSlash && strings.Contains(s, "://")
|
||||
canBracket := hasLBracket && hasRBracket
|
||||
canIPv6 := colonCount >= 2
|
||||
canIPv4 := dotCount >= 3
|
||||
// The host:port pattern is case-insensitive over Unicode, so a non-ASCII
|
||||
// letter that folds to an ASCII one (ſ for s) matches it. Any non-ASCII byte
|
||||
// keeps that pass enabled instead of deciding from an ASCII-only substring.
|
||||
canHostPort := colonCount > 0 && (dotCount > 0 || hasNonASCII || containsASCIIFold(s, "localhost:"))
|
||||
if !canURL && !canBracket && !canIPv6 && !canIPv4 && !canHostPort {
|
||||
return
|
||||
}
|
||||
b := []byte(s)
|
||||
var orig []byte
|
||||
if canBracket {
|
||||
// Left context for the subscript guard below must come from the
|
||||
// original bytes: a matched bracket is blanked as it is read, so by
|
||||
// the time a chained subscript like `a[1][::2]` is examined, the `]`
|
||||
// before it has been blanked and no longer proves the glue.
|
||||
orig = make([]byte, len(b))
|
||||
copy(orig, b)
|
||||
}
|
||||
// Left context for the subscript guard below must come from the
|
||||
// original bytes: a matched bracket is blanked as it is read, so by
|
||||
// the time a chained subscript like `a[1][::2]` is examined, the `]`
|
||||
// before it has been blanked and no longer proves the glue.
|
||||
orig := make([]byte, len(b))
|
||||
copy(orig, b)
|
||||
blank := func(from, to int) {
|
||||
for i := from; i < to; i++ {
|
||||
b[i] = ' '
|
||||
@@ -258,166 +233,122 @@ func (l *targetList) scan(s string) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if canURL {
|
||||
each(reURL, func(m []int) bool {
|
||||
scheme, found := string(b[m[2]:m[3]]), false
|
||||
for _, host := range urlHosts(string(b[m[4]:m[5]])) {
|
||||
// A host that is not a name ($HOST, a glob) is what the shell or the
|
||||
// client will make of it, which the gate cannot read.
|
||||
if t, ok := NormalizeTarget(scheme + host); ok && (t.Kind != TargetDomain || validHostname(t.Host)) {
|
||||
l.add(t)
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if found {
|
||||
// The whole token, path and query included, from the original string.
|
||||
l.urls = append(l.urls, s[m[0]:m[1]])
|
||||
}
|
||||
// The scheme and what follows the authority are never read again. An
|
||||
// authority that named no host is: an address written in it still counts.
|
||||
blank(m[0], m[4])
|
||||
blank(m[5], m[1])
|
||||
return found
|
||||
})
|
||||
}
|
||||
if canBracket {
|
||||
each(reBracketed, func(m []int) bool {
|
||||
if m[0] > 0 && (isWord(orig[m[0]-1]) || orig[m[0]-1] == ']' || orig[m[0]-1] == ')') {
|
||||
// Not a bracketed address: a subscript glued to an expression.
|
||||
// A bracketed IPv6 stands at the edge of a token or follows `:`,
|
||||
// `/` or `@` in a URL; it is never glued to a word character, and
|
||||
// never glued to the `]` or `)` that close a subscript or a call.
|
||||
// `d[::2][::-1]` is a Python step slice, `a[1][::2]` a chained
|
||||
// subscript and `f()[::2]` a subscript on a call result: the
|
||||
// brackets hold slice bounds that happen to read as a valid
|
||||
// address. Consume the subscript, so the IPv6 rule below does not
|
||||
// read the same bounds again.
|
||||
blank(m[0], m[1])
|
||||
return false
|
||||
}
|
||||
a, err := netip.ParseAddr(string(b[m[2]:m[3]]))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
t := Target{Kind: TargetIP, Host: a.Unmap().WithZone("").String()}
|
||||
if m[4] >= 0 {
|
||||
t.Port = validPort(string(b[m[4]:m[5]]))
|
||||
}
|
||||
l.add(t)
|
||||
return true
|
||||
})
|
||||
}
|
||||
if canIPv6 {
|
||||
each(reIPv6, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
if start > 0 && isWord(b[start-1]) || end < len(b) && (isWord(b[end]) || b[end] == ':') {
|
||||
return false
|
||||
}
|
||||
kind, host, ok := normalizeHost(string(b[start:end]), false)
|
||||
// "::" alone is punctuation (a slice, a scope operator), not an address.
|
||||
if !ok || kind == TargetDomain || host == "::" {
|
||||
return false
|
||||
}
|
||||
l.add(Target{Kind: kind, Host: host})
|
||||
return true
|
||||
})
|
||||
}
|
||||
if canIPv4 {
|
||||
each(reIPv4, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
if start > 0 && (isWord(b[start-1]) || b[start-1] == '.') {
|
||||
return false
|
||||
}
|
||||
// A port or a prefix length makes the quad a target, not a version
|
||||
// token: a name/version component has neither.
|
||||
if bytes.IndexAny(b[start:end], "/:") < 0 && hasVersionPrefix(b, start) {
|
||||
return false
|
||||
}
|
||||
// The address alone, when what follows it is not a port or a prefix length.
|
||||
addrEnd := start + bytes.IndexAny(b[start:end], "/:")
|
||||
if addrEnd < start {
|
||||
addrEnd = end
|
||||
}
|
||||
if !endsToken(b, end) {
|
||||
end = addrEnd
|
||||
if !endsToken(b, end) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
a, err := netip.ParseAddr(string(b[start:addrEnd]))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
t := Target{Kind: TargetIP, Host: a.String()}
|
||||
if end > addrEnd {
|
||||
switch suffix := string(b[addrEnd+1 : end]); b[addrEnd] {
|
||||
case '/':
|
||||
if p, err := netip.ParsePrefix(string(b[start:end])); err == nil {
|
||||
t = Target{Kind: TargetCIDR, Host: p.Masked().String()}
|
||||
}
|
||||
case ':':
|
||||
t.Port = validPort(suffix)
|
||||
}
|
||||
}
|
||||
l.add(t)
|
||||
return true
|
||||
})
|
||||
}
|
||||
if canHostPort {
|
||||
each(reHostPort, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
// Not the tail of a longer word, a path or an address, and not the head of
|
||||
// a version number (name:1.25).
|
||||
if start > 0 && (isWord(b[start-1]) || strings.IndexByte(`.-/\`, b[start-1]) >= 0) {
|
||||
return false
|
||||
each(reURL, func(m []int) bool {
|
||||
scheme, found := string(b[m[2]:m[3]]), false
|
||||
for _, host := range urlHosts(string(b[m[4]:m[5]])) {
|
||||
// A host that is not a name ($HOST, a glob) is what the shell or the
|
||||
// client will make of it, which the gate cannot read.
|
||||
if t, ok := NormalizeTarget(scheme + host); ok && (t.Kind != TargetDomain || validHostname(t.Host)) {
|
||||
l.add(t)
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if found {
|
||||
// The whole token, path and query included, from the original string.
|
||||
l.urls = append(l.urls, s[m[0]:m[1]])
|
||||
}
|
||||
// The scheme and what follows the authority are never read again. An
|
||||
// authority that named no host is: an address written in it still counts.
|
||||
blank(m[0], m[4])
|
||||
blank(m[5], m[1])
|
||||
return found
|
||||
})
|
||||
each(reBracketed, func(m []int) bool {
|
||||
if m[0] > 0 && (isWord(orig[m[0]-1]) || orig[m[0]-1] == ']' || orig[m[0]-1] == ')') {
|
||||
// Not a bracketed address: a subscript glued to an expression.
|
||||
// A bracketed IPv6 stands at the edge of a token or follows `:`,
|
||||
// `/` or `@` in a URL; it is never glued to a word character, and
|
||||
// never glued to the `]` or `)` that close a subscript or a call.
|
||||
// `d[::2][::-1]` is a Python step slice, `a[1][::2]` a chained
|
||||
// subscript and `f()[::2]` a subscript on a call result: the
|
||||
// brackets hold slice bounds that happen to read as a valid
|
||||
// address. Consume the subscript, so the IPv6 rule below does not
|
||||
// read the same bounds again.
|
||||
blank(m[0], m[1])
|
||||
return false
|
||||
}
|
||||
a, err := netip.ParseAddr(string(b[m[2]:m[3]]))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
t := Target{Kind: TargetIP, Host: a.Unmap().WithZone("").String()}
|
||||
if m[4] >= 0 {
|
||||
t.Port = validPort(string(b[m[4]:m[5]]))
|
||||
}
|
||||
l.add(t)
|
||||
return true
|
||||
})
|
||||
each(reIPv6, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
if start > 0 && isWord(b[start-1]) || end < len(b) && (isWord(b[end]) || b[end] == ':') {
|
||||
return false
|
||||
}
|
||||
kind, host, ok := normalizeHost(string(b[start:end]), false)
|
||||
// "::" alone is punctuation (a slice, a scope operator), not an address.
|
||||
if !ok || kind == TargetDomain || host == "::" {
|
||||
return false
|
||||
}
|
||||
l.add(Target{Kind: kind, Host: host})
|
||||
return true
|
||||
})
|
||||
each(reIPv4, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
if start > 0 && (isWord(b[start-1]) || b[start-1] == '.') {
|
||||
return false
|
||||
}
|
||||
// A port or a prefix length makes the quad a target, not a version
|
||||
// token: a name/version component has neither.
|
||||
if bytes.IndexAny(b[start:end], "/:") < 0 && hasVersionPrefix(b, start) {
|
||||
return false
|
||||
}
|
||||
// The address alone, when what follows it is not a port or a prefix length.
|
||||
addrEnd := start + bytes.IndexAny(b[start:end], "/:")
|
||||
if addrEnd < start {
|
||||
addrEnd = end
|
||||
}
|
||||
if !endsToken(b, end) {
|
||||
end = addrEnd
|
||||
if !endsToken(b, end) {
|
||||
return false
|
||||
}
|
||||
host, port, _ := strings.Cut(string(b[start:end]), ":")
|
||||
n := validPort(port)
|
||||
_, host, ok := normalizeHost(host, false)
|
||||
if n == 0 || !ok {
|
||||
return false
|
||||
}
|
||||
l.add(Target{Kind: TargetDomain, Host: host, Port: n})
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// containsASCIIFold reports whether s contains needle (which must be lowercase ASCII)
|
||||
// ignoring ASCII letter case, with zero allocations.
|
||||
func containsASCIIFold(s, needle string) bool {
|
||||
if len(needle) == 0 || len(s) < len(needle) {
|
||||
return false
|
||||
}
|
||||
first := needle[0]
|
||||
limit := len(s) - len(needle)
|
||||
for i := 0; i <= limit; i++ {
|
||||
c := s[i]
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
if c != first {
|
||||
continue
|
||||
a, err := netip.ParseAddr(string(b[start:addrEnd]))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
match := true
|
||||
for j := 1; j < len(needle); j++ {
|
||||
cj := s[i+j]
|
||||
if cj >= 'A' && cj <= 'Z' {
|
||||
cj += 'a' - 'A'
|
||||
}
|
||||
if cj != needle[j] {
|
||||
match = false
|
||||
break
|
||||
t := Target{Kind: TargetIP, Host: a.String()}
|
||||
if end > addrEnd {
|
||||
switch suffix := string(b[addrEnd+1 : end]); b[addrEnd] {
|
||||
case '/':
|
||||
if p, err := netip.ParsePrefix(string(b[start:end])); err == nil {
|
||||
t = Target{Kind: TargetCIDR, Host: p.Masked().String()}
|
||||
}
|
||||
case ':':
|
||||
t.Port = validPort(suffix)
|
||||
}
|
||||
}
|
||||
if match {
|
||||
return true
|
||||
l.add(t)
|
||||
return true
|
||||
})
|
||||
each(reHostPort, func(m []int) bool {
|
||||
start, end := m[0], m[1]
|
||||
// Not the tail of a longer word, a path or an address, and not the head of
|
||||
// a version number (name:1.25).
|
||||
if start > 0 && (isWord(b[start-1]) || strings.IndexByte(`.-/\`, b[start-1]) >= 0) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
if !endsToken(b, end) {
|
||||
return false
|
||||
}
|
||||
host, port, _ := strings.Cut(string(b[start:end]), ":")
|
||||
n := validPort(port)
|
||||
_, host, ok := normalizeHost(host, false)
|
||||
if n == 0 || !ok {
|
||||
return false
|
||||
}
|
||||
l.add(Target{Kind: TargetDomain, Host: host, Port: n})
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// endsToken reports whether the token that ends before b[i] really ends there:
|
||||
|
||||
@@ -97,9 +97,6 @@ func TestExtractTargets(t *testing.T) {
|
||||
{"mysql --host=203.0.113.7 -uroot", []Target{{TargetIP, "203.0.113.7", 0}}},
|
||||
{"openssl s_client -connect app.example.com:443 -servername x", []Target{app}},
|
||||
{"nc localhost:8080", []Target{{TargetDomain, "localhost", 8080}}},
|
||||
// The host:port pattern is case-insensitive over Unicode: ſ folds to s,
|
||||
// so localhoſt:8080 names localhost and is still a target.
|
||||
{"curl localhoſt:8080", []Target{{TargetDomain, "localhost", 8080}}},
|
||||
{"ping6 2001:db8::1", []Target{{TargetIP, "2001:db8::1", 0}}},
|
||||
{"curl 'http://[2001:db8::1]:8080/'; nc [2001:db8::2]:22", []Target{{TargetIP, "2001:db8::1", 8080}, {TargetIP, "2001:db8::2", 22}}},
|
||||
{"nmap fd00::/8 ::ffff:203.0.113.7", []Target{{TargetCIDR, "fd00::/8", 0}, {TargetIP, "203.0.113.7", 0}}},
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func BenchmarkEgressPolicyResolveLargeScope(b *testing.B) {
|
||||
domains := make([]string, 2000)
|
||||
for i := range domains {
|
||||
domains[i] = fmt.Sprintf("svc-%04d.corp.example.com", i)
|
||||
}
|
||||
pol, err := NewEgressPolicy("1", domains, []string{"203.0.113.0/24"}, nil)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
pol.Resolver = func(_ context.Context, _ string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("203.0.113.10")}, nil
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
b.Run("allowed_tail", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if _, err := pol.ResolveAndCheck(ctx, "api.svc-1999.corp.example.com"); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
b.Run("denied_miss", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if _, err := pol.ResolveAndCheck(ctx, "evil.unapproved.example.org"); err == nil {
|
||||
b.Fatal("expected deny")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkEgressPolicyCheckURL(b *testing.B) {
|
||||
domains := make([]string, 200)
|
||||
for i := range domains {
|
||||
domains[i] = fmt.Sprintf("app-%03d.example.com", i)
|
||||
}
|
||||
pol, err := NewEgressPolicy("1", domains, []string{"203.0.113.0/24"}, nil)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
pol.Resolver = func(_ context.Context, _ string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("198.51.100.42")}, nil
|
||||
}
|
||||
ctx := context.Background()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
if err := pol.CheckURL(ctx, "https://v1.app-199.example.com/health"); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkValidateExecRequest(b *testing.B) {
|
||||
domains := make([]string, 100)
|
||||
for i := range domains {
|
||||
domains[i] = fmt.Sprintf("*.svc-%03d.example.com", i)
|
||||
}
|
||||
cidrs := make([]string, 50)
|
||||
for i := range cidrs {
|
||||
cidrs[i] = fmt.Sprintf("198.51.100.%d/32", i+1)
|
||||
}
|
||||
env := map[string]string{
|
||||
"TERM": "xterm", "LANG": "C.UTF-8", "CI": "true", "TZ": "UTC",
|
||||
"APP_ENV": "test", "LOG_LEVEL": "info", "NO_COLOR": "1", "PAGER": "cat",
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for b.Loop() {
|
||||
req := ExecRequest{
|
||||
Argv: []string{"curl", "-s", "https://svc-001.example.com/"},
|
||||
Workdir: "/workspace/i1",
|
||||
TimeoutMS: 30000,
|
||||
ScopeDomains: domains,
|
||||
ScopeCIDRs: cidrs,
|
||||
Env: env,
|
||||
}
|
||||
if err := ValidateExecRequest(&req); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-56
@@ -136,9 +136,6 @@ type EgressPolicy struct {
|
||||
// Never lists prefixes denied even when a scope CIDR covers them (the
|
||||
// Kubernetes backend passes cluster and metadata ranges here).
|
||||
Never []netip.Prefix
|
||||
|
||||
domainSet map[string]struct{}
|
||||
domainSetLen int
|
||||
}
|
||||
|
||||
// NewEgressPolicy parses comma-separated domain suffixes and IP/CIDR entries.
|
||||
@@ -147,10 +144,6 @@ func NewEgressPolicy(taskID string, domains, cidrs []string, logger *EgressLogge
|
||||
TaskID: taskID,
|
||||
Logger: logger,
|
||||
}
|
||||
if len(domains) > 0 {
|
||||
p.Domains = make([]string, 0, len(domains))
|
||||
p.domainSet = make(map[string]struct{}, len(domains))
|
||||
}
|
||||
for _, d := range domains {
|
||||
d = strings.ToLower(strings.TrimSpace(d))
|
||||
d = strings.TrimPrefix(d, "*.")
|
||||
@@ -158,19 +151,14 @@ func NewEgressPolicy(taskID string, domains, cidrs []string, logger *EgressLogge
|
||||
d = strings.TrimSuffix(d, ".")
|
||||
if d != "" {
|
||||
p.Domains = append(p.Domains, d)
|
||||
p.domainSet[d] = struct{}{}
|
||||
}
|
||||
}
|
||||
p.domainSetLen = len(p.Domains)
|
||||
if len(cidrs) > 0 {
|
||||
p.CIDRs = make([]netip.Prefix, 0, len(cidrs))
|
||||
}
|
||||
for _, raw := range cidrs {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
if strings.IndexByte(raw, '/') >= 0 {
|
||||
if strings.Contains(raw, "/") {
|
||||
pfx, err := netip.ParsePrefix(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid scope CIDR %q: %w", raw, err)
|
||||
@@ -200,35 +188,13 @@ func ParseCSV(raw string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
func toLowerFast(s string) string {
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'A' && c <= 'Z' || c >= 0x80 {
|
||||
return strings.ToLower(s)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (p *EgressPolicy) domainAllowed(host string) bool {
|
||||
h := toLowerFast(strings.TrimSuffix(strings.TrimSpace(host), "."))
|
||||
h := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), "."))
|
||||
if h == "" {
|
||||
return false
|
||||
}
|
||||
if p.domainSet != nil && len(p.Domains) == p.domainSetLen {
|
||||
for rem := h; ; {
|
||||
if _, ok := p.domainSet[rem]; ok {
|
||||
return true
|
||||
}
|
||||
dot := strings.IndexByte(rem, '.')
|
||||
if dot < 0 || dot+1 >= len(rem) {
|
||||
return false
|
||||
}
|
||||
rem = rem[dot+1:]
|
||||
}
|
||||
}
|
||||
for _, suffix := range p.Domains {
|
||||
if h == suffix || (len(h) > len(suffix) && h[len(h)-len(suffix)-1] == '.' && strings.HasSuffix(h, suffix)) {
|
||||
if h == suffix || strings.HasSuffix(h, "."+suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -264,26 +230,12 @@ func isDefaultDeniedAddr(addr netip.Addr) bool {
|
||||
if addr.Is6() {
|
||||
return true
|
||||
}
|
||||
if !addr.Is4() {
|
||||
return true
|
||||
}
|
||||
b := addr.As4()
|
||||
switch b[0] {
|
||||
case 0, 10, 127:
|
||||
return true // 0.0.0.0/8, 10.0.0.0/8, 127.0.0.0/8
|
||||
case 100:
|
||||
return (b[1] >= 64 && b[1] <= 127) || (b[1] == 100 && b[2] == 100 && b[3] == 200) // 100.64.0.0/10, 100.100.100.200/32
|
||||
case 168:
|
||||
return b[1] == 63 && b[2] == 129 && b[3] == 16 // 168.63.129.16/32
|
||||
case 169:
|
||||
return b[1] == 254 // 169.254.0.0/16
|
||||
case 172:
|
||||
return b[1] >= 16 && b[1] <= 31 // 172.16.0.0/12
|
||||
case 192:
|
||||
return b[1] == 168 // 192.168.0.0/16
|
||||
default:
|
||||
return b[0] >= 224 // 224.0.0.0/4, 240.0.0.0/4
|
||||
for _, pfx := range defaultDeniedPrefixes {
|
||||
if pfx.Contains(addr) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type resolverCtxKey struct{}
|
||||
|
||||
@@ -1,208 +0,0 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Property 1: Exhaustive equivalence between O(1) isDefaultDeniedAddr and
|
||||
// defaultDeniedPrefixes across all 256 /8 IPv4 blocks, edge addresses, and
|
||||
// IPv4-mapped IPv6 forms (fixes #925, d92a02fa).
|
||||
func TestPropertyDefaultDeniedAddrEquivalence(t *testing.T) {
|
||||
ref := func(a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
if a.Is6() {
|
||||
return true
|
||||
}
|
||||
for _, pfx := range defaultDeniedPrefixes {
|
||||
if pfx.Contains(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
check := func(a netip.Addr) {
|
||||
t.Helper()
|
||||
if got, want := isDefaultDeniedAddr(a), ref(a); got != want {
|
||||
t.Fatalf("isDefaultDeniedAddr(%s) = %v, want %v", a, got, want)
|
||||
}
|
||||
if a.Is4() {
|
||||
mapped := netip.AddrFrom16([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a.As4()[0], a.As4()[1], a.As4()[2], a.As4()[3]})
|
||||
if got, want := isDefaultDeniedAddr(mapped), ref(mapped); got != want {
|
||||
t.Fatalf("isDefaultDeniedAddr(%s) = %v, want %v", mapped, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// All 256 first octets with key boundary values.
|
||||
for b0 := 0; b0 < 256; b0++ {
|
||||
for _, b1 := range []int{0, 15, 16, 31, 32, 63, 64, 100, 127, 128, 168, 254, 255} {
|
||||
check(netip.AddrFrom4([4]byte{byte(b0), byte(b1), 0, 0}))
|
||||
check(netip.AddrFrom4([4]byte{byte(b0), byte(b1), 255, 255}))
|
||||
}
|
||||
}
|
||||
// Exact /32 cloud metadata boundaries and neighbors.
|
||||
for _, raw := range []string{
|
||||
"100.100.100.199", "100.100.100.200", "100.100.100.201",
|
||||
"168.63.129.15", "168.63.129.16", "168.63.129.17",
|
||||
"169.254.169.254", "172.15.255.255", "172.16.0.0", "172.31.255.255", "172.32.0.0",
|
||||
"::1", "::", "fe80::1", "fc00::1", "fd00:ec2::254", "2001:db8::1", "64:ff9b::7f00:1",
|
||||
} {
|
||||
check(netip.MustParseAddr(raw))
|
||||
}
|
||||
}
|
||||
|
||||
// Property 2: Never-list dominance invariant (fixes #925 d2f902db, c09be6c4).
|
||||
// Even with widest-possible scope CIDRs (0.0.0.0/0, ::/0), every IP in Never
|
||||
// (including NAT64 forms of loopback/private/IMDS) MUST be denied by both
|
||||
// ResolveAndCheck and CheckURL.
|
||||
func TestPropertyNeverListDominatesWideScope(t *testing.T) {
|
||||
pol, err := NewEgressPolicy("1", []string{"example.com"}, []string{"0.0.0.0/0", "::/0"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pol.Never = mustParsePrefixes([]string{
|
||||
"127.0.0.0/8", "10.0.0.0/8", "169.254.0.0/16",
|
||||
"64:ff9b::7f00:0/104", "64:ff9b::a00:0/104", "64:ff9b::a9fe:0/112",
|
||||
"64:ff9b:1::/48",
|
||||
})
|
||||
forbidden := []string{
|
||||
"127.0.0.1", "::ffff:127.0.0.1", "10.0.0.1", "169.254.169.254",
|
||||
"64:ff9b::7f00:1", "64:ff9b::a00:1", "64:ff9b::a9fe:a9fe", "64:ff9b:1::1",
|
||||
}
|
||||
ctx := context.Background()
|
||||
for _, rawIP := range forbidden {
|
||||
if _, err := pol.ResolveAndCheck(ctx, rawIP); err == nil {
|
||||
t.Fatalf("Never dominance violated in ResolveAndCheck(%s): got allow", rawIP)
|
||||
}
|
||||
u := "http://" + rawIP + "/"
|
||||
if strings.Contains(rawIP, ":") {
|
||||
u = "http://[" + rawIP + "]/"
|
||||
}
|
||||
if err := pol.CheckURL(ctx, u); err == nil {
|
||||
t.Fatalf("Never dominance violated in CheckURL(%s): got allow", u)
|
||||
}
|
||||
// Domain resolving to a Never IP must also fail CheckURL and ResolveAndCheck.
|
||||
pol.Resolver = func(_ context.Context, _ string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr(rawIP)}, nil
|
||||
}
|
||||
if _, err := pol.ResolveAndCheck(ctx, "app.example.com"); err == nil {
|
||||
t.Fatalf("Never dominance violated for domain -> %s in ResolveAndCheck", rawIP)
|
||||
}
|
||||
if err := pol.CheckURL(ctx, "https://app.example.com/"); err == nil {
|
||||
t.Fatalf("Never dominance violated for domain -> %s in CheckURL", rawIP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Property 3: EgressPolicy.domainAllowed hash-index vs linear reference equivalence
|
||||
// and no suffix-confusion invariant.
|
||||
func TestPropertyDomainAllowedEquivalenceAndBoundary(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(985, 985))
|
||||
labels := []string{"a", "api", "dev", "prod", "example", "corp", "test", "io", "com", "evil-example"}
|
||||
randDomain := func(n int) string {
|
||||
parts := make([]string, n)
|
||||
for i := range parts {
|
||||
parts[i] = labels[rng.IntN(len(labels))]
|
||||
}
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
scope := make([]string, 50)
|
||||
for i := range scope {
|
||||
scope[i] = randDomain(2 + rng.IntN(2))
|
||||
}
|
||||
pol, err := NewEgressPolicy("1", scope, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
linearRef := func(host string) bool {
|
||||
h := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), "."))
|
||||
if h == "" {
|
||||
return false
|
||||
}
|
||||
for _, s := range pol.Domains {
|
||||
if h == s || strings.HasSuffix(h, "."+s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
for range 2000 {
|
||||
cand := randDomain(1 + rng.IntN(4))
|
||||
if rng.IntN(3) == 0 {
|
||||
cand = strings.ToUpper(cand) + "."
|
||||
}
|
||||
if got, want := pol.domainAllowed(cand), linearRef(cand); got != want {
|
||||
t.Fatalf("domainAllowed(%q) = %v, want %v", cand, got, want)
|
||||
}
|
||||
}
|
||||
// Explicit suffix-confusion check: "evil-example.com" must NOT match "example.com".
|
||||
p2, _ := NewEgressPolicy("1", []string{"example.com"}, nil, nil)
|
||||
if p2.domainAllowed("evil-example.com") || p2.domainAllowed("notexample.com") {
|
||||
t.Fatal("suffix confusion allowed non-subdomain")
|
||||
}
|
||||
}
|
||||
|
||||
// Property 4: canonScopeDomain fast ASCII path == scopeDomainRE + canonical scope
|
||||
// entries never hold comma/space/NUL/zone + ValidateExecRequest workdir confinement
|
||||
// + ValidateEnv forbidden/reserved invariants (fixes 3eedbdc3, 3666be70).
|
||||
func TestPropertyValidateInvariants(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(3666, 3666))
|
||||
ascii := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-* /,@%:"
|
||||
for range 5000 {
|
||||
n := rng.IntN(30)
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = ascii[rng.IntN(len(ascii))]
|
||||
}
|
||||
s := string(b)
|
||||
_, got := canonScopeDomain(s)
|
||||
want := len(s) <= 253 && scopeDomainRE.MatchString(s)
|
||||
if got != want {
|
||||
t.Fatalf("canonScopeDomain(%q) = %v, want regex=%v", s, got, want)
|
||||
}
|
||||
if got && (strings.ContainsAny(s, ", \t\r\n\x00%")) {
|
||||
t.Fatalf("accepted unsafe scope domain %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// Forbidden / reserved env names must always be rejected regardless of case.
|
||||
badEnvNames := []string{
|
||||
"ARTEX_TOKEN", "artex_pg_dsn", "PGPASSWORD", "pguser", "AWS_SECRET_ACCESS_KEY",
|
||||
"GCP_PROJECT", "AZURE_TENANT_ID", "MY_API_KEY", "AUTH_TOKEN", "DB_PASSWORD",
|
||||
"CLIENT_SECRET", "LD_PRELOAD", "ld_library_path", "PATH", "http_proxy",
|
||||
"HTTPS_PROXY", "BASH_ENV", "PYTHONPATH", "NODE_OPTIONS", "GIT_SSH_COMMAND",
|
||||
}
|
||||
for _, k := range badEnvNames {
|
||||
if err := ValidateEnv(map[string]string{k: "x"}); err == nil {
|
||||
t.Fatalf("ValidateEnv accepted forbidden/reserved var %q", k)
|
||||
}
|
||||
}
|
||||
|
||||
// Workdir confinement: no traversal escapes /workspace.
|
||||
escapes := []string{
|
||||
"/workspace/../etc", "/workspace/../../root", "/workspace2", "/tmp",
|
||||
"/workspace/a/../../etc/passwd", "workspace/a", "../workspace",
|
||||
}
|
||||
for _, wd := range escapes {
|
||||
req := ExecRequest{Argv: []string{"true"}, Workdir: wd}
|
||||
if err := ValidateExecRequest(&req); err == nil {
|
||||
t.Fatalf("ValidateExecRequest accepted escaping workdir %q -> %q", wd, req.Workdir)
|
||||
}
|
||||
}
|
||||
|
||||
// IPv6 zone refusal in canonScopeCIDR.
|
||||
for _, zoned := range []string{"fe80::1%eth0", "fe80::1%eth0,evil.com", "2001:db8::1%lo/64"} {
|
||||
if c, ok := canonScopeCIDR(zoned); ok {
|
||||
t.Fatalf("canonScopeCIDR(%q) accepted zoned IPv6 -> %q", zoned, c)
|
||||
}
|
||||
}
|
||||
_ = fmt.Sprintf
|
||||
}
|
||||
+22
-101
@@ -9,58 +9,12 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
taskIDRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$`)
|
||||
envNameRE = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,127}$`)
|
||||
// A scope domain: labels of letters, digits, '-' or '_', optionally "*." first.
|
||||
// Used as fallback for non-ASCII Unicode domains; ASCII domains use a zero-alloc fast path.
|
||||
scopeDomainRE = regexp.MustCompile(`^(\*\.)?[\p{L}\p{N}_-]+(\.[\p{L}\p{N}_-]+)*\.?$`)
|
||||
)
|
||||
|
||||
func isValidTaskID(id string) bool {
|
||||
if len(id) == 0 || len(id) > 64 {
|
||||
return false
|
||||
}
|
||||
c0 := id[0]
|
||||
if !(c0 >= 'a' && c0 <= 'z' || c0 >= 'A' && c0 <= 'Z' || c0 >= '0' && c0 <= '9') {
|
||||
return false
|
||||
}
|
||||
for i := 1; i < len(id); i++ {
|
||||
c := id[i]
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '.' || c == '-') {
|
||||
return false
|
||||
}
|
||||
if c == '.' && id[i-1] == '.' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func isValidEnvName(k string) bool {
|
||||
if len(k) == 0 || len(k) > 128 {
|
||||
return false
|
||||
}
|
||||
c0 := k[0]
|
||||
if !(c0 >= 'A' && c0 <= 'Z' || c0 >= 'a' && c0 <= 'z' || c0 == '_') {
|
||||
return false
|
||||
}
|
||||
for i := 1; i < len(k); i++ {
|
||||
c := k[i]
|
||||
if !(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func toUpperFast(s string) string {
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'a' && c <= 'z' || c >= 0x80 {
|
||||
return strings.ToUpper(s)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// MaxScopeEntries caps scope_domains and scope_cidrs (each) in one request, and
|
||||
// MaxScopeBytes their comma-joined length: the egress proxy gets each list as one
|
||||
// environment string, which Linux limits to 128 KiB.
|
||||
@@ -72,7 +26,7 @@ const (
|
||||
// ValidateTaskID verifies a task ID is safe for Docker names, labels, and workspace paths.
|
||||
func ValidateTaskID(id string) error {
|
||||
id = strings.TrimSpace(id)
|
||||
if !isValidTaskID(id) {
|
||||
if id == "" || !taskIDRE.MatchString(id) || strings.Contains(id, "..") {
|
||||
return fmt.Errorf("%w: invalid task id %q", ErrBadRequest, id)
|
||||
}
|
||||
return nil
|
||||
@@ -81,16 +35,21 @@ func ValidateTaskID(id string) error {
|
||||
// IsForbiddenEnvName reports whether name matches any forbidden secret/cloud/DB pattern
|
||||
// pinned in CONTRACT.md §3: ARTEX_*, *_KEY, *_TOKEN, *_PASSWORD, *_SECRET, PG*, AWS_*, GCP_*, AZURE_*.
|
||||
func IsForbiddenEnvName(name string) bool {
|
||||
u := toUpperFast(strings.TrimSpace(name))
|
||||
u := strings.ToUpper(strings.TrimSpace(name))
|
||||
if u == "" {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(u, "ARTEX_") || strings.HasPrefix(u, "PG") ||
|
||||
strings.HasPrefix(u, "AWS_") || strings.HasPrefix(u, "GCP_") || strings.HasPrefix(u, "AZURE_") {
|
||||
return true
|
||||
for _, prefix := range []string{"ARTEX_", "PG", "AWS_", "GCP_", "AZURE_"} {
|
||||
if strings.HasPrefix(u, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return strings.HasSuffix(u, "_KEY") || strings.HasSuffix(u, "_TOKEN") ||
|
||||
strings.HasSuffix(u, "_PASSWORD") || strings.HasSuffix(u, "_SECRET")
|
||||
for _, suffix := range []string{"_KEY", "_TOKEN", "_PASSWORD", "_SECRET"} {
|
||||
if strings.HasSuffix(u, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isReservedEnvName reports whether name is set by the worker itself (proxy
|
||||
@@ -98,7 +57,7 @@ func IsForbiddenEnvName(name string) bool {
|
||||
// not ask for (LD_*, BASH_ENV, ENV, GCONV_PATH, PYTHONPATH). A request may not
|
||||
// set these in either backend.
|
||||
func isReservedEnvName(name string) bool {
|
||||
u := toUpperFast(name)
|
||||
u := strings.ToUpper(name)
|
||||
switch u {
|
||||
case "PATH", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
|
||||
"BASH_ENV", "ENV", "SHELLOPTS", "BASHOPTS", "PS4", "IFS", "PROMPT_COMMAND",
|
||||
@@ -114,7 +73,7 @@ func isReservedEnvName(name string) bool {
|
||||
// Per CONTRACT.md §3 this is always a 400 validation error, never a silent drop.
|
||||
func ValidateEnv(env map[string]string) error {
|
||||
for k, v := range env {
|
||||
if !isValidEnvName(k) {
|
||||
if !envNameRE.MatchString(k) {
|
||||
return fmt.Errorf("%w: invalid env variable name %q", ErrBadRequest, k)
|
||||
}
|
||||
if IsForbiddenEnvName(k) || isReservedEnvName(k) {
|
||||
@@ -123,7 +82,7 @@ func ValidateEnv(env map[string]string) error {
|
||||
if len(v) > MaxEnvValueBytes {
|
||||
return fmt.Errorf("%w: env variable %q exceeds %d bytes", ErrBadRequest, k, MaxEnvValueBytes)
|
||||
}
|
||||
if strings.IndexByte(v, 0) >= 0 {
|
||||
if strings.ContainsRune(v, 0) {
|
||||
return fmt.Errorf("%w: env variable %q contains NUL byte", ErrBadRequest, k)
|
||||
}
|
||||
}
|
||||
@@ -136,11 +95,11 @@ func FilterPanelEnv(kvs []string) map[string]string {
|
||||
out := make(map[string]string)
|
||||
for _, kv := range kvs {
|
||||
k, v, ok := strings.Cut(kv, "=")
|
||||
if !ok || !isValidEnvName(k) || IsForbiddenEnvName(k) || isReservedEnvName(k) || len(v) > MaxEnvValueBytes || strings.IndexByte(v, 0) >= 0 {
|
||||
if !ok || !envNameRE.MatchString(k) || IsForbiddenEnvName(k) || isReservedEnvName(k) || len(v) > MaxEnvValueBytes || strings.ContainsRune(v, 0) {
|
||||
continue
|
||||
}
|
||||
// Never override worker home variables from panel process env.
|
||||
switch toUpperFast(k) {
|
||||
switch strings.ToUpper(k) {
|
||||
case "HOME", "XDG_CACHE_HOME":
|
||||
continue
|
||||
}
|
||||
@@ -198,7 +157,7 @@ func ValidateExecRequest(req *ExecRequest) error {
|
||||
// must not fail every command: a narrower scope fails closed at the
|
||||
// deny-by-default proxy.
|
||||
func filterScope(entries []string, canon func(string) (string, bool)) (kept, dropped []string) {
|
||||
kept = make([]string, 0, len(entries))
|
||||
kept = entries[:0:0]
|
||||
for _, e := range entries {
|
||||
if c, ok := canon(e); ok {
|
||||
kept = append(kept, c)
|
||||
@@ -218,52 +177,14 @@ func joinedLen(entries []string) int {
|
||||
}
|
||||
|
||||
func canonScopeDomain(d string) (string, bool) {
|
||||
if len(d) == 0 || len(d) > 253 {
|
||||
return d, false
|
||||
}
|
||||
s := d
|
||||
if strings.HasPrefix(s, "*.") {
|
||||
s = s[2:]
|
||||
}
|
||||
if len(s) == 0 {
|
||||
return d, false
|
||||
}
|
||||
if s[len(s)-1] == '.' {
|
||||
s = s[:len(s)-1]
|
||||
}
|
||||
if len(s) == 0 {
|
||||
return d, false
|
||||
}
|
||||
labelLen := 0
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 0x80 {
|
||||
return d, scopeDomainRE.MatchString(d)
|
||||
}
|
||||
if c == '.' {
|
||||
if labelLen == 0 {
|
||||
return d, false
|
||||
}
|
||||
labelLen = 0
|
||||
continue
|
||||
}
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '-') {
|
||||
return d, false
|
||||
}
|
||||
labelLen++
|
||||
}
|
||||
return d, labelLen > 0
|
||||
return d, len(d) <= 253 && scopeDomainRE.MatchString(d)
|
||||
}
|
||||
|
||||
// canonScopeCIDR returns a prefix or address in canonical form. An address with
|
||||
// a zone is refused (the zone may hold any text, commas included), and an
|
||||
// IPv4-mapped IPv6 entry becomes the IPv4 range it maps.
|
||||
func canonScopeCIDR(c string) (string, bool) {
|
||||
if strings.IndexByte(c, '/') >= 0 {
|
||||
p, err := netip.ParsePrefix(c)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
if p, err := netip.ParsePrefix(c); err == nil {
|
||||
if p.Addr().Is4In6() && p.Bits() >= 96 {
|
||||
p = netip.PrefixFrom(p.Addr().Unmap(), p.Bits()-96)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTestGlobalProxyUsesSavedProxyAndHidesCredentials(t *testing.T) {
|
||||
// A forward proxy that answers every request with an egress IP.
|
||||
var gotAuth string
|
||||
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotAuth = r.Header.Get("Proxy-Authorization")
|
||||
_, _ = w.Write([]byte("203.0.113.7\n"))
|
||||
}))
|
||||
defer proxy.Close()
|
||||
old := globalProxyTestURL
|
||||
globalProxyTestURL = "http://egress.test/"
|
||||
defer func() { globalProxyTestURL = old }()
|
||||
|
||||
saved := strings.Replace(proxy.URL, "http://", "http://user:s3cret@", 1)
|
||||
s := &Server{m: &Manager{globalProxy: saved}}
|
||||
call := func(body string) map[string]any {
|
||||
rec := httptest.NewRecorder()
|
||||
s.testGlobalProxy(rec, httptest.NewRequest("POST", "/api/settings/global-proxy/test", strings.NewReader(body)))
|
||||
if strings.Contains(rec.Body.String(), "s3cret") {
|
||||
t.Fatalf("response leaks credentials: %s", rec.Body.String())
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
out := call(`{"global_proxy":"` + maskedSecret(saved) + `"}`)
|
||||
if out["ok"] != true || out["ip"] != "203.0.113.7" {
|
||||
t.Fatalf("masked placeholder should test the saved proxy: %v", out)
|
||||
}
|
||||
if gotAuth == "" {
|
||||
t.Fatal("saved proxy credentials were not sent to the proxy")
|
||||
}
|
||||
|
||||
if out := call(`{"global_proxy":"ftp://user:s3cret@host:21"}`); out["ok"] != false {
|
||||
t.Fatalf("invalid scheme should fail: %v", out)
|
||||
}
|
||||
if out := call(`{"global_proxy":"socks5://user:s3cret@127.0.0.1:1"}`); out["ok"] != false {
|
||||
t.Fatalf("unreachable proxy should fail: %v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestGlobalProxyMapsProxyAuthRequired(t *testing.T) {
|
||||
// A proxy that rejects every request with 407 and a proxy-specific body.
|
||||
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusProxyAuthRequired)
|
||||
_, _ = w.Write([]byte("Proxy Authentication Required by squid/6.1\n"))
|
||||
}))
|
||||
defer proxy.Close()
|
||||
old := globalProxyTestURL
|
||||
globalProxyTestURL = "http://egress.test/"
|
||||
defer func() { globalProxyTestURL = old }()
|
||||
|
||||
saved := strings.Replace(proxy.URL, "http://", "http://user:s3cret@", 1)
|
||||
s := &Server{m: &Manager{globalProxy: saved}}
|
||||
rec := httptest.NewRecorder()
|
||||
s.testGlobalProxy(rec, httptest.NewRequest("POST", "/api/settings/global-proxy/test", strings.NewReader(`{"global_proxy":"`+maskedSecret(saved)+`"}`)))
|
||||
|
||||
respBody := rec.Body.String()
|
||||
if strings.Contains(respBody, "s3cret") || strings.Contains(respBody, "squid") {
|
||||
t.Fatalf("response leaks the proxy address or its raw response: %s", respBody)
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out["ok"] != false || out["error"] != "proxy authentication failed" {
|
||||
t.Fatalf("407 should map to the fixed message: %v", out)
|
||||
}
|
||||
}
|
||||
@@ -991,6 +991,7 @@ func (s *Server) apiRoutes() *apiMux {
|
||||
s.handle(mux, "PUT /api/chat-bridges/{kind}", perm.Authenticated, s.chatBridgeSave)
|
||||
s.handle(mux, "POST /api/chat-bridges/{kind}/test", perm.Authenticated, s.chatBridgeTest)
|
||||
s.handle(mux, "POST /api/settings/web-search/test", perm.Authenticated, s.testWebSearch)
|
||||
s.handle(mux, "POST /api/settings/global-proxy/test", perm.Authenticated, s.testGlobalProxy)
|
||||
s.handle(mux, "GET /api/report", perm.Authenticated, s.getReport)
|
||||
s.handle(mux, "GET /api/chat/mentions", perm.Authenticated, s.searchChatMentions)
|
||||
s.handle(mux, "POST /api/chat", perm.Authenticated, s.chat)
|
||||
@@ -4499,6 +4500,77 @@ func (s *Server) testWebSearch(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "count": len(results), "backend": backend})
|
||||
}
|
||||
|
||||
// globalProxyTestURL is fetched through the proxy by testGlobalProxy: a cheap
|
||||
// HTTPS GET whose plain-text body is the caller's (the proxy's egress) IP.
|
||||
var globalProxyTestURL = "https://api.ipify.org"
|
||||
|
||||
// testGlobalProxy checks that a request through the global proxy works, without
|
||||
// saving anything. It uses the proxy from the form, or the saved one when the
|
||||
// form echoes the masked placeholder, and reports latency and the egress IP.
|
||||
// The proxy address itself is never echoed back: it may carry credentials.
|
||||
func (s *Server) testGlobalProxy(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Proxy string `json:"global_proxy"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
proxy := strings.TrimSpace(req.Proxy)
|
||||
if isMaskedSecret(proxy) {
|
||||
proxy = s.m.GlobalProxy()
|
||||
}
|
||||
if proxy == "" {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": "no proxy configured"})
|
||||
return
|
||||
}
|
||||
pu, err := traffic.ValidateProxyURL(proxy)
|
||||
if err != nil {
|
||||
// The validation error quotes the raw address, credentials included.
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": "invalid proxy address: use http://, https:// or socks5://host:port"})
|
||||
return
|
||||
}
|
||||
tr := &http.Transport{Proxy: http.ProxyURL(pu), DisableKeepAlives: true}
|
||||
defer tr.CloseIdleConnections()
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
hreq, err := http.NewRequestWithContext(ctx, http.MethodGet, globalProxyTestURL, nil)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
resp, err := (&http.Client{Transport: tr}).Do(hreq)
|
||||
if err != nil {
|
||||
// Never echo err.Error(): it can carry the proxy address or a proxy
|
||||
// response line (for example a 407 on an HTTPS CONNECT comes back here).
|
||||
msg := "could not connect through the proxy"
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
msg = "proxy did not respond within 15s"
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": msg})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64))
|
||||
latency := time.Since(start).Milliseconds()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// A plain-HTTP proxy surfaces 407 here. Map it to a fixed message so the
|
||||
// raw proxy response line never reaches the UI.
|
||||
if resp.StatusCode == http.StatusProxyAuthRequired {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": "proxy authentication failed", "latency_ms": latency})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": "unexpected response: " + resp.Status, "latency_ms": latency})
|
||||
return
|
||||
}
|
||||
ip := ""
|
||||
if addr, err := netip.ParseAddr(strings.TrimSpace(string(body))); err == nil {
|
||||
ip = addr.String()
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "latency_ms": latency, "ip": ip})
|
||||
}
|
||||
|
||||
// mainSessions lists the task's main-agent conversation segments (newest-first) and
|
||||
// the current one. The frontend renders these as switchable sessions under Main Agent.
|
||||
func (s *Server) mainSessions(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -21,19 +21,21 @@ test("preferences restore filters and view and mark hydration", () => {
|
||||
assert.equal(empty.preferencesHydrated, true);
|
||||
});
|
||||
|
||||
test("filter fingerprint change resets pagination, expansion and snapshots but keeps the edit buffer", () => {
|
||||
const browsed = (edit) => [
|
||||
{ type: "assetScopeSelected", scope: "host:a" },
|
||||
{ type: "groupPagination", action: { type: "pagination/pageChanged", page: 3 } },
|
||||
{ type: "pagination/pageChanged", page: 4 },
|
||||
{ type: "list/loaded", items: [{ id: 1 }], total: 1 },
|
||||
{ type: "list/loadFinished" },
|
||||
{ type: "groupToggled", key: "7", open: true },
|
||||
{ type: "groupLoadStarted", key: "7", page: 1, pageSize: 10 },
|
||||
{ type: "rowExpanded", key: "finding:1", edit },
|
||||
];
|
||||
|
||||
test("a filter change resets pagination, expansion and snapshots in the same update, but keeps the edit buffer", () => {
|
||||
const edit = { name: "x", vulnclass: "xss", severity: "high" };
|
||||
const s = reduce([
|
||||
{ type: "groupPagination", action: { type: "pagination/pageChanged", page: 3 } },
|
||||
{ type: "pagination/pageChanged", page: 4 },
|
||||
{ type: "list/loaded", items: [{ id: 1 }], total: 1 },
|
||||
{ type: "list/loadFinished" },
|
||||
{ type: "groupToggled", key: "7", open: true },
|
||||
{ type: "groupLoadStarted", key: "7", page: 1, pageSize: 10 },
|
||||
{ type: "assetScopeSelected", scope: "host:a" },
|
||||
{ type: "rowExpanded", key: "finding:1", edit },
|
||||
{ type: "filterFingerprintChanged" },
|
||||
]);
|
||||
const s = reduce([...browsed(edit), { type: "filterChanged", patch: { severity: "high" } }]);
|
||||
assert.equal(s.filters.severity, "high");
|
||||
assert.equal(s.groupPagination.page, 1);
|
||||
assert.equal(s.grouped.expanded.size, 0);
|
||||
assert.deepEqual(s.grouped.findings, {});
|
||||
@@ -126,3 +128,29 @@ test("editChanged accepts values and functional updates", () => {
|
||||
assert.equal(collapsed.expandedRow.edit, null);
|
||||
assert.equal(findingsPageReducer(collapsed, { type: "editChanged", edit: (e) => e }), collapsed);
|
||||
});
|
||||
|
||||
test("typing in the search box does not reset; the debounced query does", () => {
|
||||
const s = reduce([...browsed({}), { type: "filterChanged", patch: { search: " sqli " } }]);
|
||||
assert.equal(s.pagination.page, 4);
|
||||
const debounced = reduce([{ type: "searchDebounced" }], s);
|
||||
assert.equal(debounced.filters.query, "sqli");
|
||||
assert.equal(debounced.pagination.page, 1);
|
||||
});
|
||||
|
||||
test("a company switch resets the views; the same company keeps the state", () => {
|
||||
const s = reduce([...browsed({})]);
|
||||
assert.equal(reduce([{ type: "companyChanged", company: undefined }], s), s);
|
||||
const switched = reduce([{ type: "companyChanged", company: "2" }], s);
|
||||
assert.equal(switched.company, "2");
|
||||
assert.equal(switched.pagination.page, 1);
|
||||
assert.equal(switched.asset.scope, null);
|
||||
});
|
||||
|
||||
test("picking another asset node returns to page 1", () => {
|
||||
const s = reduce([
|
||||
{ type: "pagination/pageChanged", page: 4 },
|
||||
{ type: "assetScopeSelected", scope: "host:b" },
|
||||
]);
|
||||
assert.equal(s.asset.scope, "host:b");
|
||||
assert.equal(s.pagination.page, 1);
|
||||
});
|
||||
|
||||
@@ -159,6 +159,8 @@ export type FindingsPageState = {
|
||||
/** False until saved list preferences have been read from localStorage. */
|
||||
preferencesHydrated: boolean;
|
||||
filters: FindingsFilters;
|
||||
/** The active company the views were last reset for; undefined = all companies. */
|
||||
company: string | undefined;
|
||||
flat: ListState<Finding>;
|
||||
/** The flat (and asset) view's pager; one-based pages. */
|
||||
pagination: Pagination;
|
||||
@@ -191,7 +193,7 @@ export type FindingsPageAction =
|
||||
| { type: "preferencesRestored"; view?: FindingView; filters: Partial<FindingListPreferences> }
|
||||
| { type: "filterChanged"; patch: Partial<FindingsFilters> }
|
||||
| { type: "searchDebounced" }
|
||||
| { type: "filterFingerprintChanged" }
|
||||
| { type: "companyChanged"; company: string | undefined }
|
||||
| { type: "assetScopeSelected"; scope: string | null }
|
||||
| { type: "assetTreeLoadStarted" }
|
||||
| {
|
||||
@@ -232,6 +234,7 @@ export function createInitialFindingsPageState(): FindingsPageState {
|
||||
return {
|
||||
view: "flat",
|
||||
preferencesHydrated: false,
|
||||
company: undefined,
|
||||
filters: {
|
||||
severity: "all",
|
||||
status: "all",
|
||||
@@ -265,10 +268,41 @@ export function createInitialFindingsPageState(): FindingsPageState {
|
||||
};
|
||||
}
|
||||
|
||||
/** Filters that change the result set; the raw search box is not one of them until it is debounced into `query`. */
|
||||
const RESULT_FILTERS: (keyof FindingsFilters)[] = [
|
||||
"severity",
|
||||
"status",
|
||||
"reportState",
|
||||
"verificationStatus",
|
||||
"vulnclass",
|
||||
"task",
|
||||
"sort",
|
||||
"query",
|
||||
];
|
||||
|
||||
/**
|
||||
* A different result set: every view goes back to its first page and drops its expansion and snapshots, in the
|
||||
* same update as the change, so no request for the old page goes out with the new filters. The selected asset
|
||||
* node may not exist in the new tree, so it falls back to "All assets".
|
||||
*/
|
||||
function resetViews(state: FindingsPageState): FindingsPageState {
|
||||
return {
|
||||
...state,
|
||||
flat: EMPTY_FLAT_STATE,
|
||||
pagination: toFirstPage(state.pagination),
|
||||
asset: { tree: EMPTY_ASSET_TREE, scope: null },
|
||||
grouped: { ...state.grouped, expanded: new Set(), findings: {} },
|
||||
groupPagination: toFirstPage(state.groupPagination),
|
||||
expandedRow: { ...state.expandedRow, key: null },
|
||||
};
|
||||
}
|
||||
|
||||
function withFilters(state: FindingsPageState, patch: Partial<FindingsFilters>): FindingsPageState {
|
||||
const keys = Object.keys(patch) as (keyof FindingsFilters)[];
|
||||
if (keys.every((key) => patch[key] === undefined || patch[key] === state.filters[key])) return state;
|
||||
return { ...state, filters: { ...state.filters, ...patch } };
|
||||
const filters = { ...state.filters, ...patch };
|
||||
const next = { ...state, filters };
|
||||
return RESULT_FILTERS.some((key) => filters[key] !== state.filters[key]) ? resetViews(next) : next;
|
||||
}
|
||||
|
||||
function withGroupFindings(state: FindingsPageState, findings: Record<string, GroupFindingsState>): FindingsPageState {
|
||||
@@ -300,21 +334,13 @@ export function findingsPageReducer(state: FindingsPageState, action: FindingsPa
|
||||
return withFilters(state, action.patch);
|
||||
case "searchDebounced":
|
||||
return withFilters(state, { query: state.filters.search.trim() });
|
||||
// Reset every view's pagination and expansion when a shared finding filter changes. The
|
||||
// previously selected asset node may no longer be in the tree, so fall back to "All assets".
|
||||
case "filterFingerprintChanged":
|
||||
return {
|
||||
...state,
|
||||
flat: EMPTY_FLAT_STATE,
|
||||
pagination: toFirstPage(state.pagination),
|
||||
asset: { tree: EMPTY_ASSET_TREE, scope: null },
|
||||
grouped: { ...state.grouped, expanded: new Set(), findings: {} },
|
||||
groupPagination: toFirstPage(state.groupPagination),
|
||||
expandedRow: { ...state.expandedRow, key: null },
|
||||
};
|
||||
case "companyChanged":
|
||||
if (action.company === state.company) return state;
|
||||
return resetViews({ ...state, company: action.company });
|
||||
case "assetScopeSelected":
|
||||
// A different asset node is a different result set: back to page one in the same update.
|
||||
if (action.scope === state.asset.scope) return state;
|
||||
return { ...state, asset: { ...state.asset, scope: action.scope } };
|
||||
return { ...state, asset: { ...state.asset, scope: action.scope }, pagination: toFirstPage(state.pagination) };
|
||||
case "assetTreeLoadStarted":
|
||||
return { ...state, asset: { ...state.asset, tree: { ...state.asset.tree, loading: true } } };
|
||||
case "assetTreeLoaded":
|
||||
|
||||
@@ -99,7 +99,9 @@ export default function FindingsPage() {
|
||||
const [state, dispatch] = React.useReducer(findingsPageReducer, urlView as FindingView, (initialView) => ({
|
||||
...createInitialFindingsPageState(),
|
||||
view: initialView,
|
||||
company,
|
||||
}));
|
||||
if (state.company !== company) dispatch({ type: "companyChanged", company });
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: "viewChanged", view: urlView as FindingView });
|
||||
}, [urlView]);
|
||||
@@ -292,14 +294,6 @@ export default function FindingsPage() {
|
||||
groupFindingsRef.current = groupFindings;
|
||||
visibleGroupKeysRef.current = new Set(groups.map(findingGroupKey));
|
||||
|
||||
// A company switch drops the picked asset node: the node may belong to the
|
||||
// company we just left, and the tree is about to be reloaded under the new one.
|
||||
React.useEffect(() => {
|
||||
// company is a trigger here, not a value the effect reads.
|
||||
void company;
|
||||
dispatch({ type: "assetScopeSelected", scope: null });
|
||||
}, [company]);
|
||||
|
||||
// The asset view's right-hand list = the flat list + a filter for the selected subtree, so both views share one list state.
|
||||
const activeAssetScope = view === "asset" ? assetScope : null;
|
||||
|
||||
@@ -509,19 +503,6 @@ export default function FindingsPage() {
|
||||
[loadAssetTree, loadFlat, loadGroup, refreshGroups, view],
|
||||
);
|
||||
|
||||
// Reset every view's pagination and expansion when a shared finding filter changes.
|
||||
React.useEffect(() => {
|
||||
void filterFingerprint;
|
||||
// Filters change the tree too; the previously selected node may no longer be in it, so the reducer falls back to "All assets".
|
||||
dispatch({ type: "filterFingerprintChanged" });
|
||||
}, [filterFingerprint]);
|
||||
|
||||
// Switching asset nodes means a different result set; go back to page one.
|
||||
React.useEffect(() => {
|
||||
void assetScope;
|
||||
dispatch({ type: "pagination/pageChanged", page: 1 });
|
||||
}, [assetScope]);
|
||||
|
||||
// The asset tree is queried once on view entry / filter change (plus actively re-pulled by
|
||||
// refreshAfterMutation after this page mutates a finding); no polling.
|
||||
React.useEffect(() => {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
|
||||
export type CategoryManagementView = number | "uncategorized" | "new";
|
||||
|
||||
export type CategoryEditor = {
|
||||
view: CategoryManagementView;
|
||||
draftName: string;
|
||||
};
|
||||
|
||||
export type CategoryTaskDrag = {
|
||||
/** Task whose category update request is in flight (a per-task ID, so not a `request` slice). */
|
||||
movingTaskID: string | null;
|
||||
activeTaskID: string | null;
|
||||
};
|
||||
|
||||
export type CategoryManagementRequest = "save" | "delete";
|
||||
|
||||
export type CategoryManagementSheetState = {
|
||||
open: boolean;
|
||||
editor: CategoryEditor;
|
||||
deleteDialogOpen: boolean;
|
||||
requests: Requests<CategoryManagementRequest>;
|
||||
drag: CategoryTaskDrag;
|
||||
};
|
||||
|
||||
export type CategoryManagementSheetAction =
|
||||
| RequestAction<CategoryManagementRequest>
|
||||
| { type: "openChanged"; open: boolean }
|
||||
| { type: "viewSelected"; view: CategoryManagementView; draftName: string }
|
||||
| { type: "draftNameChanged"; draftName: string }
|
||||
| { type: "deleteDialogOpenChanged"; open: boolean }
|
||||
| { type: "dragChanged"; patch: Partial<CategoryTaskDrag> };
|
||||
|
||||
export const initialCategoryManagementSheetState: CategoryManagementSheetState = {
|
||||
open: false,
|
||||
editor: { view: "new", draftName: "" },
|
||||
deleteDialogOpen: false,
|
||||
requests: createRequests(["save", "delete"]),
|
||||
drag: { movingTaskID: null, activeTaskID: null },
|
||||
};
|
||||
|
||||
export function categoryManagementSheetReducer(
|
||||
state: CategoryManagementSheetState,
|
||||
action: CategoryManagementSheetAction,
|
||||
): CategoryManagementSheetState {
|
||||
if (isRequestAction<CategoryManagementRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "openChanged":
|
||||
if (action.open === state.open) return state;
|
||||
return { ...state, open: action.open };
|
||||
case "viewSelected":
|
||||
return { ...state, editor: { view: action.view, draftName: action.draftName } };
|
||||
case "draftNameChanged":
|
||||
return { ...state, editor: { ...state.editor, draftName: action.draftName } };
|
||||
case "deleteDialogOpenChanged":
|
||||
if (action.open === state.deleteDialogOpen) return state;
|
||||
return { ...state, deleteDialogOpen: action.open };
|
||||
case "dragChanged":
|
||||
return setSlice(state, "drag", mergePatch(state.drag, action.patch));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
|
||||
export type ConcurrencySettingsForm = {
|
||||
enabled: boolean;
|
||||
/** Raw input value; parsed and clamped on save. */
|
||||
limit: string;
|
||||
};
|
||||
|
||||
export type ConcurrencySettingsRequest = "load" | "save";
|
||||
|
||||
export type ConcurrencySettingsDialogState = {
|
||||
open: boolean;
|
||||
form: ConcurrencySettingsForm;
|
||||
requests: Requests<ConcurrencySettingsRequest>;
|
||||
};
|
||||
|
||||
export type ConcurrencySettingsDialogAction =
|
||||
| RequestAction<ConcurrencySettingsRequest>
|
||||
| { type: "openChanged"; open: boolean }
|
||||
| { type: "formChanged"; patch: Partial<ConcurrencySettingsForm> }
|
||||
| { type: "settingsLoaded"; form: ConcurrencySettingsForm };
|
||||
|
||||
export const initialConcurrencySettingsDialogState: ConcurrencySettingsDialogState = {
|
||||
open: false,
|
||||
form: { enabled: false, limit: "5" },
|
||||
requests: createRequests(["load", "save"]),
|
||||
};
|
||||
|
||||
export function concurrencySettingsDialogReducer(
|
||||
state: ConcurrencySettingsDialogState,
|
||||
action: ConcurrencySettingsDialogAction,
|
||||
): ConcurrencySettingsDialogState {
|
||||
if (isRequestAction<ConcurrencySettingsRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "openChanged":
|
||||
if (action.open === state.open) return state;
|
||||
return { ...state, open: action.open };
|
||||
case "formChanged":
|
||||
return { ...state, form: { ...state.form, ...action.patch } };
|
||||
case "settingsLoaded":
|
||||
return { ...state, form: action.form };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { AssetInterceptRuleInput, Company, LLMProfile, TaskCredentialInput } from "@/lib/types";
|
||||
|
||||
// UPLOAD_MARKER labels the auto-appended block of uploaded-file paths inside the task
|
||||
// description, so re-uploads append under the same block instead of adding a new header.
|
||||
const UPLOAD_MARKER = "[Uploaded Files (Absolute Paths)]";
|
||||
|
||||
// appendUploads folds newly-uploaded files' ABSOLUTE paths into the description as a
|
||||
// Read/Bash-friendly manifest — the worker opens them by path. Keeps one marked block:
|
||||
// first upload adds the header, later uploads append bullets under it. Each file comes
|
||||
// in as an already-rendered "- <path> (<size>)" line, so this file needs no formatter.
|
||||
export function appendUploads(desc: string, lines: string[]): string {
|
||||
const bullets = lines.join("\n");
|
||||
if (desc.includes(UPLOAD_MARKER)) {
|
||||
return `${desc.replace(/\s*$/, "")}\n${bullets}\n`;
|
||||
}
|
||||
const head = desc.trim() ? `${desc.replace(/\s*$/, "")}\n\n` : "";
|
||||
return `${head}${UPLOAD_MARKER} worker can open them by path with Read/Bash:\n${bullets}\n`;
|
||||
}
|
||||
|
||||
export type CreateTaskForm = {
|
||||
name: string;
|
||||
categoryID: number | undefined;
|
||||
description: string;
|
||||
goal: string;
|
||||
selectedTemplateID: number | null;
|
||||
sourceTaskIDs: string[];
|
||||
companyIDs: number[];
|
||||
llmProfileIDs: string[];
|
||||
llmRotate: boolean;
|
||||
/** Task-level timeout (minutes); empty/0 = no limit. */
|
||||
timeoutMin: string;
|
||||
/** Planner heartbeat (minutes); default 10, minimum 10 (matching the backend). */
|
||||
heartbeatMin: string;
|
||||
/** Dispatch a seed intent at creation so the worker starts without waiting for the first planner round; off by default, standard plan-then-execute. */
|
||||
seedFirstIntent: boolean;
|
||||
/** Asset coverage feature; on by default. Off = no coverage computed/displayed, no scope accumulation, scope-related tools hidden (company links unaffected). */
|
||||
coverageEnabled: boolean;
|
||||
/** Task-level asset intercept rules (this task only, never entering the global table). */
|
||||
interceptRules: AssetInterceptRuleInput[];
|
||||
/**
|
||||
* Target gate: the switch that decides whether the block rules above are matched against outbound network
|
||||
* targets at all. "auto" sends nothing, so the backend keeps its default (on for scoped tasks, off otherwise).
|
||||
*/
|
||||
targetGateMode: "auto" | "on" | "off";
|
||||
/** Test accounts declared at creation (#3); an empty password = the agent registers that account and records it. */
|
||||
credentials: TaskCredentialInput[];
|
||||
};
|
||||
|
||||
export type CreateTaskOptions = {
|
||||
profiles: LLMProfile[];
|
||||
companies: Company[];
|
||||
};
|
||||
|
||||
/** File upload (method 1): files are staged under drafts/<draftId>/uploads/ before the task is created. */
|
||||
export type CreateTaskUpload = {
|
||||
count: number;
|
||||
};
|
||||
|
||||
export type CreateTaskRequest = "upload" | "create";
|
||||
|
||||
export type CreateTaskSheetState = {
|
||||
open: boolean;
|
||||
form: CreateTaskForm;
|
||||
options: CreateTaskOptions;
|
||||
upload: CreateTaskUpload;
|
||||
requests: Requests<CreateTaskRequest>;
|
||||
};
|
||||
|
||||
export type CreateTaskTemplate = Pick<CreateTaskForm, "description" | "goal" | "categoryID" | "interceptRules">;
|
||||
|
||||
export type CreateTaskSheetAction =
|
||||
| RequestAction<CreateTaskRequest>
|
||||
| { type: "openChanged"; open: boolean }
|
||||
| { type: "formFieldChanged"; patch: Partial<CreateTaskForm> }
|
||||
| { type: "templateApplied"; template: CreateTaskTemplate }
|
||||
| { type: "credentialAdded" }
|
||||
| { type: "credentialChanged"; index: number; patch: Partial<TaskCredentialInput> }
|
||||
| { type: "credentialRemoved"; index: number }
|
||||
| { type: "profilesLoaded"; profiles: LLMProfile[] }
|
||||
| { type: "companiesLoaded"; companies: Company[] }
|
||||
| { type: "filesUploaded"; manifestLines: string[] }
|
||||
| { type: "taskCreated" };
|
||||
|
||||
export const initialCreateTaskForm: CreateTaskForm = {
|
||||
name: "",
|
||||
categoryID: undefined,
|
||||
description: "",
|
||||
goal: "",
|
||||
selectedTemplateID: null,
|
||||
sourceTaskIDs: [],
|
||||
companyIDs: [],
|
||||
llmProfileIDs: [],
|
||||
llmRotate: false,
|
||||
timeoutMin: "",
|
||||
heartbeatMin: "10",
|
||||
seedFirstIntent: false,
|
||||
coverageEnabled: true,
|
||||
interceptRules: [],
|
||||
targetGateMode: "auto",
|
||||
credentials: [],
|
||||
};
|
||||
|
||||
export const initialCreateTaskSheetState: CreateTaskSheetState = {
|
||||
open: false,
|
||||
form: initialCreateTaskForm,
|
||||
options: { profiles: [], companies: [] },
|
||||
upload: { count: 0 },
|
||||
requests: createRequests(["upload", "create"]),
|
||||
};
|
||||
|
||||
function withForm(state: CreateTaskSheetState, patch: Partial<CreateTaskForm>): CreateTaskSheetState {
|
||||
return { ...state, form: { ...state.form, ...patch } };
|
||||
}
|
||||
|
||||
export function createTaskSheetReducer(
|
||||
state: CreateTaskSheetState,
|
||||
action: CreateTaskSheetAction,
|
||||
): CreateTaskSheetState {
|
||||
if (isRequestAction<CreateTaskRequest>(action))
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
switch (action.type) {
|
||||
case "openChanged":
|
||||
if (action.open === state.open) return state;
|
||||
return { ...state, open: action.open };
|
||||
case "formFieldChanged":
|
||||
return withForm(state, action.patch);
|
||||
case "templateApplied":
|
||||
// A template replaces the description, so the uploaded-files note no longer applies.
|
||||
return { ...withForm(state, action.template), upload: { ...state.upload, count: 0 } };
|
||||
case "credentialAdded":
|
||||
return withForm(state, {
|
||||
credentials: [...state.form.credentials, { domain: "", username: "", password: "", note: "" }],
|
||||
});
|
||||
case "credentialChanged":
|
||||
return withForm(state, {
|
||||
credentials: state.form.credentials.map((credential, i) =>
|
||||
i === action.index ? { ...credential, ...action.patch } : credential,
|
||||
),
|
||||
});
|
||||
case "credentialRemoved":
|
||||
return withForm(state, { credentials: state.form.credentials.filter((_, i) => i !== action.index) });
|
||||
case "profilesLoaded":
|
||||
return { ...state, options: { ...state.options, profiles: action.profiles } };
|
||||
case "companiesLoaded":
|
||||
return { ...state, options: { ...state.options, companies: action.companies } };
|
||||
case "filesUploaded":
|
||||
return {
|
||||
...withForm(state, { description: appendUploads(state.form.description, action.manifestLines) }),
|
||||
upload: { ...state.upload, count: state.upload.count + action.manifestLines.length },
|
||||
};
|
||||
case "taskCreated":
|
||||
return { ...state, open: false, form: initialCreateTaskForm, upload: { ...state.upload, count: 0 } };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { initialTaskArchivesPanelState as initial, taskArchivesPanelReducer } from "./task-archives-panel.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initial) => actions.reduce(taskArchivesPanelReducer, state);
|
||||
const archive = (id) => ({ id, task_id: String(id), state: "ready" });
|
||||
|
||||
test("the spinner shows until the first load settles", () => {
|
||||
assert.equal(initial.list.loaded, false);
|
||||
assert.deepEqual(initial.pagination, { page: 1, size: 20, firstPage: 1 });
|
||||
const s = reduce([{ type: "list/loaded", items: [archive(1)], total: 7 }, { type: "list/loadFinished" }]);
|
||||
assert.equal(s.list.loaded, true);
|
||||
assert.equal(s.list.total, 7);
|
||||
});
|
||||
|
||||
test("loading a page prunes selections that are no longer on it", () => {
|
||||
const s = reduce([
|
||||
{ type: "list/loaded", items: [archive(1), archive(2)], total: 2 },
|
||||
{ type: "archiveSelectionToggled", id: 1, checked: true },
|
||||
{ type: "archiveSelectionToggled", id: 2, checked: true },
|
||||
{ type: "list/loaded", items: [archive(2), archive(3)], total: 2 },
|
||||
]);
|
||||
assert.deepEqual([...s.selected], [2]);
|
||||
const same = taskArchivesPanelReducer(s, { type: "list/loaded", items: [archive(2)], total: 1 });
|
||||
assert.equal(same.selected, s.selected);
|
||||
});
|
||||
|
||||
test("an unchanged poll keeps the same state; a changed archive is updated", () => {
|
||||
const s = reduce([{ type: "list/loaded", items: [archive(1), archive(2)], total: 2 }, { type: "list/loadFinished" }]);
|
||||
assert.equal(reduce([{ type: "list/loaded", items: [archive(1), archive(2)], total: 2 }], s), s);
|
||||
const changed = reduce(
|
||||
[{ type: "list/loaded", items: [archive(1), { ...archive(2), state: "restoring" }], total: 2 }],
|
||||
s,
|
||||
);
|
||||
assert.equal(changed.list.items[1].state, "restoring");
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
toFirstPage,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import { isSelectionAction, type SelectionAction, selectionReducer } from "@/lib/reducers/selection";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { TaskArchive } from "@/lib/types";
|
||||
|
||||
export type TaskArchivesFilters = {
|
||||
query: string;
|
||||
/** "all" or a TaskArchiveState. */
|
||||
state: string;
|
||||
};
|
||||
|
||||
export type TaskArchivesPanelState = {
|
||||
filters: TaskArchivesFilters;
|
||||
/** One-based, matching the archives API. */
|
||||
pagination: Pagination;
|
||||
/**
|
||||
* The spinner shows only until the first load settles (`!loaded`); polling never
|
||||
* dispatches `list/loadStarted`, so it does not show the spinner again.
|
||||
*/
|
||||
list: ListState<TaskArchive>;
|
||||
/** Selected archive IDs, always a subset of the current page. */
|
||||
selected: Set<number>;
|
||||
};
|
||||
|
||||
export type TaskArchivesPanelAction =
|
||||
| PaginationAction
|
||||
| ListAction<TaskArchive>
|
||||
| SelectionAction<number>
|
||||
| { type: "queryChanged"; query: string }
|
||||
| { type: "stateFilterChanged"; state: string }
|
||||
| { type: "archiveSelectionToggled"; id: number; checked: boolean };
|
||||
|
||||
export const initialTaskArchivesPanelState: TaskArchivesPanelState = {
|
||||
filters: { query: "", state: "all" },
|
||||
pagination: createPagination(20, 1),
|
||||
list: createList(),
|
||||
selected: new Set(),
|
||||
};
|
||||
|
||||
function withSelection(state: TaskArchivesPanelState, action: SelectionAction<number>): TaskArchivesPanelState {
|
||||
return setSlice(state, "selected", selectionReducer(state.selected, action));
|
||||
}
|
||||
|
||||
export function taskArchivesPanelReducer(
|
||||
state: TaskArchivesPanelState,
|
||||
action: TaskArchivesPanelAction,
|
||||
): TaskArchivesPanelState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isSelectionAction<number>(action)) return withSelection(state, action);
|
||||
if (isListAction<TaskArchive>(action)) {
|
||||
if (
|
||||
action.type === "list/loaded" &&
|
||||
(action.total ?? action.items.length) === state.list.total &&
|
||||
JSON.stringify(action.items) === JSON.stringify(state.list.items)
|
||||
)
|
||||
return state;
|
||||
const next = setSlice(state, "list", listReducer(state.list, action));
|
||||
if (action.type !== "list/loaded") return next;
|
||||
// Keep only selections that are still on the freshly loaded page.
|
||||
return withSelection(next, { type: "selection/pruned", keep: action.items.map((archive) => archive.id) });
|
||||
}
|
||||
switch (action.type) {
|
||||
case "queryChanged":
|
||||
// Every filter change sends the user back to the first page.
|
||||
if (action.query === state.filters.query) return state;
|
||||
return {
|
||||
...state,
|
||||
filters: { ...state.filters, query: action.query },
|
||||
pagination: toFirstPage(state.pagination),
|
||||
};
|
||||
case "stateFilterChanged":
|
||||
if (action.state === state.filters.state) return state;
|
||||
return {
|
||||
...state,
|
||||
filters: { ...state.filters, state: action.state },
|
||||
pagination: toFirstPage(state.pagination),
|
||||
};
|
||||
case "archiveSelectionToggled":
|
||||
return withSelection(state, { type: "selection/changed", ids: [action.id], selected: action.checked });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { initTasksPageState, tasksPageReducer } from "./tasks-page.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const initial = initTasksPageState(1000);
|
||||
const reduce = (actions, state = initial) => actions.reduce(tasksPageReducer, state);
|
||||
const task = (id, extra = {}) => ({ id, status: "done", description: "", goal: "", created_at: "", ...extra });
|
||||
|
||||
test("hydration applies only the saved filters it is given and marks hydrated", () => {
|
||||
const s = reduce([{ type: "filtersHydrated", status: "running" }]);
|
||||
assert.deepEqual(s.filters, { query: "", status: "running", category: "all", hydrated: true });
|
||||
const none = reduce([{ type: "filtersHydrated" }]);
|
||||
assert.deepEqual(none.filters, { query: "", status: "all", category: "all", hydrated: true });
|
||||
});
|
||||
|
||||
test("loading tasks prunes selections whose task disappeared", () => {
|
||||
const s = reduce([
|
||||
{ type: "tasksLoaded", tasks: [task("1"), task("2"), task("3")] },
|
||||
{ type: "taskSelectionToggled", id: "1", checked: true },
|
||||
{ type: "taskSelectionToggled", id: "3", checked: true },
|
||||
{ type: "tasksLoaded", tasks: [task("1"), task("2")] },
|
||||
]);
|
||||
assert.deepEqual([...s.selectedIds], ["1"]);
|
||||
});
|
||||
|
||||
test("category move updates only the moved task, from the latest list", () => {
|
||||
const loaded = reduce([
|
||||
{ type: "tasksLoaded", tasks: [task("1", { category_id: 5, category_name: "Old" }), task("2")] },
|
||||
]);
|
||||
const s = tasksPageReducer(loaded, { type: "taskCategoryMoved", taskID: "1", category: { id: 7, name: "New" } });
|
||||
assert.equal(s.tasks[1], loaded.tasks[1]);
|
||||
assert.equal(s.tasks[0].category_id, 7);
|
||||
assert.equal(s.tasks[0].category_name, "New");
|
||||
const un = tasksPageReducer(s, { type: "taskCategoryMoved", taskID: "1", category: null });
|
||||
assert.equal(un.tasks[0].category_id, undefined);
|
||||
assert.equal(un.tasks[0].category_name, undefined);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { isSelectionAction, type SelectionAction, selectionReducer } from "@/lib/reducers/selection";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { Task, TaskCategory, TaskStatus } from "@/lib/types";
|
||||
|
||||
export type TaskStatusFilter = TaskStatus | "all";
|
||||
|
||||
export type TasksFilters = {
|
||||
query: string;
|
||||
status: TaskStatusFilter;
|
||||
/** "all", the uncategorized sentinel, or a category ID as a string. */
|
||||
category: string;
|
||||
/** Set once the saved status/category filters were read from localStorage. */
|
||||
hydrated: boolean;
|
||||
};
|
||||
|
||||
export type TasksCategories = {
|
||||
items: TaskCategory[];
|
||||
loaded: boolean;
|
||||
};
|
||||
|
||||
export type TasksBulkRequest = "pause" | "resume" | "moveCategory";
|
||||
|
||||
export type TasksPageState = {
|
||||
tasks: Task[];
|
||||
categories: TasksCategories;
|
||||
filters: TasksFilters;
|
||||
/** One-based, client-side pager over the filtered list. */
|
||||
pagination: Pagination;
|
||||
/** Unix seconds, ticked every second while a task is running. */
|
||||
nowSec: number;
|
||||
/** Multi-select survives paging/filter changes and only shrinks when a task disappears. */
|
||||
selectedIds: Set<string>;
|
||||
bulk: Requests<TasksBulkRequest>;
|
||||
};
|
||||
|
||||
export type TasksPageAction =
|
||||
| PaginationAction
|
||||
| SelectionAction<string>
|
||||
| RequestAction<TasksBulkRequest>
|
||||
| { type: "tasksLoaded"; tasks: Task[] }
|
||||
| { type: "taskCategoryMoved"; taskID: string; category: TaskCategory | null }
|
||||
| { type: "categoriesLoaded"; categories: TaskCategory[] }
|
||||
| { type: "filtersChanged"; patch: Partial<TasksFilters> }
|
||||
| { type: "filtersHydrated"; status?: TaskStatusFilter; category?: string }
|
||||
| { type: "clockTicked"; nowSec: number }
|
||||
| { type: "taskSelectionToggled"; id: string; checked: boolean }
|
||||
| { type: "pageSelectionToggled"; ids: string[]; checked: boolean }
|
||||
| { type: "tasksDeselected"; ids: string[] };
|
||||
|
||||
export function initTasksPageState(nowSec: number): TasksPageState {
|
||||
return {
|
||||
tasks: [],
|
||||
categories: { items: [], loaded: false },
|
||||
filters: { query: "", status: "all", category: "all", hydrated: false },
|
||||
pagination: createPagination(20, 1),
|
||||
nowSec,
|
||||
selectedIds: new Set(),
|
||||
bulk: createRequests(["pause", "resume", "moveCategory"]),
|
||||
};
|
||||
}
|
||||
|
||||
export function bulkControlling(bulk: Requests<TasksBulkRequest>): "pause" | "resume" | null {
|
||||
if (bulk.pause.pending) return "pause";
|
||||
if (bulk.resume.pending) return "resume";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function moveTaskCategory(tasks: Task[], taskID: string, category: TaskCategory | null): Task[] {
|
||||
return tasks.map((task) =>
|
||||
task.id === taskID ? { ...task, category_id: category?.id, category_name: category?.name } : task,
|
||||
);
|
||||
}
|
||||
|
||||
function withSelection(state: TasksPageState, action: SelectionAction<string>): TasksPageState {
|
||||
return setSlice(state, "selectedIds", selectionReducer(state.selectedIds, action));
|
||||
}
|
||||
|
||||
function withTasks(state: TasksPageState, tasks: Task[]): TasksPageState {
|
||||
return withSelection({ ...state, tasks }, { type: "selection/pruned", keep: tasks.map((task) => task.id) });
|
||||
}
|
||||
|
||||
export function tasksPageReducer(state: TasksPageState, action: TasksPageAction): TasksPageState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isSelectionAction<string>(action)) return withSelection(state, action);
|
||||
if (isRequestAction<TasksBulkRequest>(action)) return setSlice(state, "bulk", requestReducer(state.bulk, action));
|
||||
switch (action.type) {
|
||||
case "tasksLoaded":
|
||||
return withTasks(state, action.tasks);
|
||||
case "taskCategoryMoved":
|
||||
return withTasks(state, moveTaskCategory(state.tasks, action.taskID, action.category));
|
||||
case "categoriesLoaded":
|
||||
return { ...state, categories: { items: action.categories, loaded: true } };
|
||||
case "filtersChanged":
|
||||
return setSlice(state, "filters", mergePatch(state.filters, action.patch));
|
||||
case "filtersHydrated":
|
||||
return {
|
||||
...state,
|
||||
filters: {
|
||||
...state.filters,
|
||||
status: action.status ?? state.filters.status,
|
||||
category: action.category ?? state.filters.category,
|
||||
hydrated: true,
|
||||
},
|
||||
};
|
||||
case "clockTicked":
|
||||
if (action.nowSec === state.nowSec) return state;
|
||||
return { ...state, nowSec: action.nowSec };
|
||||
case "taskSelectionToggled":
|
||||
return withSelection(state, { type: "selection/changed", ids: [action.id], selected: action.checked });
|
||||
case "pageSelectionToggled":
|
||||
return withSelection(state, { type: "selection/changed", ids: action.ids, selected: action.checked });
|
||||
case "tasksDeselected":
|
||||
return withSelection(state, { type: "selection/changed", ids: action.ids, selected: false });
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -48,6 +48,7 @@ export type SettingsRequest =
|
||||
| "keenableKey"
|
||||
| "proxy"
|
||||
| "globalProxy"
|
||||
| "globalProxyTest"
|
||||
| "workers"
|
||||
| "test";
|
||||
|
||||
@@ -97,6 +98,7 @@ export const initialSystemSettingsPageState: SystemSettingsPageState = {
|
||||
"keenableKey",
|
||||
"proxy",
|
||||
"globalProxy",
|
||||
"globalProxyTest",
|
||||
"workers",
|
||||
"test",
|
||||
]),
|
||||
|
||||
@@ -59,6 +59,7 @@ export default function SystemSettingsPage() {
|
||||
const savingGlobalProxy = requests.globalProxy.pending;
|
||||
const savingWorkers = requests.workers.pending;
|
||||
const testing = requests.test.pending;
|
||||
const testingGlobalProxy = requests.globalProxyTest.pending;
|
||||
// Pure frontend preference: bypasses /api/settings, reads and writes localStorage directly.
|
||||
const sendMode = useChatSendMode();
|
||||
|
||||
@@ -251,6 +252,23 @@ export default function SystemSettingsPage() {
|
||||
.finally(() => dispatch({ type: "request/finished", key: "globalProxy" }));
|
||||
};
|
||||
|
||||
// Test the proxy currently in the field (the masked placeholder means the saved one). Saves nothing.
|
||||
const testGlobalProxy = () => {
|
||||
dispatch({ type: "request/started", key: "globalProxyTest" });
|
||||
api
|
||||
.testGlobalProxy(globalProxyInput.trim())
|
||||
.then((r) => {
|
||||
if (!r.ok) toast.error(t("Proxy test failed: {error}", { error: r.error || t("unknown error") }));
|
||||
else if (r.ip)
|
||||
toast.success(
|
||||
t("Proxy test succeeded · {latency} ms · egress IP {ip}", { latency: r.latency_ms ?? 0, ip: r.ip }),
|
||||
);
|
||||
else toast.success(t("Proxy test succeeded · {latency} ms", { latency: r.latency_ms ?? 0 }));
|
||||
})
|
||||
.catch((e) => toast.error(t("Proxy test failed: {error}", { error: (e as Error).message })))
|
||||
.finally(() => dispatch({ type: "request/finished", key: "globalProxyTest" }));
|
||||
};
|
||||
|
||||
// Run a real "test" search ("test") against the CURRENT form values (backend +
|
||||
// proxy + entered key), falling back to saved values server-side. Toasts result.
|
||||
const runTest = () => {
|
||||
@@ -408,6 +426,14 @@ export default function SystemSettingsPage() {
|
||||
disabled={!loaded || savingGlobalProxy}
|
||||
onChange={(e) => dispatch({ type: "globalProxyChanged", value: e.target.value })}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={testGlobalProxy}
|
||||
disabled={!loaded || testingGlobalProxy || !globalProxyInput.trim()}
|
||||
>
|
||||
{testingGlobalProxy ? t("Testing…") : t("Test connection")}
|
||||
</Button>
|
||||
<Button type="button" onClick={saveGlobalProxy} disabled={!loaded || savingGlobalProxy}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { agentEditorReducer, initialAgentEditorState } from "./agent-editor.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialAgentEditorState) => actions.reduce(agentEditorReducer, state);
|
||||
|
||||
const v1 = { version: 1, template_text: "old", note: "", ts: "" };
|
||||
const v2 = { version: 2, template_text: "new", note: "", ts: "" };
|
||||
|
||||
test("agentLoaded fills form, defaults and visibility, falling back on missing fields", () => {
|
||||
const s = reduce([
|
||||
{ type: "formFieldChanged", patch: { prompt: "unsaved" } },
|
||||
{
|
||||
type: "agentLoaded",
|
||||
detail: {
|
||||
prompt: "hello",
|
||||
agent: { max_turns: 7, llm_profile_id: 3, web_search: true },
|
||||
versions: null,
|
||||
variables: null,
|
||||
visibility: { mcp: [1], skill: null },
|
||||
wrapup_max_turns: 2,
|
||||
task_timeout_wrapup_supported: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.equal(s.form.prompt, "hello");
|
||||
assert.equal(s.form.maxTurns, "7");
|
||||
assert.equal(s.form.runSecs, "600");
|
||||
assert.equal(s.form.llmProfileId, "3");
|
||||
assert.equal(s.form.webSearch, true);
|
||||
assert.equal(s.form.interactiveShell, false);
|
||||
assert.equal(s.form.wrapupTurns, "2");
|
||||
assert.equal(s.form.ttTurns, "0");
|
||||
assert.deepEqual(s.agent.versions, []);
|
||||
assert.deepEqual(s.visibility, { mcp: [1], skill: [] });
|
||||
assert.deepEqual(s.defaults, { wrapup: "", wrapupTurns: 5, ttSupported: true, ttWrapup: "", ttTurns: 5 });
|
||||
assert.equal(s.agent.loaded, false);
|
||||
assert.equal(reduce([{ type: "agentLoadFinished" }], s).agent.loaded, true);
|
||||
});
|
||||
|
||||
test("viewed version can be compared or loaded into the editor", () => {
|
||||
const viewing = reduce([
|
||||
{ type: "versionDialogsChanged", patch: { viewing: v1 } },
|
||||
{ type: "versionDialogsChanged", patch: { diffing: v2 } },
|
||||
]);
|
||||
const compared = reduce([{ type: "viewedVersionCompared" }], viewing);
|
||||
assert.deepEqual(compared.versionDialogs, { viewing: null, diffing: v1 });
|
||||
const loaded = reduce([{ type: "viewedVersionLoaded" }], viewing);
|
||||
assert.equal(loaded.form.prompt, "old");
|
||||
assert.deepEqual(loaded.versionDialogs, { viewing: null, diffing: v2 });
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { AgentDetail, MCPServer, PromptVar, PromptVersion, Settings, SkillItem, Tool } from "@/lib/types";
|
||||
|
||||
export type LlmProfile = NonNullable<AgentDetail["llm_profiles"]>[number];
|
||||
|
||||
export type AgentEditorAgent = {
|
||||
/** null = not loaded yet, or the agent was not found. */
|
||||
detail: AgentDetail | null;
|
||||
loaded: boolean;
|
||||
/** Newest first; [0] is the current version. */
|
||||
versions: PromptVersion[];
|
||||
variables: PromptVar[];
|
||||
llmProfiles: LlmProfile[];
|
||||
};
|
||||
|
||||
export type AgentEditorDefaults = {
|
||||
wrapup: string;
|
||||
wrapupTurns: number;
|
||||
ttSupported: boolean;
|
||||
ttWrapup: string;
|
||||
ttTurns: number;
|
||||
};
|
||||
|
||||
/** Editable fields; numbers stay strings while typed and are parsed on save. */
|
||||
export type AgentEditorForm = {
|
||||
prompt: string;
|
||||
maxTurns: string;
|
||||
runSecs: string;
|
||||
/** "" = follow (unbound); otherwise a profile id string. */
|
||||
llmProfileId: string;
|
||||
webSearch: boolean;
|
||||
interactiveShell: boolean;
|
||||
wrapup: string;
|
||||
wrapupTurns: string;
|
||||
ttWrapup: string;
|
||||
ttTurns: string;
|
||||
};
|
||||
|
||||
export type AgentEditorVisibility = {
|
||||
mcp: number[];
|
||||
skill: string[];
|
||||
};
|
||||
|
||||
export type AgentEditorCatalog = {
|
||||
mcp: MCPServer[];
|
||||
skills: SkillItem[];
|
||||
tools: Tool[];
|
||||
settings: Settings | null;
|
||||
};
|
||||
|
||||
/** Version shown in the view dialog and version compared with the current one (null = closed). */
|
||||
export type AgentEditorVersionDialogs = {
|
||||
viewing: PromptVersion | null;
|
||||
diffing: PromptVersion | null;
|
||||
};
|
||||
|
||||
export type AgentEditorState = {
|
||||
agent: AgentEditorAgent;
|
||||
defaults: AgentEditorDefaults;
|
||||
form: AgentEditorForm;
|
||||
visibility: AgentEditorVisibility;
|
||||
catalog: AgentEditorCatalog;
|
||||
versionDialogs: AgentEditorVersionDialogs;
|
||||
preview: string;
|
||||
};
|
||||
|
||||
export type AgentEditorAction =
|
||||
| { type: "catalogLoaded"; patch: Partial<AgentEditorCatalog> }
|
||||
| { type: "agentLoaded"; detail: AgentDetail }
|
||||
| { type: "agentLoadFailed" }
|
||||
| { type: "agentLoadFinished" }
|
||||
| { type: "formFieldChanged"; patch: Partial<AgentEditorForm> }
|
||||
| { type: "variableInserted"; name: string }
|
||||
| { type: "previewRendered"; text: string }
|
||||
| { type: "visibilityChanged"; patch: Partial<AgentEditorVisibility> }
|
||||
| { type: "toolAgentsChanged"; key: string; agents: string[] }
|
||||
| { type: "versionDialogsChanged"; patch: Partial<AgentEditorVersionDialogs> }
|
||||
| { type: "viewedVersionCompared" }
|
||||
| { type: "viewedVersionLoaded" };
|
||||
|
||||
export const initialAgentEditorState: AgentEditorState = {
|
||||
agent: { detail: null, loaded: false, versions: [], variables: [], llmProfiles: [] },
|
||||
defaults: { wrapup: "", wrapupTurns: 5, ttSupported: false, ttWrapup: "", ttTurns: 5 },
|
||||
form: {
|
||||
prompt: "",
|
||||
maxTurns: "0",
|
||||
runSecs: "600",
|
||||
llmProfileId: "",
|
||||
webSearch: false,
|
||||
interactiveShell: false,
|
||||
wrapup: "",
|
||||
wrapupTurns: "0",
|
||||
ttWrapup: "",
|
||||
ttTurns: "0",
|
||||
},
|
||||
visibility: { mcp: [], skill: [] },
|
||||
catalog: { mcp: [], skills: [], tools: [], settings: null },
|
||||
versionDialogs: { viewing: null, diffing: null },
|
||||
preview: "",
|
||||
};
|
||||
|
||||
/** Fills the whole editor from a freshly loaded agent; unsaved edits are replaced. */
|
||||
function fromDetail(state: AgentEditorState, d: AgentDetail): AgentEditorState {
|
||||
// biome-ignore-start lint/suspicious/noUnnecessaryConditions: the backend may send null for nil slices/strings despite the type.
|
||||
return {
|
||||
...state,
|
||||
agent: {
|
||||
...state.agent,
|
||||
detail: d,
|
||||
versions: d.versions ?? [],
|
||||
variables: d.variables ?? [],
|
||||
llmProfiles: d.llm_profiles ?? [],
|
||||
},
|
||||
defaults: {
|
||||
wrapup: d.wrapup_default ?? "",
|
||||
wrapupTurns: d.wrapup_max_turns_default ?? 5,
|
||||
ttSupported: !!d.task_timeout_wrapup_supported,
|
||||
ttWrapup: d.task_timeout_wrapup_default ?? "",
|
||||
ttTurns: d.task_timeout_wrapup_max_turns_default ?? 5,
|
||||
},
|
||||
form: {
|
||||
prompt: d.prompt ?? "",
|
||||
maxTurns: String(d.agent?.max_turns ?? 0),
|
||||
runSecs: String(d.agent?.run_seconds ?? 600),
|
||||
llmProfileId: d.agent?.llm_profile_id != null ? String(d.agent.llm_profile_id) : "",
|
||||
webSearch: !!d.agent?.web_search,
|
||||
interactiveShell: !!d.agent?.interactive_shell,
|
||||
wrapup: d.wrapup_prompt ?? "",
|
||||
wrapupTurns: String(d.wrapup_max_turns ?? 0),
|
||||
ttWrapup: d.task_timeout_wrapup_prompt ?? "",
|
||||
ttTurns: String(d.task_timeout_wrapup_max_turns ?? 0),
|
||||
},
|
||||
visibility: { mcp: d.visibility?.mcp ?? [], skill: d.visibility?.skill ?? [] },
|
||||
};
|
||||
// biome-ignore-end lint/suspicious/noUnnecessaryConditions: see above.
|
||||
}
|
||||
|
||||
export function agentEditorReducer(state: AgentEditorState, action: AgentEditorAction): AgentEditorState {
|
||||
switch (action.type) {
|
||||
case "catalogLoaded":
|
||||
return setSlice(state, "catalog", mergePatch(state.catalog, action.patch));
|
||||
case "agentLoaded":
|
||||
return fromDetail(state, action.detail);
|
||||
case "agentLoadFailed":
|
||||
if (state.agent.detail === null) return state;
|
||||
return { ...state, agent: { ...state.agent, detail: null } };
|
||||
case "agentLoadFinished":
|
||||
if (state.agent.loaded) return state;
|
||||
return { ...state, agent: { ...state.agent, loaded: true } };
|
||||
case "formFieldChanged":
|
||||
return setSlice(state, "form", mergePatch(state.form, action.patch));
|
||||
case "variableInserted":
|
||||
return { ...state, form: { ...state.form, prompt: `${state.form.prompt}{{.${action.name}}}` } };
|
||||
case "previewRendered":
|
||||
return action.text === state.preview ? state : { ...state, preview: action.text };
|
||||
case "visibilityChanged":
|
||||
return setSlice(state, "visibility", mergePatch(state.visibility, action.patch));
|
||||
case "toolAgentsChanged": {
|
||||
const tools = state.catalog.tools.map((x) => (x.key === action.key ? { ...x, agents: action.agents } : x));
|
||||
return { ...state, catalog: { ...state.catalog, tools } };
|
||||
}
|
||||
case "versionDialogsChanged":
|
||||
return setSlice(state, "versionDialogs", mergePatch(state.versionDialogs, action.patch));
|
||||
case "viewedVersionCompared": {
|
||||
const { viewing } = state.versionDialogs;
|
||||
if (!viewing) return state;
|
||||
return { ...state, versionDialogs: { viewing: null, diffing: viewing } };
|
||||
}
|
||||
case "viewedVersionLoaded": {
|
||||
const { viewing } = state.versionDialogs;
|
||||
if (!viewing) return state;
|
||||
return {
|
||||
...state,
|
||||
form: { ...state.form, prompt: viewing.template_text },
|
||||
versionDialogs: { ...state.versionDialogs, viewing: null },
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { agentTriggersTabReducer, createAgentTriggersTabState } from "./agent-triggers-tab.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = createAgentTriggersTabState()) => actions.reduce(agentTriggersTabReducer, state);
|
||||
|
||||
const _trigger = {
|
||||
id: 9,
|
||||
enabled: false,
|
||||
interval_sec: 0,
|
||||
on_finding: true,
|
||||
on_goal_met: false,
|
||||
on_task_timeout: false,
|
||||
on_tool_call: true,
|
||||
on_task_create: false,
|
||||
interval_message: "",
|
||||
finding_message: "found",
|
||||
goal_message: "",
|
||||
task_timeout_message: "",
|
||||
tool_call_message: "called",
|
||||
task_create_message: "",
|
||||
tool_names: null,
|
||||
};
|
||||
|
||||
test("behaviorSynced replaces local edits and is a no-op when unchanged", () => {
|
||||
const s = createAgentTriggersTabState();
|
||||
assert.equal(agentTriggersTabReducer(s, { type: "behaviorSynced", policy: {} }), s);
|
||||
const edited = reduce([{ type: "behaviorChanged", patch: { maxParallel: "12" } }], s);
|
||||
assert.equal(reduce([{ type: "behaviorSynced", policy: {} }], edited).behavior.maxParallel, "5");
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { Agent, AgentTrigger, Tool } from "@/lib/types";
|
||||
|
||||
export type TriggerRunMode = "serial" | "parallel";
|
||||
export type TriggerMergeMode = "by_task" | "all" | "none";
|
||||
|
||||
export type TriggerBehavior = {
|
||||
runMode: TriggerRunMode;
|
||||
mergeMode: TriggerMergeMode;
|
||||
/** Typed value; normalized and saved on blur. */
|
||||
maxParallel: string;
|
||||
};
|
||||
|
||||
export type TriggerForm = {
|
||||
onInterval: boolean;
|
||||
intervalSec: string;
|
||||
onFinding: boolean;
|
||||
onGoalMet: boolean;
|
||||
onTaskTimeout: boolean;
|
||||
onToolCall: boolean;
|
||||
onTaskCreate: boolean;
|
||||
intervalMsg: string;
|
||||
findingMsg: string;
|
||||
goalMsg: string;
|
||||
taskTimeoutMsg: string;
|
||||
toolCallMsg: string;
|
||||
taskCreateMsg: string;
|
||||
toolNames: string[];
|
||||
};
|
||||
|
||||
export type TriggerEditor = {
|
||||
/** null = create mode; otherwise the id of the trigger being edited. */
|
||||
editingId: number | null;
|
||||
form: TriggerForm;
|
||||
};
|
||||
|
||||
export type AgentTriggersTabRequest = "save";
|
||||
|
||||
export type TriggerPolicy = Pick<Agent, "trigger_run_mode" | "trigger_merge_mode" | "trigger_max_parallel">;
|
||||
|
||||
export type AgentTriggersTabState = {
|
||||
triggers: AgentTrigger[];
|
||||
tools: Tool[];
|
||||
behavior: TriggerBehavior;
|
||||
editor: TriggerEditor;
|
||||
requests: Requests<AgentTriggersTabRequest>;
|
||||
};
|
||||
|
||||
export type AgentTriggersTabAction =
|
||||
| RequestAction<AgentTriggersTabRequest>
|
||||
| { type: "triggersLoaded"; triggers: AgentTrigger[] }
|
||||
| { type: "toolsLoaded"; tools: Tool[] }
|
||||
/** The agent's saved policy changed (new agent or reload); replaces the local values. */
|
||||
| { type: "behaviorSynced"; policy: TriggerPolicy }
|
||||
| { type: "behaviorChanged"; patch: Partial<TriggerBehavior> }
|
||||
| { type: "formFieldChanged"; patch: Partial<TriggerForm> }
|
||||
| { type: "toolNameToggled"; key: string }
|
||||
| { type: "formReset" }
|
||||
| { type: "editStarted"; trigger: AgentTrigger };
|
||||
|
||||
export const emptyTriggerForm: TriggerForm = {
|
||||
onInterval: false,
|
||||
intervalSec: "60",
|
||||
onFinding: false,
|
||||
onGoalMet: false,
|
||||
onTaskTimeout: false,
|
||||
onToolCall: false,
|
||||
onTaskCreate: false,
|
||||
intervalMsg: "",
|
||||
findingMsg: "",
|
||||
goalMsg: "",
|
||||
taskTimeoutMsg: "",
|
||||
toolCallMsg: "",
|
||||
taskCreateMsg: "",
|
||||
toolNames: [],
|
||||
};
|
||||
|
||||
function behaviorOf(agent?: TriggerPolicy): TriggerBehavior {
|
||||
return {
|
||||
runMode: agent?.trigger_run_mode ?? "serial",
|
||||
mergeMode: agent?.trigger_merge_mode ?? "all",
|
||||
maxParallel: String(agent?.trigger_max_parallel ?? 5),
|
||||
};
|
||||
}
|
||||
|
||||
export function createAgentTriggersTabState(agent?: TriggerPolicy): AgentTriggersTabState {
|
||||
return {
|
||||
triggers: [],
|
||||
tools: [],
|
||||
behavior: behaviorOf(agent),
|
||||
editor: { editingId: null, form: emptyTriggerForm },
|
||||
requests: createRequests(["save"]),
|
||||
};
|
||||
}
|
||||
|
||||
function formOf(trg: AgentTrigger): TriggerForm {
|
||||
return {
|
||||
onInterval: trg.interval_sec > 0,
|
||||
intervalSec: trg.interval_sec > 0 ? String(trg.interval_sec) : "60",
|
||||
onFinding: trg.on_finding,
|
||||
onGoalMet: trg.on_goal_met,
|
||||
onTaskTimeout: trg.on_task_timeout,
|
||||
onToolCall: trg.on_tool_call,
|
||||
onTaskCreate: trg.on_task_create,
|
||||
intervalMsg: trg.interval_message,
|
||||
findingMsg: trg.finding_message,
|
||||
goalMsg: trg.goal_message,
|
||||
taskTimeoutMsg: trg.task_timeout_message,
|
||||
toolCallMsg: trg.tool_call_message,
|
||||
taskCreateMsg: trg.task_create_message,
|
||||
// biome-ignore lint/suspicious/noUnnecessaryConditions: the backend may send null for a nil slice.
|
||||
toolNames: trg.tool_names ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function setForm(state: AgentTriggersTabState, form: TriggerForm): AgentTriggersTabState {
|
||||
return form === state.editor.form ? state : { ...state, editor: { ...state.editor, form } };
|
||||
}
|
||||
|
||||
export function agentTriggersTabReducer(
|
||||
state: AgentTriggersTabState,
|
||||
action: AgentTriggersTabAction,
|
||||
): AgentTriggersTabState {
|
||||
if (isRequestAction<AgentTriggersTabRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "triggersLoaded":
|
||||
return { ...state, triggers: action.triggers };
|
||||
case "toolsLoaded":
|
||||
return { ...state, tools: action.tools };
|
||||
case "behaviorSynced":
|
||||
return setSlice(state, "behavior", mergePatch(state.behavior, behaviorOf(action.policy)));
|
||||
case "behaviorChanged":
|
||||
return setSlice(state, "behavior", mergePatch(state.behavior, action.patch));
|
||||
case "formFieldChanged":
|
||||
return setForm(state, mergePatch(state.editor.form, action.patch));
|
||||
case "toolNameToggled": {
|
||||
const { toolNames } = state.editor.form;
|
||||
const next = toolNames.includes(action.key)
|
||||
? toolNames.filter((k) => k !== action.key)
|
||||
: [...toolNames, action.key];
|
||||
return setForm(state, { ...state.editor.form, toolNames: next });
|
||||
}
|
||||
case "formReset":
|
||||
if (state.editor.editingId === null && state.editor.form === emptyTriggerForm) return state;
|
||||
return { ...state, editor: { editingId: null, form: emptyTriggerForm } };
|
||||
case "editStarted":
|
||||
return { ...state, editor: { editingId: action.trigger.id, form: formOf(action.trigger) } };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { approvalRecordsReducer, initialApprovalRecordsState } from "./approval-records.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialApprovalRecordsState) => actions.reduce(approvalRecordsReducer, state);
|
||||
|
||||
const row = (id, extra = {}) => ({
|
||||
id,
|
||||
agent_name: "a",
|
||||
tool_name: "Bash",
|
||||
tool_input: {},
|
||||
status: "pending",
|
||||
reason: "",
|
||||
created_at: "",
|
||||
conv_title: "",
|
||||
conv_agent_key: "",
|
||||
rule_name: "",
|
||||
...extra,
|
||||
});
|
||||
|
||||
test("loadSettled keeps old rows when the history request failed", () => {
|
||||
const s = reduce([
|
||||
{
|
||||
type: "loadSettled",
|
||||
history: { ok: true, value: { items: [row(1)], total: 1 } },
|
||||
pending: { ok: true, value: [] },
|
||||
manual: false,
|
||||
},
|
||||
{
|
||||
type: "loadSettled",
|
||||
history: { ok: false, error: "down" },
|
||||
pending: { ok: false, error: "queue down" },
|
||||
manual: false,
|
||||
},
|
||||
]);
|
||||
assert.equal(s.list.items.length, 1);
|
||||
assert.deepEqual(s.errors, { history: "down", pending: "queue down" });
|
||||
assert.equal(s.revision, 0);
|
||||
});
|
||||
|
||||
test("filterChanged returns to page 1, drops rows and shows the skeleton again", () => {
|
||||
const s = reduce([
|
||||
{
|
||||
type: "loadSettled",
|
||||
history: { ok: false, error: "down" },
|
||||
pending: { ok: true, value: [] },
|
||||
manual: false,
|
||||
},
|
||||
{ type: "list/loaded", items: [row(1)], total: 30 },
|
||||
{ type: "list/loadFinished" },
|
||||
{ type: "pagination/pageChanged", page: 2 },
|
||||
{ type: "filterChanged", filter: { status: "denied" } },
|
||||
]);
|
||||
assert.deepEqual(s.filter, { status: "denied" });
|
||||
assert.equal(s.pagination.page, 1);
|
||||
assert.equal(s.list.items.length, 0);
|
||||
assert.equal(s.list.total, 0);
|
||||
assert.equal(s.list.loaded, false);
|
||||
assert.equal(s.errors.history, "");
|
||||
});
|
||||
|
||||
test("decided marks the history row and drops it from the queue", () => {
|
||||
const s = reduce([
|
||||
{ type: "list/loaded", items: [row(1), row(2)], total: 2 },
|
||||
{
|
||||
type: "loadSettled",
|
||||
history: { ok: true, value: { items: [row(1), row(2)], total: 2 } },
|
||||
pending: { ok: true, value: [row(1), row(3)] },
|
||||
manual: false,
|
||||
},
|
||||
{ type: "decided", id: 1, decision: "allowed", at: "2026-01-01T00:00:00Z" },
|
||||
]);
|
||||
assert.equal(s.list.items[0].status, "allowed");
|
||||
assert.equal(s.list.items[0].decided_by, "human");
|
||||
assert.equal(s.list.items[0].decided_at, "2026-01-01T00:00:00Z");
|
||||
assert.equal(s.list.items[1].status, "pending");
|
||||
assert.deepEqual(
|
||||
s.pendingRows.map((r) => r.id),
|
||||
[3],
|
||||
);
|
||||
assert.equal(s.revision, 1);
|
||||
});
|
||||
|
||||
test("batchDecided keeps only failed ids selected and lists their errors", () => {
|
||||
const s = reduce([
|
||||
{ type: "selection/toggled", id: 1 },
|
||||
{ type: "selection/toggled", id: 2 },
|
||||
{ type: "batchChanged", patch: { decision: "denied" } },
|
||||
{ type: "batchDecided", failed: [{ id: 2, error: "nope" }] },
|
||||
]);
|
||||
assert.deepEqual([...s.selection], [2]);
|
||||
assert.deepEqual(s.batch.errors, [{ id: 2, error: "nope" }]);
|
||||
assert.equal(s.batch.decision, "denied");
|
||||
assert.equal(s.revision, 1);
|
||||
});
|
||||
|
||||
test("an unchanged poll keeps the same state; a changed row or a manual reload does not", () => {
|
||||
const settled = (items, pending, manual = false) => ({
|
||||
type: "loadSettled",
|
||||
history: { ok: true, value: { items, total: items.length } },
|
||||
pending: { ok: true, value: pending },
|
||||
manual,
|
||||
});
|
||||
const s = reduce([settled([row(1), row(2)], [{ id: 2 }]), { type: "list/loadFinished" }]);
|
||||
assert.equal(reduce([settled([row(1), row(2)], [{ id: 2 }])], s), s);
|
||||
const changed = reduce([settled([row(1), row(2, { status: "allowed" })], [])], s);
|
||||
assert.equal(changed.list.items[1].status, "allowed");
|
||||
assert.deepEqual(changed.pendingRows, []);
|
||||
assert.equal(reduce([settled([row(1), row(2)], [{ id: 2 }], true)], s).revision, s.revision + 1);
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
toFirstPage,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { isSelectionAction, type SelectionAction, selectionReducer } from "@/lib/reducers/selection";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { InterceptApprovalFilter, InterceptApprovalRow, InterceptPending } from "@/lib/types";
|
||||
|
||||
export const DEFAULT_PAGE_SIZE = 20;
|
||||
|
||||
export type ApprovalDecision = "allowed" | "denied";
|
||||
export type BatchFailure = { id: number; error: string };
|
||||
|
||||
export type ApprovalBatch = {
|
||||
/** Decision awaiting confirmation; null = confirmation dialog closed. */
|
||||
decision: ApprovalDecision | null;
|
||||
errors: BatchFailure[];
|
||||
};
|
||||
|
||||
export type ApprovalRecordsState = {
|
||||
filter: InterceptApprovalFilter;
|
||||
/** 1-based, like the intercept history API. */
|
||||
pagination: Pagination;
|
||||
/**
|
||||
* Approval history page. `loaded` is false until the first load for the current filter settles (shows the
|
||||
* skeleton); `loading` is true while a manual refresh is in flight (spins the Refresh icon).
|
||||
*/
|
||||
list: ListState<InterceptApprovalRow>;
|
||||
pendingRows: InterceptPending[];
|
||||
errors: { history: string; pending: string };
|
||||
/** `decide.pending` while a single or batch decision is in flight. */
|
||||
requests: Requests<"decide">;
|
||||
/** Bumped after a manual reload or a decision so expanded rows refetch their detail. */
|
||||
revision: number;
|
||||
selection: Set<number>;
|
||||
batch: ApprovalBatch;
|
||||
};
|
||||
|
||||
export type SettledResult<T> = { ok: true; value: T } | { ok: false; error: string };
|
||||
|
||||
export type ApprovalRecordsAction =
|
||||
| PaginationAction
|
||||
| ListAction<InterceptApprovalRow>
|
||||
| RequestAction<"decide">
|
||||
| SelectionAction<number>
|
||||
| {
|
||||
type: "loadSettled";
|
||||
history: SettledResult<{ items: InterceptApprovalRow[]; total: number }>;
|
||||
pending: SettledResult<InterceptPending[]>;
|
||||
manual: boolean;
|
||||
}
|
||||
| { type: "historyFailed"; error: string }
|
||||
| { type: "filterChanged"; filter: InterceptApprovalFilter }
|
||||
| { type: "decided"; id: number; decision: ApprovalDecision; at: string }
|
||||
| { type: "batchDecided"; failed: BatchFailure[] }
|
||||
| { type: "batchChanged"; patch: Partial<ApprovalBatch> };
|
||||
|
||||
export const initialApprovalRecordsState: ApprovalRecordsState = {
|
||||
filter: {},
|
||||
pagination: createPagination(DEFAULT_PAGE_SIZE, 1),
|
||||
list: createList(),
|
||||
pendingRows: [],
|
||||
errors: { history: "", pending: "" },
|
||||
requests: createRequests(["decide"]),
|
||||
revision: 0,
|
||||
selection: new Set(),
|
||||
batch: { decision: null, errors: [] },
|
||||
};
|
||||
|
||||
function setErrors(state: ApprovalRecordsState, patch: Partial<ApprovalRecordsState["errors"]>): ApprovalRecordsState {
|
||||
return setSlice(state, "errors", mergePatch(state.errors, patch));
|
||||
}
|
||||
|
||||
export function approvalRecordsReducer(
|
||||
state: ApprovalRecordsState,
|
||||
action: ApprovalRecordsAction,
|
||||
): ApprovalRecordsState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isListAction<InterceptApprovalRow>(action)) return setSlice(state, "list", listReducer(state.list, action));
|
||||
if (isRequestAction<"decide">(action)) return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
if (isSelectionAction<number>(action)) return setSlice(state, "selection", selectionReducer(state.selection, action));
|
||||
switch (action.type) {
|
||||
case "loadSettled": {
|
||||
let next = state;
|
||||
if (action.history.ok) {
|
||||
const { items, total } = action.history.value;
|
||||
if (total !== next.list.total || JSON.stringify(items) !== JSON.stringify(next.list.items))
|
||||
next = setSlice(next, "list", listReducer(next.list, { type: "list/loaded", items, total }));
|
||||
next = setErrors(next, { history: "" });
|
||||
} else {
|
||||
next = setErrors(next, { history: action.history.error });
|
||||
}
|
||||
if (action.pending.ok) {
|
||||
if (JSON.stringify(action.pending.value) !== JSON.stringify(next.pendingRows))
|
||||
next = { ...next, pendingRows: action.pending.value };
|
||||
next = setErrors(next, { pending: "" });
|
||||
} else {
|
||||
next = setErrors(next, { pending: action.pending.error });
|
||||
}
|
||||
return action.manual ? { ...next, revision: next.revision + 1 } : next;
|
||||
}
|
||||
case "historyFailed":
|
||||
return setErrors(state, { history: action.error });
|
||||
case "filterChanged":
|
||||
// A new filter starts over: first page, no stale rows, skeleton until its first load settles.
|
||||
return {
|
||||
...state,
|
||||
filter: action.filter,
|
||||
pagination: toFirstPage(state.pagination),
|
||||
list: listReducer(state.list, { type: "list/cleared" }),
|
||||
errors: state.errors.history ? { ...state.errors, history: "" } : state.errors,
|
||||
};
|
||||
case "decided":
|
||||
// Optimistic: mark the history row decided and drop it from the pending queue; a reload reconciles.
|
||||
return {
|
||||
...state,
|
||||
list: {
|
||||
...state.list,
|
||||
items: state.list.items.map((row) =>
|
||||
row.id === action.id
|
||||
? { ...row, status: action.decision, decided_by: "human", decided_at: action.at }
|
||||
: row,
|
||||
),
|
||||
},
|
||||
pendingRows: state.pendingRows.filter((row) => row.id !== action.id),
|
||||
revision: state.revision + 1,
|
||||
};
|
||||
case "batchDecided":
|
||||
// Ids that failed stay selected so the user can retry them.
|
||||
return {
|
||||
...state,
|
||||
batch: { ...state.batch, errors: action.failed },
|
||||
selection: selectionReducer(state.selection, { type: "selection/set", ids: action.failed.map((f) => f.id) }),
|
||||
revision: state.revision + 1,
|
||||
};
|
||||
case "batchChanged":
|
||||
return setSlice(state, "batch", mergePatch(state.batch, action.patch));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { FindingTraffic, FindingTrafficBinding, TrafficEvidenceRole } from "@/lib/types";
|
||||
|
||||
type FindingTrafficRequest = "mutate";
|
||||
|
||||
/** The finding's bound traffic; `data` is null while (re)loading. */
|
||||
export type FindingTrafficEvidence = {
|
||||
data: FindingTraffic | null;
|
||||
error: string;
|
||||
/** Bumped to force a reload (retry, failed change, new binding). */
|
||||
reloadTick: number;
|
||||
};
|
||||
|
||||
/** Role/note dialog for one binding; `binding` null = closed. */
|
||||
export type FindingTrafficEditor = {
|
||||
binding: FindingTrafficBinding | null;
|
||||
role: TrafficEvidenceRole;
|
||||
note: string;
|
||||
};
|
||||
|
||||
export type FindingTrafficPanelState = {
|
||||
evidence: FindingTrafficEvidence;
|
||||
editor: FindingTrafficEditor;
|
||||
adding: boolean;
|
||||
preview: string | null;
|
||||
/** Errors of changes are toasted; only `pending` is used. */
|
||||
requests: Requests<FindingTrafficRequest>;
|
||||
};
|
||||
|
||||
export type FindingTrafficPanelAction =
|
||||
| RequestAction<FindingTrafficRequest>
|
||||
| { type: "loadStarted" }
|
||||
| { type: "loaded"; data: FindingTraffic }
|
||||
| { type: "loadFailed"; error: string }
|
||||
| { type: "reloadRequested" }
|
||||
| { type: "mutated"; data: FindingTraffic }
|
||||
| { type: "addingChanged"; open: boolean }
|
||||
| { type: "previewChanged"; id: string | null }
|
||||
| { type: "editStarted"; binding: FindingTrafficBinding }
|
||||
| { type: "editorChanged"; patch: Partial<FindingTrafficEditor> };
|
||||
|
||||
export const initialFindingTrafficPanelState: FindingTrafficPanelState = {
|
||||
evidence: { data: null, error: "", reloadTick: 0 },
|
||||
editor: { binding: null, role: "supporting", note: "" },
|
||||
adding: false,
|
||||
preview: null,
|
||||
requests: createRequests(["mutate"]),
|
||||
};
|
||||
|
||||
function withEvidence(
|
||||
state: FindingTrafficPanelState,
|
||||
patch: Partial<FindingTrafficEvidence>,
|
||||
): FindingTrafficPanelState {
|
||||
return setSlice(state, "evidence", mergePatch(state.evidence, patch));
|
||||
}
|
||||
|
||||
export function findingTrafficPanelReducer(
|
||||
state: FindingTrafficPanelState,
|
||||
action: FindingTrafficPanelAction,
|
||||
): FindingTrafficPanelState {
|
||||
if (isRequestAction<FindingTrafficRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "loadStarted":
|
||||
return withEvidence(state, { data: null, error: "" });
|
||||
case "loaded":
|
||||
return withEvidence(state, { data: action.data });
|
||||
case "loadFailed":
|
||||
return withEvidence(state, { error: action.error });
|
||||
case "reloadRequested":
|
||||
return withEvidence(state, { reloadTick: state.evidence.reloadTick + 1 });
|
||||
case "mutated":
|
||||
return { ...withEvidence(state, { data: action.data }), editor: { ...state.editor, binding: null } };
|
||||
case "addingChanged":
|
||||
return setSlice(state, "adding", action.open);
|
||||
case "previewChanged":
|
||||
return setSlice(state, "preview", action.id);
|
||||
case "editStarted":
|
||||
return { ...state, editor: { binding: action.binding, role: action.binding.role, note: action.binding.note } };
|
||||
case "editorChanged":
|
||||
return setSlice(state, "editor", mergePatch(state.editor, action.patch));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { initialInterceptCardState, interceptCardReducer } from "./intercept-card.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialInterceptCardState) => actions.reduce(interceptCardReducer, state);
|
||||
|
||||
test("a resolved approval shows its decision; a pending one keeps the current decision", () => {
|
||||
let s = reduce([
|
||||
{ type: "approvalLoadFailed", error: "x" },
|
||||
{ type: "approvalLoaded", pending: { id: 1, status: "timeout" } },
|
||||
]);
|
||||
assert.deepEqual([s.approval.decided, s.approval.statusError], ["timeout", ""]);
|
||||
s = reduce([
|
||||
{ type: "decided", decision: "allowed" },
|
||||
{ type: "approvalLoaded", pending: { id: 1, status: "pending" } },
|
||||
]);
|
||||
assert.equal(s.approval.decided, "allowed");
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { InterceptPending } from "@/lib/types";
|
||||
|
||||
export type InterceptDecision = "allowed" | "denied" | "timeout";
|
||||
|
||||
type InterceptCardRequest = "decide";
|
||||
|
||||
export type InterceptApproval = {
|
||||
pending: InterceptPending | null;
|
||||
decided: InterceptDecision | null;
|
||||
statusError: string;
|
||||
/** Bumped by "Retry details" to reload the approval. */
|
||||
retry: number;
|
||||
};
|
||||
|
||||
export type InterceptCardState = {
|
||||
detail: Record<string, unknown> | null;
|
||||
approval: InterceptApproval;
|
||||
expanded: boolean;
|
||||
/** Decision errors are toasted; only `pending` is used. */
|
||||
requests: Requests<InterceptCardRequest>;
|
||||
};
|
||||
|
||||
export type InterceptCardAction =
|
||||
| RequestAction<InterceptCardRequest>
|
||||
| { type: "detailLoaded"; detail: Record<string, unknown> }
|
||||
| { type: "approvalLoaded"; pending: InterceptPending }
|
||||
| { type: "approvalLoadFailed"; error: string }
|
||||
| { type: "retryRequested" }
|
||||
| { type: "decided"; decision: InterceptDecision }
|
||||
| { type: "expandedChanged"; expanded: boolean };
|
||||
|
||||
export const initialInterceptCardState: InterceptCardState = {
|
||||
detail: null,
|
||||
approval: { pending: null, decided: null, statusError: "", retry: 0 },
|
||||
expanded: false,
|
||||
requests: createRequests(["decide"]),
|
||||
};
|
||||
|
||||
export function interceptCardReducer(state: InterceptCardState, action: InterceptCardAction): InterceptCardState {
|
||||
if (isRequestAction<InterceptCardRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "detailLoaded":
|
||||
return { ...state, detail: action.detail };
|
||||
case "approvalLoaded": {
|
||||
const { pending } = action;
|
||||
// An already-resolved approval (e.g. after a page refresh) shows its decision instead of the buttons.
|
||||
const decided = pending.status !== "pending" ? (pending.status as InterceptDecision) : state.approval.decided;
|
||||
return { ...state, approval: { ...state.approval, pending, statusError: "", decided } };
|
||||
}
|
||||
case "approvalLoadFailed":
|
||||
return { ...state, approval: { ...state.approval, statusError: action.error } };
|
||||
case "retryRequested":
|
||||
return { ...state, approval: { ...state.approval, retry: state.approval.retry + 1 } };
|
||||
case "decided":
|
||||
if (action.decision === state.approval.decided) return state;
|
||||
return { ...state, approval: { ...state.approval, decided: action.decision } };
|
||||
case "expandedChanged":
|
||||
return setSlice(state, "expanded", action.expanded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { initialLinkTrafficState, linkTrafficReducer } from "./link-traffic-dialog.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialLinkTrafficState) => actions.reduce(linkTrafficReducer, state);
|
||||
|
||||
test("a query edit returns to page 1; the same query on page 1 keeps the state", () => {
|
||||
const s = reduce([
|
||||
{ type: "pagination/pageChanged", page: 3 },
|
||||
{ type: "queryChanged", query: "sqli" },
|
||||
]);
|
||||
assert.equal(s.pagination.page, 1);
|
||||
assert.equal(reduce([{ type: "queryChanged", query: "sqli" }], s), s);
|
||||
});
|
||||
|
||||
test("starting a load clears the previous error", () => {
|
||||
const failed = reduce([{ type: "loadFailed", error: "offline" }]);
|
||||
assert.equal(reduce([{ type: "list/loadStarted" }], failed).error, "");
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
toFirstPage,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { Finding } from "@/lib/types";
|
||||
|
||||
export const PAGE_SIZE = 20;
|
||||
|
||||
export type LinkTrafficState = {
|
||||
query: string;
|
||||
/** 1-based, as the findings API expects. */
|
||||
pagination: Pagination;
|
||||
list: ListState<Finding>;
|
||||
selected: Finding | null;
|
||||
saving: boolean;
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type LinkTrafficAction =
|
||||
| PaginationAction
|
||||
| ListAction<Finding>
|
||||
| { type: "queryChanged"; query: string }
|
||||
| { type: "findingSelected"; finding: Finding }
|
||||
| { type: "loadFailed"; error: string }
|
||||
| { type: "saveStarted" }
|
||||
| { type: "saveFailed"; error: string }
|
||||
| { type: "saveFinished" };
|
||||
|
||||
export const initialLinkTrafficState: LinkTrafficState = {
|
||||
query: "",
|
||||
pagination: createPagination(PAGE_SIZE, 1),
|
||||
list: { ...createList<Finding>(), loading: true },
|
||||
selected: null,
|
||||
saving: false,
|
||||
error: "",
|
||||
};
|
||||
|
||||
export function linkTrafficReducer(state: LinkTrafficState, action: LinkTrafficAction): LinkTrafficState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isListAction<Finding>(action)) {
|
||||
// Every load clears the previous error.
|
||||
const next = setSlice(state, "list", listReducer(state.list, action));
|
||||
return action.type === "list/loadStarted" ? setSlice(next, "error", "") : next;
|
||||
}
|
||||
switch (action.type) {
|
||||
case "queryChanged": {
|
||||
// A query edit returns to the first page.
|
||||
const pagination = toFirstPage(state.pagination);
|
||||
if (action.query === state.query && pagination === state.pagination) return state;
|
||||
return { ...state, query: action.query, pagination };
|
||||
}
|
||||
case "findingSelected":
|
||||
return setSlice(state, "selected", action.finding);
|
||||
case "loadFailed":
|
||||
return setSlice(state, "error", action.error);
|
||||
case "saveStarted":
|
||||
return { ...state, saving: true, error: "" };
|
||||
case "saveFailed":
|
||||
return setSlice(state, "error", action.error);
|
||||
case "saveFinished":
|
||||
return setSlice(state, "saving", false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { initialTaskTemplateControlsState, taskTemplateControlsReducer } from "./task-template-controls.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const tpl = (id, name = `t${id}`) => ({ id, name });
|
||||
const reduce = (actions, state = initialTaskTemplateControlsState) =>
|
||||
actions.reduce(taskTemplateControlsReducer, state);
|
||||
|
||||
test("upsert moves the template to the top; remove drops it", () => {
|
||||
let s = reduce([{ type: "list/loaded", items: [tpl(1), tpl(2), tpl(3)] }]);
|
||||
s = taskTemplateControlsReducer(s, { type: "templateUpserted", template: tpl(3, "new") });
|
||||
assert.deepEqual(
|
||||
s.templates.items.map((x) => x.name),
|
||||
["new", "t1", "t2"],
|
||||
);
|
||||
s = taskTemplateControlsReducer(s, { type: "templateRemoved", id: 1 });
|
||||
assert.deepEqual(
|
||||
s.templates.items.map((x) => x.id),
|
||||
[3, 2],
|
||||
);
|
||||
});
|
||||
|
||||
test("dismissing the overwrite confirmation restores the combobox text", () => {
|
||||
const s = reduce([
|
||||
{ type: "inputValueChanged", value: "t2" },
|
||||
{ type: "confirmRequested", template: tpl(2) },
|
||||
{ type: "confirmDismissed", inputValue: "t1" },
|
||||
]);
|
||||
assert.deepEqual(s.picker, { inputValue: "t1", pending: null });
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { TemplateSeed } from "@/components/_state/task-template-manager.reducer";
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { TaskTemplate } from "@/lib/types";
|
||||
|
||||
export type TemplatePicker = {
|
||||
inputValue: string;
|
||||
pending: TaskTemplate | null;
|
||||
};
|
||||
|
||||
export type TemplateManagerDialog = {
|
||||
open: boolean;
|
||||
seed: TemplateSeed | null;
|
||||
};
|
||||
|
||||
export type TaskTemplateControlsState = {
|
||||
templates: ListState<TaskTemplate>;
|
||||
picker: TemplatePicker;
|
||||
manager: TemplateManagerDialog;
|
||||
};
|
||||
|
||||
export type TaskTemplateControlsAction =
|
||||
| ListAction<TaskTemplate>
|
||||
| { type: "inputValueChanged"; value: string }
|
||||
| { type: "confirmRequested"; template: TaskTemplate }
|
||||
| { type: "confirmClosed" }
|
||||
/** Confirmation dismissed: the combobox text returns to the selected template. */
|
||||
| { type: "confirmDismissed"; inputValue: string }
|
||||
| { type: "managerOpened"; seed: TemplateSeed | null }
|
||||
| { type: "managerOpenChanged"; open: boolean }
|
||||
/** Created or updated: moves the template to the top of the list. */
|
||||
| { type: "templateUpserted"; template: TaskTemplate }
|
||||
| { type: "templateRemoved"; id: number };
|
||||
|
||||
export const initialTaskTemplateControlsState: TaskTemplateControlsState = {
|
||||
templates: { ...createList<TaskTemplate>(), loading: true },
|
||||
picker: { inputValue: "", pending: null },
|
||||
manager: { open: false, seed: null },
|
||||
};
|
||||
|
||||
function withItems(state: TaskTemplateControlsState, items: TaskTemplate[]): TaskTemplateControlsState {
|
||||
return { ...state, templates: { ...state.templates, items, total: items.length } };
|
||||
}
|
||||
|
||||
export function taskTemplateControlsReducer(
|
||||
state: TaskTemplateControlsState,
|
||||
action: TaskTemplateControlsAction,
|
||||
): TaskTemplateControlsState {
|
||||
if (isListAction<TaskTemplate>(action)) return setSlice(state, "templates", listReducer(state.templates, action));
|
||||
switch (action.type) {
|
||||
case "inputValueChanged":
|
||||
if (action.value === state.picker.inputValue) return state;
|
||||
return { ...state, picker: { ...state.picker, inputValue: action.value } };
|
||||
case "confirmRequested":
|
||||
return { ...state, picker: { ...state.picker, pending: action.template } };
|
||||
case "confirmClosed":
|
||||
if (state.picker.pending === null) return state;
|
||||
return { ...state, picker: { ...state.picker, pending: null } };
|
||||
case "confirmDismissed":
|
||||
return { ...state, picker: { pending: null, inputValue: action.inputValue } };
|
||||
case "managerOpened":
|
||||
return { ...state, manager: { open: true, seed: action.seed } };
|
||||
case "managerOpenChanged":
|
||||
if (action.open === state.manager.open) return state;
|
||||
return { ...state, manager: { ...state.manager, open: action.open } };
|
||||
case "templateUpserted":
|
||||
return withItems(state, [
|
||||
action.template,
|
||||
...state.templates.items.filter((item) => item.id !== action.template.id),
|
||||
]);
|
||||
case "templateRemoved":
|
||||
return withItems(
|
||||
state,
|
||||
state.templates.items.filter((template) => template.id !== action.id),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { initialTaskTemplateManagerState, taskTemplateManagerReducer } from "./task-template-manager.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const tpl = (id) => ({ id, name: `t${id}`, description: "d", goal: "g", category_id: 2, intercept_rules: [] });
|
||||
const reduce = (actions, state = initialTaskTemplateManagerState) => actions.reduce(taskTemplateManagerReducer, state);
|
||||
|
||||
test("opening without a seed edits the first template, or a blank one", () => {
|
||||
let s = reduce([{ type: "managerOpened", seed: null, templates: [tpl(7), tpl(8)] }]);
|
||||
assert.deepEqual([s.editor.selectedID, s.editor.draft.name, s.editor.draft.categoryID], [7, "t7", 2]);
|
||||
s = reduce([{ type: "managerOpened", seed: null, templates: [] }]);
|
||||
assert.deepEqual([s.editor.selectedID, s.editor.draft.name], [null, ""]);
|
||||
});
|
||||
|
||||
test("deleting moves to another template from the old list and closes the confirmation", () => {
|
||||
let s = reduce([
|
||||
{ type: "templateSelected", template: tpl(1) },
|
||||
{ type: "deleteOpenChanged", open: true },
|
||||
{ type: "templateDeleted", id: 1, templates: [tpl(1), tpl(2)] },
|
||||
]);
|
||||
assert.deepEqual([s.editor.selectedID, s.deleteOpen], [2, false]);
|
||||
s = reduce([{ type: "templateDeleted", id: 1, templates: [tpl(1)] }]);
|
||||
assert.equal(s.editor.selectedID, null);
|
||||
});
|
||||
|
||||
test("an update refreshes the draft but keeps the selection", () => {
|
||||
const s = reduce([
|
||||
{ type: "templateSelected", template: tpl(3) },
|
||||
{ type: "templateUpdated", template: { ...tpl(3), name: "renamed" } },
|
||||
]);
|
||||
assert.deepEqual([s.editor.selectedID, s.editor.draft.name], [3, "renamed"]);
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { AssetInterceptRuleInput, TaskCategory, TaskTemplate } from "@/lib/types";
|
||||
|
||||
export type TemplateDraft = {
|
||||
name: string;
|
||||
description: string;
|
||||
goal: string;
|
||||
categoryID: number | null;
|
||||
interceptRules: AssetInterceptRuleInput[];
|
||||
};
|
||||
|
||||
// TemplateSeed holds the initial values carried over from the creation form when using "Save as template".
|
||||
export type TemplateSeed = Pick<TemplateDraft, "description" | "goal" | "categoryID" | "interceptRules">;
|
||||
|
||||
type TemplateRequest = "save" | "delete";
|
||||
|
||||
/** Template being edited; `selectedID` null = a new template. */
|
||||
export type TemplateEditor = {
|
||||
selectedID: number | null;
|
||||
draft: TemplateDraft;
|
||||
};
|
||||
|
||||
export type TaskTemplateManagerState = {
|
||||
editor: TemplateEditor;
|
||||
categories: TaskCategory[];
|
||||
deleteOpen: boolean;
|
||||
/** Errors are toasted; only `pending` is used. */
|
||||
requests: Requests<TemplateRequest>;
|
||||
};
|
||||
|
||||
export type TaskTemplateManagerAction =
|
||||
| RequestAction<TemplateRequest>
|
||||
| { type: "managerOpened"; seed: TemplateSeed | null; templates: TaskTemplate[] }
|
||||
| { type: "templateSelected"; template: TaskTemplate }
|
||||
| { type: "newStarted" }
|
||||
| { type: "draftChanged"; patch: Partial<TemplateDraft> }
|
||||
| { type: "templateCreated"; template: TaskTemplate }
|
||||
| { type: "templateUpdated"; template: TaskTemplate }
|
||||
/** `templates` is the list from before the deletion. */
|
||||
| { type: "templateDeleted"; id: number; templates: TaskTemplate[] }
|
||||
| { type: "categoriesLoaded"; categories: TaskCategory[] }
|
||||
| { type: "deleteOpenChanged"; open: boolean };
|
||||
|
||||
export const emptyDraft = (): TemplateDraft => ({
|
||||
name: "",
|
||||
description: "",
|
||||
goal: "",
|
||||
categoryID: null,
|
||||
interceptRules: [],
|
||||
});
|
||||
|
||||
export function templateDraft(template: TaskTemplate): TemplateDraft {
|
||||
return {
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
goal: template.goal,
|
||||
categoryID: template.category_id ?? null,
|
||||
interceptRules: template.intercept_rules ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export const initialTaskTemplateManagerState: TaskTemplateManagerState = {
|
||||
editor: { selectedID: null, draft: emptyDraft() },
|
||||
categories: [],
|
||||
deleteOpen: false,
|
||||
requests: createRequests(["save", "delete"]),
|
||||
};
|
||||
|
||||
function edit(state: TaskTemplateManagerState, template: TaskTemplate | null): TaskTemplateManagerState {
|
||||
return {
|
||||
...state,
|
||||
editor: template
|
||||
? { selectedID: template.id, draft: templateDraft(template) }
|
||||
: { selectedID: null, draft: emptyDraft() },
|
||||
};
|
||||
}
|
||||
|
||||
export function taskTemplateManagerReducer(
|
||||
state: TaskTemplateManagerState,
|
||||
action: TaskTemplateManagerAction,
|
||||
): TaskTemplateManagerState {
|
||||
if (isRequestAction<TemplateRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "managerOpened":
|
||||
// Opening with a seed ("Save as template") starts a new template from it; otherwise edit the first template.
|
||||
if (action.seed) {
|
||||
const { description, goal, categoryID, interceptRules } = action.seed;
|
||||
return {
|
||||
...state,
|
||||
editor: { selectedID: null, draft: { name: "", description, goal, categoryID, interceptRules } },
|
||||
};
|
||||
}
|
||||
return edit(state, action.templates[0] ?? null);
|
||||
case "templateSelected":
|
||||
return edit(state, action.template);
|
||||
case "newStarted":
|
||||
return edit(state, null);
|
||||
case "draftChanged":
|
||||
return { ...state, editor: { ...state.editor, draft: { ...state.editor.draft, ...action.patch } } };
|
||||
case "templateCreated":
|
||||
return edit(state, action.template);
|
||||
case "templateUpdated":
|
||||
return { ...state, editor: { ...state.editor, draft: templateDraft(action.template) } };
|
||||
case "templateDeleted": {
|
||||
const next = action.templates.find((template) => template.id !== action.id) ?? null;
|
||||
return { ...edit(state, next), deleteOpen: false };
|
||||
}
|
||||
case "categoriesLoaded":
|
||||
return { ...state, categories: action.categories };
|
||||
case "deleteOpenChanged":
|
||||
return setSlice(state, "deleteOpen", action.open);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createTrafficPickerState, trafficPickerReducer } from "./traffic-picker-dialog.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = createTrafficPickerState()) => actions.reduce(trafficPickerReducer, state);
|
||||
|
||||
test("a filter edit returns to the first page; selections survive paging", () => {
|
||||
const first = createTrafficPickerState().pagination.page;
|
||||
const s = reduce([
|
||||
{ type: "selectionChanged", ids: ["a", "b"], checked: true },
|
||||
{ type: "pagination/pageChanged", page: first + 2 },
|
||||
{ type: "selectionChanged", ids: ["c"], checked: true },
|
||||
{ type: "selectionChanged", ids: ["a"], checked: false },
|
||||
]);
|
||||
assert.deepEqual([...s.selected].sort(), ["b", "c"]);
|
||||
assert.equal(reduce([{ type: "filtersChanged", patch: { host: "x" } }], s).pagination.page, first);
|
||||
});
|
||||
|
||||
test("starting a load clears the previous error", () => {
|
||||
const failed = reduce([{ type: "loadFailed", error: "offline" }]);
|
||||
assert.equal(reduce([{ type: "list/loadStarted" }], failed).error, "");
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
toFirstPage,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import { selectionReducer } from "@/lib/reducers/selection";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { TrafficExchange } from "@/lib/types";
|
||||
|
||||
export const PAGE_SIZE = 25;
|
||||
|
||||
export type TrafficPickerFilters = {
|
||||
host: string;
|
||||
/** "all" or an HTTP method. */
|
||||
method: string;
|
||||
query: string;
|
||||
};
|
||||
|
||||
export type TrafficPickerState = {
|
||||
filters: TrafficPickerFilters;
|
||||
pagination: Pagination;
|
||||
list: ListState<TrafficExchange>;
|
||||
/** Traffic IDs checked for binding; kept across pages. */
|
||||
selected: Set<string>;
|
||||
preview: string | null;
|
||||
saving: boolean;
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type TrafficPickerAction =
|
||||
| PaginationAction
|
||||
| ListAction<TrafficExchange>
|
||||
| { type: "filtersChanged"; patch: Partial<TrafficPickerFilters> }
|
||||
| { type: "selectionChanged"; ids: string[]; checked: boolean }
|
||||
| { type: "previewChanged"; id: string | null }
|
||||
| { type: "loadFailed"; error: string }
|
||||
| { type: "saveStarted" }
|
||||
| { type: "saveFailed"; error: string }
|
||||
| { type: "saveFinished" };
|
||||
|
||||
/** Built per mount so every dialog gets its own selection Set. */
|
||||
export function createTrafficPickerState(): TrafficPickerState {
|
||||
return {
|
||||
filters: { host: "", method: "all", query: "" },
|
||||
pagination: createPagination(PAGE_SIZE),
|
||||
list: { ...createList<TrafficExchange>(), loading: true },
|
||||
selected: new Set(),
|
||||
preview: null,
|
||||
saving: false,
|
||||
error: "",
|
||||
};
|
||||
}
|
||||
|
||||
export function trafficPickerReducer(state: TrafficPickerState, action: TrafficPickerAction): TrafficPickerState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isListAction<TrafficExchange>(action)) {
|
||||
// Every load clears the previous error.
|
||||
const next = setSlice(state, "list", listReducer(state.list, action));
|
||||
return action.type === "list/loadStarted" ? setSlice(next, "error", "") : next;
|
||||
}
|
||||
switch (action.type) {
|
||||
case "filtersChanged": {
|
||||
const filters = mergePatch(state.filters, action.patch);
|
||||
// Any filter edit returns to the first page.
|
||||
const pagination = toFirstPage(state.pagination);
|
||||
if (filters === state.filters && pagination === state.pagination) return state;
|
||||
return { ...state, filters, pagination };
|
||||
}
|
||||
case "selectionChanged": {
|
||||
const next = new Set(state.selected);
|
||||
for (const id of action.ids) {
|
||||
if (action.checked) next.add(id);
|
||||
else next.delete(id);
|
||||
}
|
||||
return setSlice(state, "selected", selectionReducer(state.selected, { type: "selection/set", ids: next }));
|
||||
}
|
||||
case "previewChanged":
|
||||
return setSlice(state, "preview", action.id);
|
||||
case "loadFailed":
|
||||
return setSlice(state, "error", action.error);
|
||||
case "saveStarted":
|
||||
return { ...state, saving: true, error: "" };
|
||||
case "saveFailed":
|
||||
return setSlice(state, "error", action.error);
|
||||
case "saveFinished":
|
||||
return setSlice(state, "saving", false);
|
||||
}
|
||||
}
|
||||
+130
-180
@@ -5,6 +5,16 @@ import * as React from "react";
|
||||
import { EyeIcon, GitCompareIcon, PencilIcon, RotateCcwIcon, SaveIcon, Trash2Icon, XIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
type AgentEditorForm,
|
||||
agentEditorReducer,
|
||||
initialAgentEditorState,
|
||||
} from "@/components/_state/agent-editor.reducer";
|
||||
import {
|
||||
agentTriggersTabReducer,
|
||||
createAgentTriggersTabState,
|
||||
type TriggerForm,
|
||||
} from "@/components/_state/agent-triggers-tab.reducer";
|
||||
import { Markdown } from "@/components/markdown";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -27,17 +37,7 @@ import { Textarea } from "@/components/ui/textarea";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type {
|
||||
Agent,
|
||||
AgentDetail,
|
||||
AgentTrigger,
|
||||
MCPServer,
|
||||
PromptVar,
|
||||
PromptVersion,
|
||||
Settings,
|
||||
SkillItem,
|
||||
Tool,
|
||||
} from "@/lib/types";
|
||||
import type { Agent, AgentTrigger, Tool } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Renders a translated string, turning <b>…</b> spans into bold elements, so a sentence with emphasis stays one key.
|
||||
@@ -53,55 +53,49 @@ const TRAFFIC_TOOL_KEYS = new Set(["traffic_search", "traffic_get"]);
|
||||
// drawer (and reused full-page for deep links). Tabs: Config & Prompt / MCP / Skill /
|
||||
// Tools. Config + prompt save as before; visibility + tool bindings toggle live.
|
||||
export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?: () => void }) {
|
||||
const [detail, setDetail] = React.useState<AgentDetail | null>(null);
|
||||
const [versions, setVersions] = React.useState<PromptVersion[]>([]);
|
||||
const [variables, setVariables] = React.useState<PromptVar[]>([]);
|
||||
const [mcp, setMcp] = React.useState<MCPServer[]>([]);
|
||||
const [skills, setSkills] = React.useState<SkillItem[]>([]);
|
||||
const [tools, setTools] = React.useState<Tool[]>([]);
|
||||
const [loaded, setLoaded] = React.useState(false);
|
||||
const [viewVer, setViewVer] = React.useState<PromptVersion | null>(null);
|
||||
const [diffVer, setDiffVer] = React.useState<PromptVersion | null>(null);
|
||||
|
||||
const [prompt, setPrompt] = React.useState("");
|
||||
const [mcpVisible, setMcpVisible] = React.useState<number[]>([]);
|
||||
const [skillVisible, setSkillVisible] = React.useState<string[]>([]);
|
||||
const [preview, setPreview] = React.useState("");
|
||||
const [maxTurns, setMaxTurns] = React.useState("0");
|
||||
const [runSecs, setRunSecs] = React.useState("600");
|
||||
// "" = follow (unbound); otherwise a profile id string
|
||||
const [llmProfileId, setLlmProfileId] = React.useState("");
|
||||
const [llmProfiles, setLlmProfiles] = React.useState<NonNullable<AgentDetail["llm_profiles"]>>([]);
|
||||
const [webSearch, setWebSearch] = React.useState(false);
|
||||
const [interactiveShell, setInteractiveShell] = React.useState(false);
|
||||
const [wrapup, setWrapup] = React.useState("");
|
||||
const [wrapupDefault, setWrapupDefault] = React.useState("");
|
||||
const [wrapupTurns, setWrapupTurns] = React.useState("0");
|
||||
const [wrapupTurnsDefault, setWrapupTurnsDefault] = React.useState(5);
|
||||
// task-level timeout wrap-up prompt (worker/planner only)
|
||||
const [ttSupported, setTtSupported] = React.useState(false);
|
||||
const [ttWrapup, setTtWrapup] = React.useState("");
|
||||
const [ttWrapupDefault, setTtWrapupDefault] = React.useState("");
|
||||
const [ttTurns, setTtTurns] = React.useState("0");
|
||||
const [ttTurnsDefault, setTtTurnsDefault] = React.useState(5);
|
||||
const [settings, setSettings] = React.useState<Settings | null>(null);
|
||||
const [state, dispatch] = React.useReducer(agentEditorReducer, initialAgentEditorState);
|
||||
const { detail, loaded, versions, variables, llmProfiles } = state.agent;
|
||||
const {
|
||||
wrapup: wrapupDefault,
|
||||
wrapupTurns: wrapupTurnsDefault,
|
||||
ttSupported,
|
||||
ttWrapup: ttWrapupDefault,
|
||||
ttTurns: ttTurnsDefault,
|
||||
} = state.defaults;
|
||||
const {
|
||||
prompt,
|
||||
maxTurns,
|
||||
runSecs,
|
||||
llmProfileId,
|
||||
webSearch,
|
||||
interactiveShell,
|
||||
wrapup,
|
||||
wrapupTurns,
|
||||
ttWrapup,
|
||||
ttTurns,
|
||||
} = state.form;
|
||||
const { mcp: mcpVisible, skill: skillVisible } = state.visibility;
|
||||
const { mcp, skills, tools, settings } = state.catalog;
|
||||
const { viewing: viewVer, diffing: diffVer } = state.versionDialogs;
|
||||
const { preview } = state;
|
||||
const setForm = (patch: Partial<AgentEditorForm>) => dispatch({ type: "formFieldChanged", patch });
|
||||
|
||||
React.useEffect(() => {
|
||||
api
|
||||
.mcpServers()
|
||||
.then(setMcp)
|
||||
.then((v) => dispatch({ type: "catalogLoaded", patch: { mcp: v } }))
|
||||
.catch((error) => toast.error(t("Load failed: {error}", { error: (error as Error).message })));
|
||||
api
|
||||
.skills()
|
||||
.then(setSkills)
|
||||
.then((v) => dispatch({ type: "catalogLoaded", patch: { skills: v } }))
|
||||
.catch((error) => toast.error(t("Load failed: {error}", { error: (error as Error).message })));
|
||||
api
|
||||
.tools()
|
||||
.then(setTools)
|
||||
.then((v) => dispatch({ type: "catalogLoaded", patch: { tools: v } }))
|
||||
.catch((error) => toast.error(t("Load failed: {error}", { error: (error as Error).message })));
|
||||
api
|
||||
.settings()
|
||||
.then(setSettings)
|
||||
.then((v) => dispatch({ type: "catalogLoaded", patch: { settings: v } }))
|
||||
.catch((error) => toast.error(t("Load failed: {error}", { error: (error as Error).message })));
|
||||
}, []);
|
||||
// global gates: traffic tools need traffic capture, web search needs the master switch.
|
||||
@@ -111,31 +105,9 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
const reload = React.useCallback(() => {
|
||||
api
|
||||
.getAgent(agentKey)
|
||||
.then((d) => {
|
||||
setDetail(d);
|
||||
setPrompt(d.prompt ?? "");
|
||||
setVariables(d.variables ?? []);
|
||||
setVersions(d.versions ?? []);
|
||||
setMcpVisible(d.visibility?.mcp ?? []);
|
||||
setSkillVisible(d.visibility?.skill ?? []);
|
||||
setMaxTurns(String(d.agent?.max_turns ?? 0));
|
||||
setRunSecs(String(d.agent?.run_seconds ?? 600));
|
||||
setLlmProfileId(d.agent?.llm_profile_id != null ? String(d.agent.llm_profile_id) : "");
|
||||
setLlmProfiles(d.llm_profiles ?? []);
|
||||
setWebSearch(!!d.agent?.web_search);
|
||||
setInteractiveShell(!!d.agent?.interactive_shell);
|
||||
setWrapup(d.wrapup_prompt ?? "");
|
||||
setWrapupDefault(d.wrapup_default ?? "");
|
||||
setWrapupTurns(String(d.wrapup_max_turns ?? 0));
|
||||
setWrapupTurnsDefault(d.wrapup_max_turns_default ?? 5);
|
||||
setTtSupported(!!d.task_timeout_wrapup_supported);
|
||||
setTtWrapup(d.task_timeout_wrapup_prompt ?? "");
|
||||
setTtWrapupDefault(d.task_timeout_wrapup_default ?? "");
|
||||
setTtTurns(String(d.task_timeout_wrapup_max_turns ?? 0));
|
||||
setTtTurnsDefault(d.task_timeout_wrapup_max_turns_default ?? 5);
|
||||
})
|
||||
.catch(() => setDetail(null))
|
||||
.finally(() => setLoaded(true));
|
||||
.then((d) => dispatch({ type: "agentLoaded", detail: d }))
|
||||
.catch(() => dispatch({ type: "agentLoadFailed" }))
|
||||
.finally(() => dispatch({ type: "agentLoadFinished" }));
|
||||
}, [agentKey]);
|
||||
React.useEffect(() => {
|
||||
reload();
|
||||
@@ -144,9 +116,12 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
async function doPreview() {
|
||||
try {
|
||||
const r = await api.previewAgentPrompt(agentKey, prompt);
|
||||
setPreview(r.error ? t("Render error: {error}", { error: r.error }) : r.rendered);
|
||||
dispatch({
|
||||
type: "previewRendered",
|
||||
text: r.error ? t("Render error: {error}", { error: r.error }) : r.rendered,
|
||||
});
|
||||
} catch (e) {
|
||||
setPreview(t("Preview failed: {error}", { error: (e as Error).message }));
|
||||
dispatch({ type: "previewRendered", text: t("Preview failed: {error}", { error: (e as Error).message }) });
|
||||
}
|
||||
}
|
||||
async function savePrompt() {
|
||||
@@ -234,15 +209,13 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
async function applyVis(nextMcp: number[], nextSkill: string[], okMsg: string) {
|
||||
const prevMcp = mcpVisible;
|
||||
const prevSkill = skillVisible;
|
||||
setMcpVisible(nextMcp);
|
||||
setSkillVisible(nextSkill);
|
||||
dispatch({ type: "visibilityChanged", patch: { mcp: nextMcp, skill: nextSkill } });
|
||||
try {
|
||||
await api.setAgentVisibility(agentKey, nextMcp, nextSkill);
|
||||
toast.success(okMsg);
|
||||
onSaved?.(); // refresh the list so the card's MCP/Skill counts stay in sync
|
||||
} catch (e) {
|
||||
setMcpVisible(prevMcp);
|
||||
setSkillVisible(prevSkill);
|
||||
dispatch({ type: "visibilityChanged", patch: { mcp: prevMcp, skill: prevSkill } });
|
||||
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
}
|
||||
@@ -267,7 +240,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
const on = tool.agents.includes(agentKey);
|
||||
const nextAgents = on ? tool.agents.filter((k) => k !== agentKey) : [...tool.agents, agentKey];
|
||||
// optimistic update
|
||||
setTools((ts) => ts.map((x) => (x.key === tool.key ? { ...x, agents: nextAgents } : x)));
|
||||
dispatch({ type: "toolAgentsChanged", key: tool.key, agents: nextAgents });
|
||||
try {
|
||||
await api.saveTool(tool.key, {
|
||||
description: tool.description,
|
||||
@@ -282,7 +255,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
reload();
|
||||
api
|
||||
.tools()
|
||||
.then(setTools)
|
||||
.then((v) => dispatch({ type: "catalogLoaded", patch: { tools: v } }))
|
||||
.catch((error) => console.error("Failed to reload tools after saving bindings:", error));
|
||||
}
|
||||
}
|
||||
@@ -331,7 +304,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Select
|
||||
value={llmProfileId || "__follow__"}
|
||||
onValueChange={(v) => setLlmProfileId(v === "__follow__" ? "" : v)}
|
||||
onValueChange={(v) => setForm({ llmProfileId: v === "__follow__" ? "" : v })}
|
||||
>
|
||||
<SelectTrigger id="llm-profile" className="h-8 w-72">
|
||||
<SelectValue />
|
||||
@@ -368,7 +341,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
min={0}
|
||||
className="h-8 w-32"
|
||||
value={maxTurns}
|
||||
onChange={(e) => setMaxTurns(e.target.value)}
|
||||
onChange={(e) => setForm({ maxTurns: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
@@ -381,7 +354,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
min={0}
|
||||
className="h-8 w-32"
|
||||
value={runSecs}
|
||||
onChange={(e) => setRunSecs(e.target.value)}
|
||||
onChange={(e) => setForm({ runSecs: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
@@ -396,7 +369,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
id="web-search"
|
||||
checked={webSearch}
|
||||
disabled={!webSearchGlobalOn}
|
||||
onCheckedChange={setWebSearch}
|
||||
onCheckedChange={(v) => setForm({ webSearch: v })}
|
||||
/>
|
||||
<div className="grid gap-0.5">
|
||||
<Label htmlFor="web-search" className="text-sm">
|
||||
@@ -414,7 +387,11 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
)}
|
||||
{showInteractiveShell && (
|
||||
<div className="flex items-center gap-3 border-t pt-3">
|
||||
<Switch id="interactive-shell" checked={interactiveShell} onCheckedChange={setInteractiveShell} />
|
||||
<Switch
|
||||
id="interactive-shell"
|
||||
checked={interactiveShell}
|
||||
onCheckedChange={(v) => setForm({ interactiveShell: v })}
|
||||
/>
|
||||
<div className="grid gap-0.5">
|
||||
<Label htmlFor="interactive-shell" className="text-sm">
|
||||
{t("Interactive shell")}
|
||||
@@ -440,7 +417,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPrompt((p) => `${p}{{.${v.name}}}`)}
|
||||
onClick={() => dispatch({ type: "variableInserted", name: v.name })}
|
||||
className="hover:bg-muted inline-flex items-center gap-1 rounded-md border bg-muted/40 px-2 py-1 font-mono text-xs"
|
||||
>
|
||||
{`{{.${v.name}}}`}
|
||||
@@ -464,7 +441,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
rows={16}
|
||||
value={prompt}
|
||||
placeholder={t("Leave empty to use the built-in default prompt")}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
onChange={(e) => setForm({ prompt: e.target.value })}
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
@@ -524,7 +501,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="size-6 shrink-0"
|
||||
onClick={() => setViewVer(ver)}
|
||||
onClick={() => dispatch({ type: "versionDialogsChanged", patch: { viewing: ver } })}
|
||||
aria-label={t("View version")}
|
||||
title={t("View version")}
|
||||
>
|
||||
@@ -535,7 +512,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="size-6 shrink-0"
|
||||
onClick={() => setDiffVer(ver)}
|
||||
onClick={() => dispatch({ type: "versionDialogsChanged", patch: { diffing: ver } })}
|
||||
aria-label={t("Compare with current")}
|
||||
title={t("Compare with current")}
|
||||
>
|
||||
@@ -556,7 +533,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
<Dialog
|
||||
open={!!viewVer}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setViewVer(null);
|
||||
if (!o) dispatch({ type: "versionDialogsChanged", patch: { viewing: null } });
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-2xl">
|
||||
@@ -587,10 +564,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (viewVer) {
|
||||
setDiffVer(viewVer);
|
||||
setViewVer(null);
|
||||
}
|
||||
if (viewVer) dispatch({ type: "viewedVersionCompared" });
|
||||
}}
|
||||
>
|
||||
<GitCompareIcon className="mr-1 size-3.5" /> {t("Compare with current")}
|
||||
@@ -600,8 +574,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (viewVer) {
|
||||
setPrompt(viewVer.template_text);
|
||||
setViewVer(null);
|
||||
dispatch({ type: "viewedVersionLoaded" });
|
||||
toast.success(
|
||||
t('Loaded v{version} into the editor; click "Save as new version" to confirm', {
|
||||
version: viewVer.version,
|
||||
@@ -620,7 +593,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
<Dialog
|
||||
open={!!diffVer}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setDiffVer(null);
|
||||
if (!o) dispatch({ type: "versionDialogsChanged", patch: { diffing: null } });
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-3xl">
|
||||
@@ -675,7 +648,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
rows={10}
|
||||
value={wrapup}
|
||||
placeholder={wrapupDefault || t("Leave empty to use the built-in default wrap-up prompt")}
|
||||
onChange={(e) => setWrapup(e.target.value)}
|
||||
onChange={(e) => setForm({ wrapup: e.target.value })}
|
||||
/>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="wrapup-turns" className="text-xs">
|
||||
@@ -689,7 +662,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
min={0}
|
||||
className="h-8 w-32"
|
||||
value={wrapupTurns}
|
||||
onChange={(e) => setWrapupTurns(e.target.value)}
|
||||
onChange={(e) => setForm({ wrapupTurns: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
@@ -743,7 +716,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
placeholder={
|
||||
ttWrapupDefault || t("Leave empty to use the built-in default task timeout wrap-up prompt")
|
||||
}
|
||||
onChange={(e) => setTtWrapup(e.target.value)}
|
||||
onChange={(e) => setForm({ ttWrapup: e.target.value })}
|
||||
/>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="tt-turns" className="text-xs">
|
||||
@@ -755,7 +728,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
min={0}
|
||||
className="h-8 w-32"
|
||||
value={ttTurns}
|
||||
onChange={(e) => setTtTurns(e.target.value)}
|
||||
onChange={(e) => setForm({ ttTurns: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
@@ -932,16 +905,38 @@ function DiffView({ oldText, newText }: { oldText: string; newText: string }) {
|
||||
// Each trigger fires (schedule/finding found/goal met/task timeout/tool call, multi-select) → a new conversation runs
|
||||
// in parallel with the base user message + auto context appended by the backend.
|
||||
function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent }) {
|
||||
const [triggers, setTriggers] = React.useState<AgentTrigger[]>([]);
|
||||
const [tools, setTools] = React.useState<Tool[]>([]);
|
||||
const [state, dispatch] = React.useReducer(agentTriggersTabReducer, agent, createAgentTriggersTabState);
|
||||
const { triggers, tools } = state;
|
||||
// post-trigger handling policy (per agent); initial value comes from agent detail, saved on change.
|
||||
const [runMode, setRunMode] = React.useState<"serial" | "parallel">(agent?.trigger_run_mode ?? "serial");
|
||||
const [mergeMode, setMergeMode] = React.useState<"by_task" | "all" | "none">(agent?.trigger_merge_mode ?? "all");
|
||||
const [maxParallel, setMaxParallel] = React.useState(String(agent?.trigger_max_parallel ?? 5));
|
||||
const { runMode, mergeMode, maxParallel } = state.behavior;
|
||||
const { editingId, form } = state.editor;
|
||||
const {
|
||||
onInterval,
|
||||
intervalSec,
|
||||
onFinding,
|
||||
onGoalMet,
|
||||
onTaskTimeout,
|
||||
onToolCall,
|
||||
onTaskCreate,
|
||||
intervalMsg,
|
||||
findingMsg,
|
||||
goalMsg,
|
||||
taskTimeoutMsg,
|
||||
toolCallMsg,
|
||||
taskCreateMsg,
|
||||
toolNames,
|
||||
} = form;
|
||||
const saving = state.requests.save.pending;
|
||||
const setForm = (patch: Partial<TriggerForm>) => dispatch({ type: "formFieldChanged", patch });
|
||||
React.useEffect(() => {
|
||||
setRunMode(agent?.trigger_run_mode ?? "serial");
|
||||
setMergeMode(agent?.trigger_merge_mode ?? "all");
|
||||
setMaxParallel(String(agent?.trigger_max_parallel ?? 5));
|
||||
dispatch({
|
||||
type: "behaviorSynced",
|
||||
policy: {
|
||||
trigger_run_mode: agent?.trigger_run_mode,
|
||||
trigger_merge_mode: agent?.trigger_merge_mode,
|
||||
trigger_max_parallel: agent?.trigger_max_parallel,
|
||||
},
|
||||
});
|
||||
}, [agent?.trigger_run_mode, agent?.trigger_merge_mode, agent?.trigger_max_parallel]);
|
||||
|
||||
async function saveBehavior(patch: {
|
||||
@@ -955,29 +950,12 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
toast.error(t("Failed to save policy: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
}
|
||||
const [onInterval, setOnInterval] = React.useState(false);
|
||||
const [intervalSec, setIntervalSec] = React.useState("60");
|
||||
const [onFinding, setOnFinding] = React.useState(false);
|
||||
const [onGoalMet, setOnGoalMet] = React.useState(false);
|
||||
const [onTaskTimeout, setOnTaskTimeout] = React.useState(false);
|
||||
const [onToolCall, setOnToolCall] = React.useState(false);
|
||||
const [onTaskCreate, setOnTaskCreate] = React.useState(false);
|
||||
const [intervalMsg, setIntervalMsg] = React.useState("");
|
||||
const [findingMsg, setFindingMsg] = React.useState("");
|
||||
const [goalMsg, setGoalMsg] = React.useState("");
|
||||
const [taskTimeoutMsg, setTaskTimeoutMsg] = React.useState("");
|
||||
const [toolCallMsg, setToolCallMsg] = React.useState("");
|
||||
const [taskCreateMsg, setTaskCreateMsg] = React.useState("");
|
||||
const [toolNames, setToolNames] = React.useState<string[]>([]);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
// null = create mode; non-null = editing the trigger with that id.
|
||||
const [editingId, setEditingId] = React.useState<number | null>(null);
|
||||
|
||||
const reload = React.useCallback(() => {
|
||||
api
|
||||
.agentTriggers(agentKey)
|
||||
.then(setTriggers)
|
||||
.catch(() => setTriggers([]));
|
||||
.then((v) => dispatch({ type: "triggersLoaded", triggers: v }))
|
||||
.catch(() => dispatch({ type: "triggersLoaded", triggers: [] }));
|
||||
}, [agentKey]);
|
||||
React.useEffect(() => {
|
||||
reload();
|
||||
@@ -985,50 +963,22 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
React.useEffect(() => {
|
||||
api
|
||||
.tools()
|
||||
.then(setTools)
|
||||
.catch(() => setTools([]));
|
||||
.then((v) => dispatch({ type: "toolsLoaded", tools: v }))
|
||||
.catch(() => dispatch({ type: "toolsLoaded", tools: [] }));
|
||||
}, []);
|
||||
|
||||
function toggleTool(key: string) {
|
||||
setToolNames((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]));
|
||||
dispatch({ type: "toolNameToggled", key });
|
||||
}
|
||||
|
||||
// resetForm clears the form and returns to "create" mode.
|
||||
function resetForm() {
|
||||
setEditingId(null);
|
||||
setOnInterval(false);
|
||||
setIntervalSec("60");
|
||||
setOnFinding(false);
|
||||
setOnGoalMet(false);
|
||||
setOnTaskTimeout(false);
|
||||
setOnToolCall(false);
|
||||
setOnTaskCreate(false);
|
||||
setIntervalMsg("");
|
||||
setFindingMsg("");
|
||||
setGoalMsg("");
|
||||
setTaskTimeoutMsg("");
|
||||
setToolCallMsg("");
|
||||
setTaskCreateMsg("");
|
||||
setToolNames([]);
|
||||
dispatch({ type: "formReset" });
|
||||
}
|
||||
|
||||
// startEdit fills the form with an existing trigger and enters "edit" mode.
|
||||
function startEdit(trg: AgentTrigger) {
|
||||
setEditingId(trg.id);
|
||||
setOnInterval(trg.interval_sec > 0);
|
||||
setIntervalSec(trg.interval_sec > 0 ? String(trg.interval_sec) : "60");
|
||||
setOnFinding(trg.on_finding);
|
||||
setOnGoalMet(trg.on_goal_met);
|
||||
setOnTaskTimeout(trg.on_task_timeout);
|
||||
setOnToolCall(trg.on_tool_call);
|
||||
setOnTaskCreate(trg.on_task_create);
|
||||
setIntervalMsg(trg.interval_message);
|
||||
setFindingMsg(trg.finding_message);
|
||||
setGoalMsg(trg.goal_message);
|
||||
setTaskTimeoutMsg(trg.task_timeout_message);
|
||||
setToolCallMsg(trg.tool_call_message);
|
||||
setTaskCreateMsg(trg.task_create_message);
|
||||
setToolNames(trg.tool_names ?? []);
|
||||
dispatch({ type: "editStarted", trigger: trg });
|
||||
}
|
||||
|
||||
// submit creates or saves changes based on editingId; editing keeps the trigger's enabled state.
|
||||
@@ -1057,7 +1007,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
task_create_message: taskCreateMsg.trim(),
|
||||
tool_names: onToolCall ? toolNames : [],
|
||||
};
|
||||
setSaving(true);
|
||||
dispatch({ type: "request/started", key: "save" });
|
||||
try {
|
||||
if (editingId != null) {
|
||||
const cur = triggers.find((x) => x.id === editingId);
|
||||
@@ -1073,7 +1023,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
const error = (e as Error).message;
|
||||
toast.error(editingId != null ? t("Save failed: {error}", { error }) : t("Add failed: {error}", { error }));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
dispatch({ type: "request/finished", key: "save" });
|
||||
}
|
||||
}
|
||||
async function toggleEnabled(trg: AgentTrigger) {
|
||||
@@ -1142,7 +1092,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
value={runMode}
|
||||
onValueChange={(v) => {
|
||||
const rm = v as "serial" | "parallel";
|
||||
setRunMode(rm);
|
||||
dispatch({ type: "behaviorChanged", patch: { runMode: rm } });
|
||||
void saveBehavior({ trigger_run_mode: rm });
|
||||
}}
|
||||
>
|
||||
@@ -1163,7 +1113,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
disabled={runMode === "parallel"}
|
||||
onValueChange={(v) => {
|
||||
const mm = v as "by_task" | "all" | "none";
|
||||
setMergeMode(mm);
|
||||
dispatch({ type: "behaviorChanged", patch: { mergeMode: mm } });
|
||||
void saveBehavior({ trigger_merge_mode: mm });
|
||||
}}
|
||||
>
|
||||
@@ -1189,10 +1139,10 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
min={0}
|
||||
className="h-8 w-28"
|
||||
value={maxParallel}
|
||||
onChange={(e) => setMaxParallel(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "behaviorChanged", patch: { maxParallel: e.target.value } })}
|
||||
onBlur={() => {
|
||||
const n = Math.max(0, Math.floor(Number(maxParallel) || 0));
|
||||
setMaxParallel(String(n));
|
||||
dispatch({ type: "behaviorChanged", patch: { maxParallel: String(n) } });
|
||||
void saveBehavior({ trigger_max_parallel: n });
|
||||
}}
|
||||
/>
|
||||
@@ -1230,7 +1180,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Scheduled trigger")}
|
||||
checked={onInterval}
|
||||
onCheckedChange={(v) => setOnInterval(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onInterval: !!v })}
|
||||
/>
|
||||
{t("Scheduled trigger")}
|
||||
</div>
|
||||
@@ -1246,7 +1196,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
min={1}
|
||||
className="h-8 w-24"
|
||||
value={intervalSec}
|
||||
onChange={(e) => setIntervalSec(e.target.value)}
|
||||
onChange={(e) => setForm({ intervalSec: e.target.value })}
|
||||
/>
|
||||
<span className="text-muted-foreground text-xs">{t("seconds")}</span>
|
||||
</div>
|
||||
@@ -1255,7 +1205,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
rows={2}
|
||||
value={intervalMsg}
|
||||
placeholder={t("Message sent to the agent when the schedule fires, e.g. inspect all tasks")}
|
||||
onChange={(e) => setIntervalMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ intervalMsg: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -1267,7 +1217,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Trigger on finding")}
|
||||
checked={onFinding}
|
||||
onCheckedChange={(v) => setOnFinding(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onFinding: !!v })}
|
||||
/>
|
||||
{t("Trigger on finding")}
|
||||
</div>
|
||||
@@ -1279,7 +1229,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
placeholder={t(
|
||||
"Message sent to the agent when a finding is found (the system attaches task and finding details)",
|
||||
)}
|
||||
onChange={(e) => setFindingMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ findingMsg: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -1290,7 +1240,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Trigger on goal met")}
|
||||
checked={onGoalMet}
|
||||
onCheckedChange={(v) => setOnGoalMet(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onGoalMet: !!v })}
|
||||
/>
|
||||
{t("Trigger on goal met")}
|
||||
</div>
|
||||
@@ -1302,7 +1252,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
placeholder={t(
|
||||
"Message sent to the agent when a goal is met (the system attaches the task and the met goal)",
|
||||
)}
|
||||
onChange={(e) => setGoalMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ goalMsg: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -1313,7 +1263,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Trigger on task timeout")}
|
||||
checked={onTaskTimeout}
|
||||
onCheckedChange={(v) => setOnTaskTimeout(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onTaskTimeout: !!v })}
|
||||
/>
|
||||
{t("Trigger on task timeout")}
|
||||
</div>
|
||||
@@ -1323,7 +1273,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
rows={2}
|
||||
value={taskTimeoutMsg}
|
||||
placeholder={t("Message sent to the agent on task timeout (the system attaches the task id and goals)")}
|
||||
onChange={(e) => setTaskTimeoutMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ taskTimeoutMsg: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -1334,7 +1284,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Trigger on tool call")}
|
||||
checked={onToolCall}
|
||||
onCheckedChange={(v) => setOnToolCall(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onToolCall: !!v })}
|
||||
/>
|
||||
{t("Trigger on tool call")}
|
||||
</div>
|
||||
@@ -1378,7 +1328,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
placeholder={t(
|
||||
"Message sent to the agent when a tool is called (the system attaches task info, tool input and output)",
|
||||
)}
|
||||
onChange={(e) => setToolCallMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ toolCallMsg: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -1390,7 +1340,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Trigger on task created")}
|
||||
checked={onTaskCreate}
|
||||
onCheckedChange={(v) => setOnTaskCreate(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onTaskCreate: !!v })}
|
||||
/>
|
||||
{t("Trigger on task created")}
|
||||
</div>
|
||||
@@ -1402,7 +1352,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
placeholder={t(
|
||||
"Message sent to the agent when a task is created (the system attaches the task id and goals)",
|
||||
)}
|
||||
onChange={(e) => setTaskCreateMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ taskCreateMsg: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -45,12 +45,13 @@ import type {
|
||||
InterceptApprovalRow,
|
||||
InterceptAudit,
|
||||
InterceptDetail,
|
||||
InterceptPending,
|
||||
InterceptReviewInput,
|
||||
InterceptRisk,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { approvalRecordsReducer, initialApprovalRecordsState } from "./_state/approval-records.reducer";
|
||||
|
||||
function source(row: InterceptApprovalRow) {
|
||||
if (row.decision_source) return row.decision_source;
|
||||
if (row.rule_id) return "rule";
|
||||
@@ -877,21 +878,17 @@ function ApprovalTable({
|
||||
}
|
||||
|
||||
export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
const [rows, setRows] = React.useState<InterceptApprovalRow[]>([]);
|
||||
const [pendingRows, setPendingRows] = React.useState<InterceptPending[]>([]);
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [pageSize, setPageSize] = React.useState(20);
|
||||
const [total, setTotal] = React.useState(0);
|
||||
const [filter, setFilter] = React.useState<InterceptApprovalFilter>({});
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [refreshing, setRefreshing] = React.useState(false);
|
||||
const [error, setError] = React.useState("");
|
||||
const [pendingError, setPendingError] = React.useState("");
|
||||
const [deciding, setDeciding] = React.useState(false);
|
||||
const [revision, setRevision] = React.useState(0);
|
||||
const [selected, setSelected] = React.useState<Set<number>>(() => new Set());
|
||||
const [batchDecision, setBatchDecision] = React.useState<"allowed" | "denied" | null>(null);
|
||||
const [batchErrors, setBatchErrors] = React.useState<{ id: number; error: string }[]>([]);
|
||||
const [state, dispatch] = React.useReducer(approvalRecordsReducer, initialApprovalRecordsState);
|
||||
const { filter, pagination, list, pendingRows, revision, batch } = state;
|
||||
const { page, size: pageSize } = pagination;
|
||||
const { items: rows, total } = list;
|
||||
// Skeleton until the first load for the current filter settles; spinner while a manual refresh runs.
|
||||
const loading = !list.loaded;
|
||||
const refreshing = list.loading;
|
||||
const { history: error, pending: pendingError } = state.errors;
|
||||
const deciding = state.requests.decide.pending;
|
||||
const selected = state.selection;
|
||||
const { decision: batchDecision, errors: batchErrors } = batch;
|
||||
const request = React.useRef(0);
|
||||
const decisionLock = React.useRef(false);
|
||||
const filterID = React.useId();
|
||||
@@ -901,13 +898,13 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
// Reset the cursor so the new scope always starts at its newest records.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: taskId intentionally resets pagination when scope changes.
|
||||
React.useEffect(() => {
|
||||
setPage(1);
|
||||
dispatch({ type: "pagination/pageChanged", page: 1 });
|
||||
}, [taskId]);
|
||||
|
||||
const load = React.useCallback(
|
||||
async (manual = false) => {
|
||||
const id = ++request.current;
|
||||
if (manual) setRefreshing(true);
|
||||
if (manual) dispatch({ type: "list/loadStarted" });
|
||||
try {
|
||||
// The approval queue is independent of the current history page and its
|
||||
// filter. Older requests must remain actionable even when newer decisions
|
||||
@@ -919,27 +916,23 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
api.interceptPending(),
|
||||
]);
|
||||
if (id !== request.current) return;
|
||||
if (history.status === "fulfilled") {
|
||||
setRows(history.value.items);
|
||||
setTotal(history.value.total);
|
||||
setError("");
|
||||
} else {
|
||||
setError((history.reason as Error).message || t("Failed to load"));
|
||||
}
|
||||
if (pending.status === "fulfilled") {
|
||||
setPendingRows(pending.value);
|
||||
setPendingError("");
|
||||
} else {
|
||||
setPendingError((pending.reason as Error).message || t("Failed to load"));
|
||||
}
|
||||
if (manual) setRevision((v) => v + 1);
|
||||
dispatch({
|
||||
type: "loadSettled",
|
||||
history:
|
||||
history.status === "fulfilled"
|
||||
? { ok: true, value: history.value }
|
||||
: { ok: false, error: (history.reason as Error).message || t("Failed to load") },
|
||||
pending:
|
||||
pending.status === "fulfilled"
|
||||
? { ok: true, value: pending.value }
|
||||
: { ok: false, error: (pending.reason as Error).message || t("Failed to load") },
|
||||
manual,
|
||||
});
|
||||
} catch (e) {
|
||||
if (id === request.current) setError((e as Error).message || t("Failed to load"));
|
||||
if (id === request.current)
|
||||
dispatch({ type: "historyFailed", error: (e as Error).message || t("Failed to load") });
|
||||
} finally {
|
||||
if (id === request.current) {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
if (id === request.current) dispatch({ type: "list/loadFinished" });
|
||||
}
|
||||
},
|
||||
[taskId, page, pageSize, filter],
|
||||
@@ -956,39 +949,25 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const changePageSize = (next: number) => {
|
||||
setPageSize(next);
|
||||
setPage(1);
|
||||
};
|
||||
const changePageSize = (next: number) => dispatch({ type: "pagination/sizeChanged", size: next });
|
||||
|
||||
const changeFilter = (next: InterceptApprovalFilter) => {
|
||||
// An in-flight response for the old filter must not repopulate the table.
|
||||
request.current++;
|
||||
setFilter(next);
|
||||
setPage(1);
|
||||
setRows([]);
|
||||
setTotal(0);
|
||||
setError("");
|
||||
setLoading(true);
|
||||
dispatch({ type: "filterChanged", filter: next });
|
||||
};
|
||||
|
||||
const decide: Decide = async (id, decision) => {
|
||||
if (decisionLock.current) return;
|
||||
decisionLock.current = true;
|
||||
setDeciding(true);
|
||||
dispatch({ type: "request/started", key: "decide" });
|
||||
try {
|
||||
await api.interceptDecide(id, decision);
|
||||
// Invalidate a list request started before this decision.
|
||||
request.current++;
|
||||
// Optimistically drop the decided item from the independent pending queue
|
||||
// for instant feedback; the re-fetch below reconciles with server truth.
|
||||
setRows((prev) =>
|
||||
prev.map((row) =>
|
||||
row.id === id ? { ...row, status: decision, decided_by: "human", decided_at: new Date().toISOString() } : row,
|
||||
),
|
||||
);
|
||||
setPendingRows((prev) => prev.filter((row) => row.id !== id));
|
||||
setRevision((v) => v + 1);
|
||||
dispatch({ type: "decided", id, decision, at: new Date().toISOString() });
|
||||
toast.success(decision === "allowed" ? t("Execution allowed") : t("Execution denied"));
|
||||
// Re-fetch counts and rows: a decided item may no longer match the filter.
|
||||
await latestLoad.current(true);
|
||||
@@ -997,7 +976,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
await latestLoad.current(true);
|
||||
} finally {
|
||||
decisionLock.current = false;
|
||||
setDeciding(false);
|
||||
dispatch({ type: "request/finished", key: "decide" });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1016,15 +995,13 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
const selectedHigh = selectedRows.filter((row) => row.risk?.level === "high").length;
|
||||
const selection: Selection = {
|
||||
selected,
|
||||
toggle: (id) =>
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
}),
|
||||
toggle: (id) => dispatch({ type: "selection/toggled", id }),
|
||||
toggleAll: () =>
|
||||
setSelected(selectedRows.length === pending.length ? new Set() : new Set(pending.map((row) => row.id))),
|
||||
dispatch(
|
||||
selectedRows.length === pending.length
|
||||
? { type: "selection/cleared" }
|
||||
: { type: "selection/set", ids: pending.map((row) => row.id) },
|
||||
),
|
||||
};
|
||||
|
||||
// Each id is decided by the server exactly like a single decision. The server
|
||||
@@ -1038,7 +1015,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
const ids = selectedRows.map((row) => row.id);
|
||||
if (!ids.length || decisionLock.current) return;
|
||||
decisionLock.current = true;
|
||||
setDeciding(true);
|
||||
dispatch({ type: "request/started", key: "decide" });
|
||||
let decided = 0;
|
||||
const failed: { id: number; error: string }[] = [];
|
||||
try {
|
||||
@@ -1054,9 +1031,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
}
|
||||
}
|
||||
request.current++;
|
||||
setBatchErrors(failed);
|
||||
setSelected(new Set(failed.map((f) => f.id)));
|
||||
setRevision((v) => v + 1);
|
||||
dispatch({ type: "batchDecided", failed });
|
||||
if (failed.length)
|
||||
toast.error(
|
||||
decision === "allowed"
|
||||
@@ -1075,8 +1050,8 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
);
|
||||
} finally {
|
||||
decisionLock.current = false;
|
||||
setDeciding(false);
|
||||
setBatchDecision(null);
|
||||
dispatch({ type: "request/finished", key: "decide" });
|
||||
dispatch({ type: "batchChanged", patch: { decision: null } });
|
||||
await latestLoad.current(true);
|
||||
}
|
||||
};
|
||||
@@ -1226,7 +1201,11 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-t px-4 py-3 text-sm">
|
||||
<span className="text-muted-foreground">{t("{count} selected", { count: selectedRows.length })}</span>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" disabled={deciding || !selectedRows.length} onClick={() => setBatchDecision("allowed")}>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={deciding || !selectedRows.length}
|
||||
onClick={() => dispatch({ type: "batchChanged", patch: { decision: "allowed" } })}
|
||||
>
|
||||
<CheckIcon data-icon="inline-start" />
|
||||
{t("Approve selected")}
|
||||
</Button>
|
||||
@@ -1234,7 +1213,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
disabled={deciding || !selectedRows.length}
|
||||
onClick={() => setBatchDecision("denied")}
|
||||
onClick={() => dispatch({ type: "batchChanged", patch: { decision: "denied" } })}
|
||||
>
|
||||
<XIcon data-icon="inline-start" />
|
||||
{t("Deny selected")}
|
||||
@@ -1246,7 +1225,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
<AlertDialog
|
||||
open={batchDecision != null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !deciding) setBatchDecision(null);
|
||||
if (!open && !deciding) dispatch({ type: "batchChanged", patch: { decision: null } });
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
@@ -1322,7 +1301,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
total={total}
|
||||
onPageChange={setPage}
|
||||
onPageChange={(next) => dispatch({ type: "pagination/pageChanged", page: next })}
|
||||
onPageSizeChange={changePageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
/>
|
||||
|
||||
@@ -5,6 +5,10 @@ import * as React from "react";
|
||||
import { ArrowDownIcon, ArrowUpIcon, PlusIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
findingTrafficPanelReducer,
|
||||
initialFindingTrafficPanelState,
|
||||
} from "@/components/_state/finding-traffic-panel.reducer";
|
||||
import { TrafficEvidenceViewer } from "@/components/traffic-evidence-viewer";
|
||||
import { TrafficPickerDialog } from "@/components/traffic-picker-dialog";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
@@ -26,7 +30,7 @@ import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { FindingTraffic, FindingTrafficBinding, TrafficEvidenceRole } from "@/lib/types";
|
||||
import type { FindingTraffic, TrafficEvidenceRole } from "@/lib/types";
|
||||
|
||||
const ROLES: Record<TrafficEvidenceRole, string> = {
|
||||
baseline: t("Baseline"),
|
||||
@@ -46,45 +50,39 @@ export function FindingTrafficPanel({
|
||||
readOnly?: boolean;
|
||||
onChanged: () => void;
|
||||
}) {
|
||||
const [data, setData] = React.useState<FindingTraffic | null>(null);
|
||||
const [error, setError] = React.useState("");
|
||||
const [adding, setAdding] = React.useState(false);
|
||||
const [preview, setPreview] = React.useState<string | null>(null);
|
||||
const [editing, setEditing] = React.useState<FindingTrafficBinding | null>(null);
|
||||
const [role, setRole] = React.useState<TrafficEvidenceRole>("supporting");
|
||||
const [note, setNote] = React.useState("");
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const [reload, setReload] = React.useState(0);
|
||||
const [state, dispatch] = React.useReducer(findingTrafficPanelReducer, initialFindingTrafficPanelState);
|
||||
const { data, error, reloadTick } = state.evidence;
|
||||
const { binding: editing, role, note } = state.editor;
|
||||
const { adding, preview } = state;
|
||||
const busy = state.requests.mutate.pending;
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: retry token intentionally refreshes this request.
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
setData(null);
|
||||
setError("");
|
||||
dispatch({ type: "loadStarted" });
|
||||
api
|
||||
.findingTraffic(findingId, contextTask)
|
||||
.then((value) => {
|
||||
if (active) setData(value);
|
||||
if (active) dispatch({ type: "loaded", data: value });
|
||||
})
|
||||
.catch((e: Error) => {
|
||||
if (active) setError(e.message);
|
||||
if (active) dispatch({ type: "loadFailed", error: e.message });
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [findingId, contextTask, reload]);
|
||||
}, [findingId, contextTask, reloadTick]);
|
||||
|
||||
async function mutate(action: () => Promise<FindingTraffic>) {
|
||||
setBusy(true);
|
||||
dispatch({ type: "request/started", key: "mutate" });
|
||||
try {
|
||||
setData(await action());
|
||||
setEditing(null);
|
||||
dispatch({ type: "mutated", data: await action() });
|
||||
onChanged();
|
||||
toast.success(t("Traffic evidence updated"));
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
setReload((n) => n + 1);
|
||||
dispatch({ type: "reloadRequested" });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
dispatch({ type: "request/finished", key: "mutate" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +102,12 @@ export function FindingTrafficPanel({
|
||||
{t("Linked traffic")} {data ? `(${data.bindings.length})` : ""}
|
||||
</CardTitle>
|
||||
{!readOnly ? (
|
||||
<Button variant="outline" size="sm" disabled={!data || busy} onClick={() => setAdding(true)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!data || busy}
|
||||
onClick={() => dispatch({ type: "addingChanged", open: true })}
|
||||
>
|
||||
<PlusIcon data-icon="inline-start" />
|
||||
{t("Link traffic")}
|
||||
</Button>
|
||||
@@ -123,7 +126,7 @@ export function FindingTrafficPanel({
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>
|
||||
{error}
|
||||
<Button variant="link" onClick={() => setReload((n) => n + 1)}>
|
||||
<Button variant="link" onClick={() => dispatch({ type: "reloadRequested" })}>
|
||||
{t("Retry")}
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
@@ -155,7 +158,7 @@ export function FindingTrafficPanel({
|
||||
<Button
|
||||
variant="link"
|
||||
className="h-auto justify-start p-0 text-left whitespace-normal"
|
||||
onClick={() => setPreview(b.id)}
|
||||
onClick={() => dispatch({ type: "previewChanged", id: b.id })}
|
||||
>
|
||||
<span className="break-all font-mono text-xs">{b.snapshot.url}</span>
|
||||
</Button>
|
||||
@@ -165,7 +168,7 @@ export function FindingTrafficPanel({
|
||||
{new Date(b.snapshot.captured_at * 1000).toLocaleString(intlLocale)}
|
||||
</span>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<Button variant="outline" size="sm" onClick={() => setPreview(b.id)}>
|
||||
<Button variant="outline" size="sm" onClick={() => dispatch({ type: "previewChanged", id: b.id })}>
|
||||
{t("View message")}
|
||||
</Button>
|
||||
{!readOnly ? (
|
||||
@@ -174,11 +177,7 @@ export function FindingTrafficPanel({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
setEditing(b);
|
||||
setRole(b.role);
|
||||
setNote(b.note);
|
||||
}}
|
||||
onClick={() => dispatch({ type: "editStarted", binding: b })}
|
||||
>
|
||||
{t("Edit note")}
|
||||
</Button>
|
||||
@@ -224,9 +223,9 @@ export function FindingTrafficPanel({
|
||||
findingId={findingId}
|
||||
contextTask={contextTask}
|
||||
bound={data.bindings}
|
||||
onClose={() => setAdding(false)}
|
||||
onClose={() => dispatch({ type: "addingChanged", open: false })}
|
||||
onBound={() => {
|
||||
setReload((n) => n + 1);
|
||||
dispatch({ type: "reloadRequested" });
|
||||
onChanged();
|
||||
}}
|
||||
/>
|
||||
@@ -235,12 +234,12 @@ export function FindingTrafficPanel({
|
||||
findingId={findingId}
|
||||
bindingId={preview}
|
||||
contextTask={contextTask}
|
||||
onClose={() => setPreview(null)}
|
||||
onClose={() => dispatch({ type: "previewChanged", id: null })}
|
||||
/>
|
||||
<Dialog
|
||||
open={editing !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !busy) setEditing(null);
|
||||
if (!open && !busy) dispatch({ type: "editorChanged", patch: { binding: null } });
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
@@ -253,7 +252,10 @@ export function FindingTrafficPanel({
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="evidence-role">{t("Role")}</FieldLabel>
|
||||
<Select value={role} onValueChange={(v) => setRole(v as TrafficEvidenceRole)}>
|
||||
<Select
|
||||
value={role}
|
||||
onValueChange={(v) => dispatch({ type: "editorChanged", patch: { role: v as TrafficEvidenceRole } })}
|
||||
>
|
||||
<SelectTrigger id="evidence-role">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -270,11 +272,19 @@ export function FindingTrafficPanel({
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="evidence-note">{t("Evidence note")}</FieldLabel>
|
||||
<Textarea id="evidence-note" value={note} onChange={(e) => setNote(e.target.value)} />
|
||||
<Textarea
|
||||
id="evidence-note"
|
||||
value={note}
|
||||
onChange={(e) => dispatch({ type: "editorChanged", patch: { note: e.target.value } })}
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" disabled={busy} onClick={() => setEditing(null)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() => dispatch({ type: "editorChanged", patch: { binding: null } })}
|
||||
>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
|
||||
@@ -4,6 +4,11 @@ import * as React from "react";
|
||||
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
initialLinkTrafficState,
|
||||
linkTrafficReducer,
|
||||
PAGE_SIZE,
|
||||
} from "@/components/_state/link-traffic-dialog.reducer";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -18,7 +23,6 @@ import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Finding, FindingsPage } from "@/lib/types";
|
||||
|
||||
export function LinkTrafficDialog({
|
||||
trafficIds,
|
||||
@@ -29,28 +33,24 @@ export function LinkTrafficDialog({
|
||||
onClose: () => void;
|
||||
onBound: () => void;
|
||||
}) {
|
||||
const [query, setQuery] = React.useState("");
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [data, setData] = React.useState<FindingsPage | null>(null);
|
||||
const [selected, setSelected] = React.useState<Finding | null>(null);
|
||||
const [error, setError] = React.useState("");
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [state, dispatch] = React.useReducer(linkTrafficReducer, initialLinkTrafficState);
|
||||
const { query, selected, saving: busy, error } = state;
|
||||
const { page } = state.pagination;
|
||||
const { items, total, loading } = state.list;
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
dispatch({ type: "list/loadStarted" });
|
||||
const timer = setTimeout(() => {
|
||||
api
|
||||
.findingsPage({ page, pageSize: 20, query })
|
||||
.findingsPage({ page, pageSize: PAGE_SIZE, query })
|
||||
.then((d) => {
|
||||
if (active) setData(d);
|
||||
if (active) dispatch({ type: "list/loaded", items: d.items, total: d.total });
|
||||
})
|
||||
.catch((e: Error) => {
|
||||
if (active) setError(e.message);
|
||||
if (active) dispatch({ type: "loadFailed", error: e.message });
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setLoading(false);
|
||||
if (active) dispatch({ type: "list/loadFinished" });
|
||||
});
|
||||
}, 250);
|
||||
return () => {
|
||||
@@ -60,8 +60,7 @@ export function LinkTrafficDialog({
|
||||
}, [query, page]);
|
||||
async function save() {
|
||||
if (!selected?.finding_id) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
dispatch({ type: "saveStarted" });
|
||||
try {
|
||||
await api.bindFindingTraffic(
|
||||
selected.finding_id,
|
||||
@@ -76,9 +75,9 @@ export function LinkTrafficDialog({
|
||||
onBound();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
dispatch({ type: "saveFailed", error: (e as Error).message });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
dispatch({ type: "saveFinished" });
|
||||
}
|
||||
}
|
||||
return (
|
||||
@@ -104,10 +103,7 @@ export function LinkTrafficDialog({
|
||||
id="link-finding-query"
|
||||
placeholder={t("Name / summary / vulnerability class")}
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
onChange={(e) => dispatch({ type: "queryChanged", query: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
@@ -117,14 +113,14 @@ export function LinkTrafficDialog({
|
||||
</Alert>
|
||||
) : null}
|
||||
<div className="flex max-h-[40vh] flex-col gap-2 overflow-auto" aria-busy={loading}>
|
||||
{(data?.items ?? []).map((f) => (
|
||||
{items.map((f) => (
|
||||
<Button
|
||||
key={f.finding_id ?? f.id}
|
||||
variant={selected?.finding_id === f.finding_id ? "secondary" : "outline"}
|
||||
className="h-auto justify-start p-3 text-left whitespace-normal"
|
||||
aria-pressed={selected?.finding_id === f.finding_id}
|
||||
disabled={busy || !f.finding_id || f.inherited}
|
||||
onClick={() => setSelected(f)}
|
||||
onClick={() => dispatch({ type: "findingSelected", finding: f })}
|
||||
>
|
||||
<span className="flex min-w-0 flex-col gap-1">
|
||||
<span>
|
||||
@@ -134,22 +130,27 @@ export function LinkTrafficDialog({
|
||||
</span>
|
||||
</Button>
|
||||
))}
|
||||
{!data?.items.length ? (
|
||||
{!items.length ? (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||
{loading ? t("Loading…") : t("No matching vulnerabilities; register one first")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Button variant="outline" size="sm" disabled={loading || page <= 1} onClick={() => setPage((p) => p - 1)}>
|
||||
{t("Previous")}
|
||||
</Button>
|
||||
<span className="text-xs">{t("Page {page} · {total} total", { page, total: data?.total ?? 0 })}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || page * 20 >= (data?.total ?? 0)}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
disabled={loading || page <= 1}
|
||||
onClick={() => dispatch({ type: "pagination/pageChanged", page: page - 1 })}
|
||||
>
|
||||
{t("Previous")}
|
||||
</Button>
|
||||
<span className="text-xs">{t("Page {page} · {total} total", { page, total })}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || page * PAGE_SIZE >= total}
|
||||
onClick={() => dispatch({ type: "pagination/pageChanged", page: page + 1 })}
|
||||
>
|
||||
{t("Next")}
|
||||
</Button>
|
||||
|
||||
@@ -5,6 +5,16 @@ import * as React from "react";
|
||||
import { LibraryIcon, PlusIcon, SaveIcon, Settings2Icon, Trash2Icon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
initialTaskTemplateControlsState,
|
||||
taskTemplateControlsReducer,
|
||||
} from "@/components/_state/task-template-controls.reducer";
|
||||
import {
|
||||
initialTaskTemplateManagerState,
|
||||
type TemplateDraft,
|
||||
type TemplateSeed,
|
||||
taskTemplateManagerReducer,
|
||||
} from "@/components/_state/task-template-manager.reducer";
|
||||
import { AssetInterceptRulesEditor } from "@/components/asset-intercept-rules-editor";
|
||||
import {
|
||||
AlertDialog,
|
||||
@@ -34,20 +44,9 @@ import { Spinner } from "@/components/ui/spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { AssetInterceptRuleInput, TaskCategory, TaskTemplate } from "@/lib/types";
|
||||
import type { AssetInterceptRuleInput, TaskTemplate } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface TemplateDraft {
|
||||
name: string;
|
||||
description: string;
|
||||
goal: string;
|
||||
categoryID: number | null;
|
||||
interceptRules: AssetInterceptRuleInput[];
|
||||
}
|
||||
|
||||
// TemplateSeed holds the initial values carried over from the creation form when using "Save as template".
|
||||
type TemplateSeed = Pick<TemplateDraft, "description" | "goal" | "categoryID" | "interceptRules">;
|
||||
|
||||
interface TaskTemplateManagerProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
@@ -58,24 +57,6 @@ interface TaskTemplateManagerProps {
|
||||
onDeleted: (id: number) => void;
|
||||
}
|
||||
|
||||
const emptyDraft = (): TemplateDraft => ({
|
||||
name: "",
|
||||
description: "",
|
||||
goal: "",
|
||||
categoryID: null,
|
||||
interceptRules: [],
|
||||
});
|
||||
|
||||
function templateDraft(template: TaskTemplate): TemplateDraft {
|
||||
return {
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
goal: template.goal,
|
||||
categoryID: template.category_id ?? null,
|
||||
interceptRules: template.intercept_rules ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function TaskTemplateManager({
|
||||
open,
|
||||
onOpenChange,
|
||||
@@ -85,60 +66,40 @@ function TaskTemplateManager({
|
||||
onUpdated,
|
||||
onDeleted,
|
||||
}: TaskTemplateManagerProps) {
|
||||
const [selectedID, setSelectedID] = React.useState<number | null>(null);
|
||||
const [draft, setDraft] = React.useState<TemplateDraft>(emptyDraft);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [deleteOpen, setDeleteOpen] = React.useState(false);
|
||||
const [deleting, setDeleting] = React.useState(false);
|
||||
const [categories, setCategories] = React.useState<TaskCategory[]>([]);
|
||||
const [state, dispatch] = React.useReducer(taskTemplateManagerReducer, initialTaskTemplateManagerState);
|
||||
const { selectedID, draft } = state.editor;
|
||||
const { categories, deleteOpen } = state;
|
||||
const saving = state.requests.save.pending;
|
||||
const deleting = state.requests.delete.pending;
|
||||
const wasOpen = React.useRef(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
api
|
||||
.taskCategories()
|
||||
.then(setCategories)
|
||||
.catch(() => setCategories([]));
|
||||
.then((loaded) => dispatch({ type: "categoriesLoaded", categories: loaded }))
|
||||
.catch(() => dispatch({ type: "categoriesLoaded", categories: [] }));
|
||||
}, [open]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open && !wasOpen.current) {
|
||||
if (seed) {
|
||||
setSelectedID(null);
|
||||
setDraft({
|
||||
name: "",
|
||||
description: seed.description,
|
||||
goal: seed.goal,
|
||||
categoryID: seed.categoryID,
|
||||
interceptRules: seed.interceptRules,
|
||||
});
|
||||
} else if (templates[0]) {
|
||||
setSelectedID(templates[0].id);
|
||||
setDraft(templateDraft(templates[0]));
|
||||
} else {
|
||||
setSelectedID(null);
|
||||
setDraft(emptyDraft());
|
||||
}
|
||||
}
|
||||
if (open && !wasOpen.current) dispatch({ type: "managerOpened", seed, templates });
|
||||
wasOpen.current = open;
|
||||
}, [open, seed, templates]);
|
||||
|
||||
const selectTemplate = (template: TaskTemplate) => {
|
||||
setSelectedID(template.id);
|
||||
setDraft(templateDraft(template));
|
||||
dispatch({ type: "templateSelected", template });
|
||||
};
|
||||
|
||||
const startNew = () => {
|
||||
setSelectedID(null);
|
||||
setDraft(emptyDraft());
|
||||
dispatch({ type: "newStarted" });
|
||||
};
|
||||
|
||||
const updateDraft = (field: "name" | "description" | "goal", value: string) => {
|
||||
setDraft((current) => ({ ...current, [field]: value }));
|
||||
dispatch({ type: "draftChanged", patch: { [field]: value } });
|
||||
};
|
||||
|
||||
const patchDraft = (patch: Partial<TemplateDraft>) => {
|
||||
setDraft((current) => ({ ...current, ...patch }));
|
||||
dispatch({ type: "draftChanged", patch });
|
||||
};
|
||||
|
||||
async function save() {
|
||||
@@ -155,47 +116,39 @@ function TaskTemplateManager({
|
||||
toast.error(t("Fill in the template name, description, and goal"));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
dispatch({ type: "request/started", key: "save" });
|
||||
try {
|
||||
if (selectedID == null) {
|
||||
const created = await api.createTaskTemplate(input);
|
||||
onCreated(created);
|
||||
setSelectedID(created.id);
|
||||
setDraft(templateDraft(created));
|
||||
dispatch({ type: "templateCreated", template: created });
|
||||
toast.success(t("Template created"));
|
||||
} else {
|
||||
const updated = await api.updateTaskTemplate(selectedID, input);
|
||||
onUpdated(updated);
|
||||
setDraft(templateDraft(updated));
|
||||
dispatch({ type: "templateUpdated", template: updated });
|
||||
toast.success(t("Template updated"));
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(t("Save failed: {error}", { error: (error as Error).message }));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
dispatch({ type: "request/finished", key: "save" });
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
if (selectedID == null) return;
|
||||
const deletedID = selectedID;
|
||||
setDeleting(true);
|
||||
dispatch({ type: "request/started", key: "delete" });
|
||||
try {
|
||||
await api.deleteTaskTemplate(deletedID);
|
||||
onDeleted(deletedID);
|
||||
const next = templates.find((template) => template.id !== deletedID);
|
||||
if (next) {
|
||||
setSelectedID(next.id);
|
||||
setDraft(templateDraft(next));
|
||||
} else {
|
||||
startNew();
|
||||
}
|
||||
setDeleteOpen(false);
|
||||
dispatch({ type: "templateDeleted", id: deletedID, templates });
|
||||
toast.success(t("Template deleted"));
|
||||
} catch (error) {
|
||||
toast.error(t("Delete failed: {error}", { error: (error as Error).message }));
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
dispatch({ type: "request/finished", key: "delete" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,7 +265,12 @@ function TaskTemplateManager({
|
||||
</div>
|
||||
<SheetFooter className="border-t px-6 py-4 sm:flex-row sm:items-center">
|
||||
{selectedID != null && (
|
||||
<Button type="button" variant="destructive" className="sm:mr-auto" onClick={() => setDeleteOpen(true)}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
className="sm:mr-auto"
|
||||
onClick={() => dispatch({ type: "deleteOpenChanged", open: true })}
|
||||
>
|
||||
<Trash2Icon data-icon="inline-start" />
|
||||
{t("Delete template")}
|
||||
</Button>
|
||||
@@ -327,7 +285,10 @@ function TaskTemplateManager({
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialog
|
||||
open={deleteOpen}
|
||||
onOpenChange={(nextOpen) => dispatch({ type: "deleteOpenChanged", open: nextOpen })}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
@@ -378,22 +339,20 @@ export function TaskTemplateControls({
|
||||
onApply,
|
||||
portalContainer,
|
||||
}: TaskTemplateControlsProps) {
|
||||
const [templates, setTemplates] = React.useState<TaskTemplate[]>([]);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [templateInputValue, setTemplateInputValue] = React.useState("");
|
||||
const [pendingTemplate, setPendingTemplate] = React.useState<TaskTemplate | null>(null);
|
||||
const [managerOpen, setManagerOpen] = React.useState(false);
|
||||
const [managerSeed, setManagerSeed] = React.useState<TemplateSeed | null>(null);
|
||||
const [state, dispatch] = React.useReducer(taskTemplateControlsReducer, initialTaskTemplateControlsState);
|
||||
const { items: templates, loading } = state.templates;
|
||||
const { inputValue: templateInputValue, pending: pendingTemplate } = state.picker;
|
||||
const { open: managerOpen, seed: managerSeed } = state.manager;
|
||||
|
||||
const loadTemplates = React.useCallback(async () => {
|
||||
setLoading(true);
|
||||
dispatch({ type: "list/loadStarted" });
|
||||
try {
|
||||
setTemplates(await api.taskTemplates());
|
||||
dispatch({ type: "list/loaded", items: await api.taskTemplates() });
|
||||
} catch (error) {
|
||||
setTemplates([]);
|
||||
dispatch({ type: "list/loaded", items: [] });
|
||||
toast.error(t("Failed to load templates: {error}", { error: (error as Error).message }));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
dispatch({ type: "list/loadFinished" });
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -407,42 +366,41 @@ export function TaskTemplateControls({
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
setTemplateInputValue(selectedTemplate?.name ?? "");
|
||||
dispatch({ type: "inputValueChanged", value: selectedTemplate?.name ?? "" });
|
||||
}, [selectedTemplate]);
|
||||
|
||||
const applyTemplate = (template: TaskTemplate) => {
|
||||
onApply(template);
|
||||
onSelectedTemplateIDChange(template.id);
|
||||
setPendingTemplate(null);
|
||||
dispatch({ type: "confirmClosed" });
|
||||
};
|
||||
|
||||
const chooseTemplate = (template: TaskTemplate | null) => {
|
||||
if (!template) {
|
||||
setTemplateInputValue("");
|
||||
dispatch({ type: "inputValueChanged", value: "" });
|
||||
onSelectedTemplateIDChange(null);
|
||||
return;
|
||||
}
|
||||
setTemplateInputValue(template.name);
|
||||
dispatch({ type: "inputValueChanged", value: template.name });
|
||||
const hasContent = description.trim() !== "" || goal.trim() !== "";
|
||||
const changesContent = description !== template.description || goal !== template.goal;
|
||||
if (hasContent && changesContent) {
|
||||
setPendingTemplate(template);
|
||||
dispatch({ type: "confirmRequested", template });
|
||||
return;
|
||||
}
|
||||
applyTemplate(template);
|
||||
};
|
||||
|
||||
const openManager = (seed: TemplateSeed | null) => {
|
||||
setManagerSeed(seed);
|
||||
setManagerOpen(true);
|
||||
dispatch({ type: "managerOpened", seed });
|
||||
};
|
||||
|
||||
const upsertTemplate = (template: TaskTemplate) => {
|
||||
setTemplates((current) => [template, ...current.filter((item) => item.id !== template.id)]);
|
||||
dispatch({ type: "templateUpserted", template });
|
||||
};
|
||||
|
||||
const deleteTemplate = (id: number) => {
|
||||
setTemplates((current) => current.filter((template) => template.id !== id));
|
||||
dispatch({ type: "templateRemoved", id });
|
||||
if (selectedTemplateID === id) onSelectedTemplateIDChange(null);
|
||||
};
|
||||
|
||||
@@ -483,7 +441,7 @@ export function TaskTemplateControls({
|
||||
itemToStringLabel={(template) => template.name}
|
||||
itemToStringValue={(template) => String(template.id)}
|
||||
inputValue={templateInputValue}
|
||||
onInputValueChange={(value) => setTemplateInputValue(value)}
|
||||
onInputValueChange={(value) => dispatch({ type: "inputValueChanged", value })}
|
||||
value={selectedTemplate}
|
||||
onValueChange={chooseTemplate}
|
||||
>
|
||||
@@ -522,8 +480,7 @@ export function TaskTemplateControls({
|
||||
open={pendingTemplate != null}
|
||||
onOpenChange={(open) => {
|
||||
if (open) return;
|
||||
setPendingTemplate(null);
|
||||
setTemplateInputValue(selectedTemplate?.name ?? "");
|
||||
dispatch({ type: "confirmDismissed", inputValue: selectedTemplate?.name ?? "" });
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
@@ -544,7 +501,7 @@ export function TaskTemplateControls({
|
||||
|
||||
<TaskTemplateManager
|
||||
open={managerOpen}
|
||||
onOpenChange={setManagerOpen}
|
||||
onOpenChange={(open) => dispatch({ type: "managerOpenChanged", open })}
|
||||
templates={templates}
|
||||
seed={managerSeed}
|
||||
onCreated={upsertTemplate}
|
||||
|
||||
@@ -4,6 +4,11 @@ import * as React from "react";
|
||||
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
createTrafficPickerState,
|
||||
PAGE_SIZE,
|
||||
trafficPickerReducer,
|
||||
} from "@/components/_state/traffic-picker-dialog.reducer";
|
||||
import { CapturedTrafficViewer } from "@/components/traffic-evidence-viewer";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -23,7 +28,7 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectVa
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { FindingTrafficBinding, TrafficResp } from "@/lib/types";
|
||||
import type { FindingTrafficBinding } from "@/lib/types";
|
||||
|
||||
const METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
|
||||
|
||||
@@ -40,32 +45,26 @@ export function TrafficPickerDialog({
|
||||
onClose: () => void;
|
||||
onBound: () => void;
|
||||
}) {
|
||||
const [host, setHost] = React.useState("");
|
||||
const [method, setMethod] = React.useState("all");
|
||||
const [query, setQuery] = React.useState("");
|
||||
const [page, setPage] = React.useState(0);
|
||||
const [data, setData] = React.useState<TrafficResp | null>(null);
|
||||
const [selected, setSelected] = React.useState<Set<string>>(() => new Set());
|
||||
const [preview, setPreview] = React.useState<string | null>(null);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const [error, setError] = React.useState("");
|
||||
const [state, dispatch] = React.useReducer(trafficPickerReducer, undefined, createTrafficPickerState);
|
||||
const { filters, selected, preview, saving: busy, error } = state;
|
||||
const { host, method, query } = filters;
|
||||
const { page } = state.pagination;
|
||||
const { items: rows, total, loading } = state.list;
|
||||
const alreadyBound = new Set(bound.map((b) => b.snapshot.source_traffic_id));
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
dispatch({ type: "list/loadStarted" });
|
||||
const timer = setTimeout(() => {
|
||||
api
|
||||
.traffic(page, 25, host, method === "all" ? "" : method, query)
|
||||
.traffic(page, PAGE_SIZE, host, method === "all" ? "" : method, query)
|
||||
.then((d) => {
|
||||
if (active) setData(d);
|
||||
if (active) dispatch({ type: "list/loaded", items: d.exchanges ?? [], total: d.total ?? 0 });
|
||||
})
|
||||
.catch((e: Error) => {
|
||||
if (active) setError(e.message);
|
||||
if (active) dispatch({ type: "loadFailed", error: e.message });
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setLoading(false);
|
||||
if (active) dispatch({ type: "list/loadFinished" });
|
||||
});
|
||||
}, 250);
|
||||
return () => {
|
||||
@@ -74,19 +73,12 @@ export function TrafficPickerDialog({
|
||||
};
|
||||
}, [page, host, method, query]);
|
||||
|
||||
const rows = data?.exchanges ?? [];
|
||||
const selectable = rows.filter((e) => !alreadyBound.has(e.id));
|
||||
function toggle(id: string, checked: boolean) {
|
||||
setSelected((previous) => {
|
||||
const next = new Set(previous);
|
||||
if (checked) next.add(id);
|
||||
else next.delete(id);
|
||||
return next;
|
||||
});
|
||||
dispatch({ type: "selectionChanged", ids: [id], checked });
|
||||
}
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
dispatch({ type: "saveStarted" });
|
||||
try {
|
||||
await api.bindFindingTraffic(
|
||||
findingId,
|
||||
@@ -97,9 +89,9 @@ export function TrafficPickerDialog({
|
||||
onBound();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
dispatch({ type: "saveFailed", error: (e as Error).message });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
dispatch({ type: "saveFinished" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,21 +119,12 @@ export function TrafficPickerDialog({
|
||||
id="evidence-host"
|
||||
value={host}
|
||||
placeholder={t("Domain or IP")}
|
||||
onChange={(e) => {
|
||||
setHost(e.target.value);
|
||||
setPage(0);
|
||||
}}
|
||||
onChange={(e) => dispatch({ type: "filtersChanged", patch: { host: e.target.value } })}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="evidence-method">{t("Request method")}</FieldLabel>
|
||||
<Select
|
||||
value={method}
|
||||
onValueChange={(v) => {
|
||||
setMethod(v);
|
||||
setPage(0);
|
||||
}}
|
||||
>
|
||||
<Select value={method} onValueChange={(v) => dispatch({ type: "filtersChanged", patch: { method: v } })}>
|
||||
<SelectTrigger id="evidence-method">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -163,10 +146,7 @@ export function TrafficPickerDialog({
|
||||
id="evidence-query"
|
||||
value={query}
|
||||
placeholder={t("URL / body keyword")}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setPage(0);
|
||||
}}
|
||||
onChange={(e) => dispatch({ type: "filtersChanged", patch: { query: e.target.value } })}
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
@@ -185,13 +165,10 @@ export function TrafficPickerDialog({
|
||||
disabled={loading || busy || selectable.length === 0}
|
||||
checked={selectable.length > 0 && selectable.every((e) => selected.has(e.id))}
|
||||
onCheckedChange={(checked) =>
|
||||
setSelected((previous) => {
|
||||
const next = new Set(previous);
|
||||
for (const e of selectable) {
|
||||
if (checked === true) next.add(e.id);
|
||||
else next.delete(e.id);
|
||||
}
|
||||
return next;
|
||||
dispatch({
|
||||
type: "selectionChanged",
|
||||
ids: selectable.map((e) => e.id),
|
||||
checked: checked === true,
|
||||
})
|
||||
}
|
||||
/>
|
||||
@@ -224,7 +201,7 @@ export function TrafficPickerDialog({
|
||||
</TableCell>
|
||||
<TableCell>{e.status}</TableCell>
|
||||
<TableCell>
|
||||
<Button variant="ghost" size="sm" onClick={() => setPreview(e.id)}>
|
||||
<Button variant="ghost" size="sm" onClick={() => dispatch({ type: "previewChanged", id: e.id })}>
|
||||
{t("Preview")}
|
||||
</Button>
|
||||
</TableCell>
|
||||
@@ -242,14 +219,14 @@ export function TrafficPickerDialog({
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="text-sm">
|
||||
{t("{selected} selected · {total} total", { selected: selected.size, total: data?.total ?? 0 })}
|
||||
{t("{selected} selected · {total} total", { selected: selected.size, total })}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || page === 0}
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
onClick={() => dispatch({ type: "pagination/pageChanged", page: page - 1 })}
|
||||
>
|
||||
{t("Previous")}
|
||||
</Button>
|
||||
@@ -257,8 +234,8 @@ export function TrafficPickerDialog({
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || (page + 1) * 25 >= (data?.total ?? 0)}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
disabled={loading || (page + 1) * PAGE_SIZE >= total}
|
||||
onClick={() => dispatch({ type: "pagination/pageChanged", page: page + 1 })}
|
||||
>
|
||||
{t("Next")}
|
||||
</Button>
|
||||
@@ -274,7 +251,7 @@ export function TrafficPickerDialog({
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<CapturedTrafficViewer id={preview} onClose={() => setPreview(null)} />
|
||||
<CapturedTrafficViewer id={preview} onClose={() => dispatch({ type: "previewChanged", id: null })} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,11 @@ import {
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
type InterceptDecision,
|
||||
initialInterceptCardState,
|
||||
interceptCardReducer,
|
||||
} from "@/components/_state/intercept-card.reducer";
|
||||
import { ApprovalDetail } from "@/components/approval-records";
|
||||
import { Markdown } from "@/components/markdown";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -27,7 +32,7 @@ import { intlLocale, t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import { reportsBashExit127 } from "@/lib/bash-exit-status";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import type { Activity, InterceptPending } from "@/lib/types";
|
||||
import type { Activity } from "@/lib/types";
|
||||
|
||||
// ---- per-agent lane color (planner + work#1/#2/#3 …) ---------------------------
|
||||
const workerColors = ["bg-sky-600", "bg-violet-600", "bg-teal-600", "bg-pink-600", "bg-orange-600"];
|
||||
@@ -193,13 +198,12 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
return m ? m[1] : step.summary;
|
||||
}, [step.summary]);
|
||||
|
||||
const [detail, setDetail] = React.useState<Record<string, unknown> | null>(null);
|
||||
const [decided, setDecided] = React.useState<"allowed" | "denied" | "timeout" | null>(null);
|
||||
const [deciding, setDeciding] = React.useState(false);
|
||||
const [expanded, setExpanded] = React.useState(false);
|
||||
const [pending, setPending] = React.useState<InterceptPending | null>(null);
|
||||
const [statusError, setStatusError] = React.useState("");
|
||||
const [retry, setRetry] = React.useState(0);
|
||||
const [state, dispatch] = React.useReducer(interceptCardReducer, initialInterceptCardState);
|
||||
const { detail, expanded } = state;
|
||||
const { pending, decided, statusError, retry } = state.approval;
|
||||
const deciding = state.requests.decide.pending;
|
||||
// Stable: ApprovalDetail reloads whenever onResolved changes.
|
||||
const onResolved = React.useCallback((decision: InterceptDecision) => dispatch({ type: "decided", decision }), []);
|
||||
|
||||
// Load persisted detail JSON + check the real current status from the backend
|
||||
// so that a page refresh shows the already-decided state instead of re-offering buttons.
|
||||
@@ -209,7 +213,7 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
.then((raw) => {
|
||||
if (!live || !raw) return;
|
||||
try {
|
||||
setDetail(JSON.parse(raw));
|
||||
dispatch({ type: "detailLoaded", detail: JSON.parse(raw) });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
@@ -229,13 +233,14 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
api
|
||||
.interceptGetOne(pendingId)
|
||||
.then((p) => {
|
||||
if (!live) return;
|
||||
setPending(p);
|
||||
setStatusError("");
|
||||
if (p.status !== "pending") setDecided(p.status as "allowed" | "denied" | "timeout");
|
||||
if (live) dispatch({ type: "approvalLoaded", pending: p });
|
||||
})
|
||||
.catch((error) => {
|
||||
if (live) setStatusError((error as Error).message || t("Failed to load approval details"));
|
||||
if (live)
|
||||
dispatch({
|
||||
type: "approvalLoadFailed",
|
||||
error: (error as Error).message || t("Failed to load approval details"),
|
||||
});
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
@@ -244,15 +249,15 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
|
||||
async function decide(decision: "allowed" | "denied") {
|
||||
if (step.inherited || !pendingId || deciding) return;
|
||||
setDeciding(true);
|
||||
dispatch({ type: "request/started", key: "decide" });
|
||||
try {
|
||||
await api.interceptDecide(pendingId, decision);
|
||||
setDecided(decision);
|
||||
dispatch({ type: "decided", decision });
|
||||
toast.success(decision === "allowed" ? t("Execution allowed") : t("Execution denied"));
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setDeciding(false);
|
||||
dispatch({ type: "request/finished", key: "decide" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,7 +324,11 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
)}
|
||||
</div>
|
||||
{pendingId ? (
|
||||
<Collapsible open={expanded} onOpenChange={setExpanded} className="mt-2 min-w-0">
|
||||
<Collapsible
|
||||
open={expanded}
|
||||
onOpenChange={(open) => dispatch({ type: "expandedChanged", expanded: open })}
|
||||
className="mt-2 min-w-0"
|
||||
>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -339,12 +348,12 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
revision={retry}
|
||||
readOnly={Boolean(step.inherited)}
|
||||
defaultExpanded
|
||||
onResolved={setDecided}
|
||||
onResolved={onResolved}
|
||||
/>
|
||||
) : statusError ? (
|
||||
<div className="flex flex-wrap items-center gap-2 p-3" role="alert">
|
||||
<span>{statusError}</span>
|
||||
<Button variant="outline" size="sm" onClick={() => setRetry((value) => value + 1)}>
|
||||
<Button variant="outline" size="sm" onClick={() => dispatch({ type: "retryRequested" })}>
|
||||
{t("Retry details")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1763,6 +1763,9 @@
|
||||
"Proxy {proxy}": "Proxy {proxy}",
|
||||
"Proxy address": "Adresse du proxy",
|
||||
"Proxy or upstream error": "Erreur du proxy ou de l'amont",
|
||||
"Proxy test failed: {error}": "Échec du test du proxy : {error}",
|
||||
"Proxy test succeeded · {latency} ms": "Test du proxy réussi · {latency} ms",
|
||||
"Proxy test succeeded · {latency} ms · egress IP {ip}": "Test du proxy réussi · {latency} ms · IP de sortie {ip}",
|
||||
"Proxy URL (empty = direct)": "URL du proxy (vide = direct)",
|
||||
"Purge all": "Tout purger",
|
||||
"Purge all traffic records?": "Purger tous les enregistrements de trafic ?",
|
||||
|
||||
@@ -1763,6 +1763,9 @@
|
||||
"Proxy {proxy}": "Proxy {proxy}",
|
||||
"Proxy address": "Endereço do proxy",
|
||||
"Proxy or upstream error": "Erro de proxy ou upstream",
|
||||
"Proxy test failed: {error}": "Falha no teste do proxy: {error}",
|
||||
"Proxy test succeeded · {latency} ms": "Teste do proxy bem-sucedido · {latency} ms",
|
||||
"Proxy test succeeded · {latency} ms · egress IP {ip}": "Teste do proxy bem-sucedido · {latency} ms · IP de saída {ip}",
|
||||
"Proxy URL (empty = direct)": "URL do proxy (vazio = direto)",
|
||||
"Purge all": "Purgar tudo",
|
||||
"Purge all traffic records?": "Purgar todos os registros de tráfego?",
|
||||
|
||||
@@ -1763,6 +1763,9 @@
|
||||
"Proxy {proxy}": "Proxy {proxy}",
|
||||
"Proxy address": "Proxy adresi",
|
||||
"Proxy or upstream error": "Proxy veya üst sunucu hatası",
|
||||
"Proxy test failed: {error}": "Proxy testi başarısız: {error}",
|
||||
"Proxy test succeeded · {latency} ms": "Proxy testi başarılı · {latency} ms",
|
||||
"Proxy test succeeded · {latency} ms · egress IP {ip}": "Proxy testi başarılı · {latency} ms · çıkış IP'si {ip}",
|
||||
"Proxy URL (empty = direct)": "Proxy URL'si (boş = doğrudan)",
|
||||
"Purge all": "Tümünü temizle",
|
||||
"Purge all traffic records?": "Tüm trafik kayıtları temizlensin mi?",
|
||||
|
||||
@@ -1763,6 +1763,9 @@
|
||||
"Proxy {proxy}": "Proxy {proxy}",
|
||||
"Proxy address": "Địa chỉ proxy",
|
||||
"Proxy or upstream error": "Lỗi proxy hoặc upstream",
|
||||
"Proxy test failed: {error}": "Kiểm tra proxy thất bại: {error}",
|
||||
"Proxy test succeeded · {latency} ms": "Kiểm tra proxy thành công · {latency} ms",
|
||||
"Proxy test succeeded · {latency} ms · egress IP {ip}": "Kiểm tra proxy thành công · {latency} ms · IP đầu ra {ip}",
|
||||
"Proxy URL (empty = direct)": "URL proxy (để trống = trực tiếp)",
|
||||
"Purge all": "Xóa sạch tất cả",
|
||||
"Purge all traffic records?": "Xóa sạch mọi bản ghi lưu lượng?",
|
||||
|
||||
@@ -1763,6 +1763,9 @@
|
||||
"Proxy {proxy}": "代理 {proxy}",
|
||||
"Proxy address": "代理地址",
|
||||
"Proxy or upstream error": "代理或上游错误",
|
||||
"Proxy test failed: {error}": "代理测试失败:{error}",
|
||||
"Proxy test succeeded · {latency} ms": "代理测试成功 · {latency} ms",
|
||||
"Proxy test succeeded · {latency} ms · egress IP {ip}": "代理测试成功 · {latency} ms · 出口 IP {ip}",
|
||||
"Proxy URL (empty = direct)": "代理 URL(空=直连)",
|
||||
"Purge all": "清空全部",
|
||||
"Purge all traffic records?": "清空全部流量记录?",
|
||||
|
||||
@@ -1082,6 +1082,11 @@ export const api = {
|
||||
tavily_search_api_key?: string;
|
||||
keenable_search_api_key?: string;
|
||||
}) => post<{ ok: boolean; error?: string; count?: number; backend?: string }>(`/settings/web-search/test`, patch),
|
||||
// Fetch a public endpoint through the given (or, when masked, the saved) global proxy. Saves nothing.
|
||||
testGlobalProxy: (global_proxy: string) =>
|
||||
post<{ ok: boolean; error?: string; latency_ms?: number; ip?: string }>(`/settings/global-proxy/test`, {
|
||||
global_proxy,
|
||||
}),
|
||||
|
||||
// ---- Vulnerability IM push ----
|
||||
// Channels are multi-instance resources (several bots of the same kind, each with its own
|
||||
|
||||
@@ -2329,6 +2329,7 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
if (path === "/settings" && m === "GET") return D.settings;
|
||||
if (path === "/settings" && m === "PUT") return { ...D.settings, ...b };
|
||||
if (path === "/settings/web-search/test") return { ok: true, count: 5, backend: D.settings.web_search_backend };
|
||||
if (path === "/settings/global-proxy/test") return { ok: true, latency_ms: 120, ip: "203.0.113.7" };
|
||||
if (path === "/settings/python/detect") return { python_interpreter: "/usr/bin/python3" };
|
||||
if (path === "/chat")
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user