diff --git a/internal/access/mcp.go b/internal/access/mcp.go index 4b8ae8e39..44df1bc7c 100644 --- a/internal/access/mcp.go +++ b/internal/access/mcp.go @@ -2,9 +2,10 @@ package access import ( "errors" - "regexp" "slices" "strings" + + "github.com/yetone/magpie/internal/capre" ) // A key's MCP list (Key.MCP, wakaka on Discord) holds it to some of the @@ -20,7 +21,7 @@ const NoMCP = "-" // mcpServerRe is a server's name as the Library takes one (library's // nameRe), and as magpie names its own servers. -var mcpServerRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`) +var mcpServerRe = capre.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]*$`, 64) // CleanMCP is a key's MCP list as it is kept: each entry trimmed and // checked, told apart in no other way than as written, a tool dropped diff --git a/internal/agent/openclaw.go b/internal/agent/openclaw.go index 932c1ba08..28483abd0 100644 --- a/internal/agent/openclaw.go +++ b/internal/agent/openclaw.go @@ -45,13 +45,13 @@ import ( "fmt" "os" "path/filepath" - "regexp" "slices" "strings" "github.com/tidwall/gjson" "github.com/tidwall/jsonc" + "github.com/yetone/magpie/internal/capre" "github.com/yetone/magpie/internal/edit" ) @@ -72,7 +72,7 @@ const ( ) // openClawProfile is a profile name OpenClaw takes (profile-utils.ts). -var openClawProfile = regexp.MustCompile(`(?i)^[a-z0-9][a-z0-9_-]{0,63}$`) +var openClawProfile = capre.MustCompile(`(?i)^[a-z0-9][a-z0-9_-]*$`, 64) // openClawHome is OpenClaw's ~: $OPENCLAW_HOME, a leading ~ in it the // system's home (resolveEffectiveHomeDir). diff --git a/internal/capre/capre.go b/internal/capre/capre.go new file mode 100644 index 000000000..f4915ba2a --- /dev/null +++ b/internal/capre/capre.go @@ -0,0 +1,30 @@ +// Package capre is a regular expression held to a length. +// +// Go's regexp unrolls a bounded repeat: [A-Za-z0-9.-]{0,254} is 254 +// copies of the class, 89kB of program kept from start to exit for +// one settings check. The same class with * is a few states, and the +// bound is a length check. A pattern here is whole-string (^…$), every +// character of it of the repeated classes, so the length is its count +// of characters. +package capre + +import ( + "regexp" + "unicode/utf8" +) + +type Regexp struct { + re *regexp.Regexp + max int +} + +// MustCompile is expr, unbounded, matching only a string of max +// characters at most. +func MustCompile(expr string, max int) *Regexp { + return &Regexp{regexp.MustCompile(expr), max} +} + +// MatchString is whether s, of max characters at most, matches. +func (r *Regexp) MatchString(s string) bool { + return (len(s) <= r.max || utf8.RuneCountInString(s) <= r.max) && r.re.MatchString(s) +} diff --git a/internal/capre/capre_test.go b/internal/capre/capre_test.go new file mode 100644 index 000000000..60e808e48 --- /dev/null +++ b/internal/capre/capre_test.go @@ -0,0 +1,62 @@ +package capre + +import ( + "regexp" + "runtime" + "strings" + "testing" +) + +// The bounded patterns magpie had, each beside what replaced it. +var pairs = []struct { + bounded, open string + max int +}{ + {`^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$`, `^[A-Za-z0-9][A-Za-z0-9.-]*$`, 255}, + {`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`, `^[A-Za-z0-9][A-Za-z0-9_-]*$`, 64}, + {`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, `^[A-Za-z0-9][A-Za-z0-9._-]*$`, 64}, + {`^[a-zA-Z0-9_-]{1,128}$`, `^[a-zA-Z0-9_-]+$`, 128}, + {`^[A-Za-z0-9._@:/ -]{1,80}$`, `^[A-Za-z0-9._@:/ -]+$`, 80}, + {`^[^\x00-\x1f\x7f]{0,100}$`, `^[^\x00-\x1f\x7f]*$`, 100}, + {`(?i)^[a-z0-9][a-z0-9_-]{0,63}$`, `(?i)^[a-z0-9][a-z0-9_-]*$`, 64}, + {`^[0-9A-Za-z_.-]{1,64}$`, `^[0-9A-Za-z_.-]{1,}$`, 64}, +} + +func TestCappedMatchesBounded(t *testing.T) { + var in []string + for _, unit := range []string{"a", "Z", "9", "-", ".", "_", " ", "é", "K", "ſ", "\x00", "\xff", "@", "日"} { + for _, n := range []int{0, 1, 2, 63, 64, 65, 79, 80, 81, 99, 100, 101, 127, 128, 129, 254, 255, 256, 300} { + in = append(in, strings.Repeat(unit, n), "a"+strings.Repeat(unit, n), strings.Repeat(unit, n)+"a") + } + } + for _, p := range pairs { + want, got := regexp.MustCompile(p.bounded), MustCompile(p.open, p.max) + for _, s := range in { + if w, g := want.MatchString(s), got.MatchString(s); w != g { + t.Errorf("%s on %d bytes of %q: %v, want %v", p.open, len(s), s[:min(len(s), 4)], g, w) + } + } + } +} + +// TestCappedIsSmall: the reason for the package. A program of the +// bounded class is tens of kB; held to a length it is a fraction of one. +func TestCappedIsSmall(t *testing.T) { + heap := func(f func() any) int64 { + var a, b runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&a) + v := f() + runtime.GC() + runtime.ReadMemStats(&b) + runtime.KeepAlive(v) + return max(0, int64(b.HeapAlloc)-int64(a.HeapAlloc)) + } + p := pairs[0] + bounded := heap(func() any { return regexp.MustCompile(p.bounded) }) + capped := heap(func() any { return MustCompile(p.open, p.max) }) + if capped*10 > bounded { + t.Fatalf("held to a length: %d bytes, bounded %d", capped, bounded) + } + t.Logf("held to a length: %d bytes, bounded %d", capped, bounded) +} diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 7d9d2746f..e260c0669 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -19,6 +19,7 @@ import ( "sync" "sync/atomic" "time" + "unicode/utf8" "github.com/tidwall/gjson" @@ -3099,7 +3100,24 @@ func callItemIDs(body []byte) []byte { // "Invalid 'input[1].id': 'rs_6aca2fc7533c979d5f0e4f7a:rs_01a125caa544754e9a3c70080100b009'. // Expected an ID that contains letters, numbers, underscores, or dashes, // but this value contained additional characters." -var itemIDRefusal = regexp.MustCompile(`(?s)Invalid 'input\[\d+\]\.id'.{0,1000}?Expected an ID that contains letters, numbers, underscores, or dashes`) +// It is the tail within 1000 characters of the head: the regexp +// .{0,1000}? it was unrolled to 88kB of program, held from start to exit. +func itemIDRefusal(b []byte) bool { + const tail = "Expected an ID that contains letters, numbers, underscores, or dashes" + for _, at := range itemIDRefusalHead.FindAllIndex(b, -1) { + rest, end := b[at[1]:], 0 + for n := 0; n < 1000 && end < len(rest); n++ { + _, w := utf8.DecodeRune(rest[end:]) + end += w + } + if bytes.Contains(rest[:min(len(rest), end+len(tail))], []byte(tail)) { + return true + } + } + return false +} + +var itemIDRefusalHead = regexp.MustCompile(`Invalid 'input\[\d+\]\.id'`) // itemIDsRefused is how unfit remembers a provider turning away, for // model, an input item id with another character in it (plainItemIDs). diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 5893a2294..0c19e3a60 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6756,7 +6756,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. continue } } - if len(fs) == 0 && len(ms) == 0 && proto == provider.Responses && itemIDRefusal.Match(b) { + if len(fs) == 0 && len(ms) == 0 && proto == provider.Responses && itemIDRefusal(b) { // and an input item's id with a character OpenAI's don't // have, which a relay in front of OpenAI turns away as it // does (echo_ts): asked once more with ids it takes, and so diff --git a/internal/gateway/item_id_refusal_test.go b/internal/gateway/item_id_refusal_test.go new file mode 100644 index 000000000..83059f53b --- /dev/null +++ b/internal/gateway/item_id_refusal_test.go @@ -0,0 +1,30 @@ +package gateway + +import ( + "regexp" + "strings" + "testing" +) + +// TestItemIDRefusalAsTheRegexp: the hand-made match finds what the +// regexp it replaced found, at the 1000-character edge too. +func TestItemIDRefusalAsTheRegexp(t *testing.T) { + was := regexp.MustCompile(`(?s)Invalid 'input\[\d+\]\.id'.{0,1000}?Expected an ID that contains letters, numbers, underscores, or dashes`) + const head, tail = "Invalid 'input[12].id'", "Expected an ID that contains letters, numbers, underscores, or dashes" + in := []string{ + `{"error":{"message":"Invalid 'input[1].id': 'rs_6aca2fc7533c979d5f0e4f7a:rs_01a1'.\nExpected an ID that contains letters, numbers, underscores, or dashes, but this value contained additional characters."}}`, + "", head, tail, tail + head, head + tail, "Invalid 'input[].id'" + tail, + head + strings.Repeat("x", 2000) + head + "." + tail, + head + "Expected an ID" + strings.Repeat(" ", 900) + tail, + } + for _, unit := range []string{"x", "é", "日", "\xff", "\n"} { + for _, n := range []int{998, 999, 1000, 1001, 1002} { + in = append(in, head+strings.Repeat(unit, n)+tail, head+strings.Repeat(unit, n)+tail[:20]) + } + } + for _, s := range in { + if w, g := was.MatchString(s), itemIDRefusal([]byte(s)); w != g { + t.Errorf("%d bytes: %v, want %v", len(s), g, w) + } + } +} diff --git a/internal/gateway/undeclared_tools.go b/internal/gateway/undeclared_tools.go index a3069e799..fa70fad82 100644 --- a/internal/gateway/undeclared_tools.go +++ b/internal/gateway/undeclared_tools.go @@ -5,6 +5,7 @@ import ( "encoding/json" "regexp" + "github.com/yetone/magpie/internal/capre" "github.com/yetone/magpie/internal/provider" ) @@ -35,7 +36,7 @@ const historyToolsRefused = "tools[].history" const stubToolDescription = "Called earlier in this conversation; not available now." // anthropicToolName is a name Anthropic takes for a tool. -var anthropicToolName = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,128}$`) +var anthropicToolName = capre.MustCompile(`^[a-zA-Z0-9_-]+$`, 128) // toolsMissing is an upstream refusing tool calls in a request with no // tools: Anthropic's "must define tools", Bedrock's "The toolConfig field diff --git a/internal/gui/trace.go b/internal/gui/trace.go index 3e42f0490..e9cde9033 100644 --- a/internal/gui/trace.go +++ b/internal/gui/trace.go @@ -4,13 +4,13 @@ import ( "encoding/json" "net/http" "net/url" - "regexp" "slices" "strconv" "strings" "sync" "time" + "github.com/yetone/magpie/internal/capre" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/sessions" @@ -346,10 +346,10 @@ func mainView(q url.Values) string { } // mainName is the id of a provider or an agent. -var mainName = regexp.MustCompile(`^[A-Za-z0-9._@:/ -]{1,80}$`) +var mainName = capre.MustCompile(`^[A-Za-z0-9._@:/ -]+$`, 80) // mainFind is a line of text to look for, as a search field holds one. -var mainFind = regexp.MustCompile(`^[^\x00-\x1f\x7f]{0,100}$`) +var mainFind = capre.MustCompile(`^[^\x00-\x1f\x7f]*$`, 100) // mainURL is the window's page for a view as mainView gives it, the // request's id kept as its own parameter (the panel's link to one request, diff --git a/internal/library/library.go b/internal/library/library.go index 6672e42ac..ebc5e342e 100644 --- a/internal/library/library.go +++ b/internal/library/library.go @@ -9,12 +9,12 @@ import ( "encoding/json" "fmt" "path/filepath" - "regexp" "slices" "sort" "strings" "sync" + "github.com/yetone/magpie/internal/capre" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/settings" ) @@ -276,7 +276,7 @@ func (l *Library) skill(name string) *Skill { // A name is what a server or a skill is called in every agent's file, and // a skill's folder: it has to be a bare key in TOML and a plain file name. -var nameRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`) +var nameRe = capre.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]*$`, 64) func checkName(kind, name string) error { if !nameRe.MatchString(name) { @@ -285,12 +285,13 @@ func checkName(kind, name string) error { return nil } -// agentRe is an agent's id: a name, or one in a WSL distro's -// (codex@wsl:Ubuntu-24.04). -var agentRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}(@wsl:[A-Za-z0-9][A-Za-z0-9._-]{0,63})?$`) +// An agent's id is a name, or one in a WSL distro's +// (codex@wsl:Ubuntu-24.04): distroRe is the distro's name. +var distroRe = capre.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`, 64) func checkAgent(id string) error { - if !agentRe.MatchString(id) { + name, distro, wsl := strings.Cut(id, "@wsl:") + if !nameRe.MatchString(name) || wsl && !distroRe.MatchString(distro) { return fmt.Errorf("agent %q: not an agent's id", id) } return nil diff --git a/internal/sessions/codex_provider.go b/internal/sessions/codex_provider.go index 7cc1a79cd..64e37c7c8 100644 --- a/internal/sessions/codex_provider.go +++ b/internal/sessions/codex_provider.go @@ -12,7 +12,6 @@ import ( "net/url" "os" "path/filepath" - "regexp" "strconv" "strings" "sync" @@ -23,6 +22,7 @@ import ( "github.com/tidwall/gjson" "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/capre" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/filelock" "github.com/yetone/magpie/internal/filememo" @@ -42,7 +42,7 @@ import ( // codexProviderRe is what a provider id may be: a key of config.toml's // [model_providers], or a built-in one. -var codexProviderRe = regexp.MustCompile(`^[0-9A-Za-z_.-]{1,64}$`) +var codexProviderRe = capre.MustCompile(`^[0-9A-Za-z_.-]+$`, 64) // CodexMove is one session moved to another provider. type CodexMove struct { diff --git a/internal/settings/settings.go b/internal/settings/settings.go index d1a4bc341..aa3f694a8 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -26,6 +26,7 @@ import ( "time" "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/capre" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/filememo" @@ -1308,7 +1309,7 @@ var DefaultTextSize = func() int { return 100 } -var validTerminalBundleID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$`) +var validTerminalBundleID = capre.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.-]*$`, 255) // providerID is how a provider's id is spelled: lower-case letters, digits // and dashes, as provider.Slug derives it (a custom provider's id is the