gateway, settings: an unreadable settings.json keeps the allow list read last, or lets in only this computer, never every address

Follow-up to 7a9490638. AllowIPs read settings.Load().AllowIPs, and Load
returns the defaults when settings.json can't be read or doesn't parse with
no good backup, so for those requests the allow list read as empty and
every address was let in (fail-open). A failed read is unknown, never
empty (LESSONS.md).

- settings: LoadChecked() returns Load's settings and an error when the
  file is there but can't be read, or doesn't parse with no last good
  generation, the same cases Save already refuses. No file, or an empty
  one, is not an error. Load is unchanged and now goes through the same
  reader.
- gateway: the Settings list is read with LoadChecked. On an unknown read
  the list read last in this process stays in force; with none read yet,
  only loopback and this computer's own addresses pass, and the 403 says
  settings.json in <dir> couldn't be read. Logged once until a read
  succeeds. MAGPIE_ALLOW_IPS is unaffected. AllowIPs returns the list in
  force (the last one read on an unknown read).
- gui: POST /api/settings and POST /api/settings/allowips read with
  LoadChecked and refuse on an unknown read. settings.Save already
  refused to write over such a file, so this didn't write an empty list
  before either; the handlers now refuse before building on defaults.
- docs: reference.md and gateway-routing.md say so.

Run (darwin, sandbox HOME/XDG via the tests' own setup, private GOCACHE):
- gofmt -l on the changed packages: empty.
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...: clean.
- go test -count=1 ./internal/settings ./internal/gui ./internal/gateway: ok.
- Broken by hand: allowList reading settings.Load() with no error makes
  TestAllowListUnreadableSettings fail (garbled after a read: 203.0.113.9
  got 200, want 403; never read: remote got 200, want 403 saying
  settings.json). LoadChecked never erroring on a parse failure makes
  TestLoadChecked fail ("garbled with no backup read as good") and the
  gateway test fail at its precondition.
- TestAllowIPsUnreadableSettingsNotSavedOver passes on the old GUI code
  too (Save refused already); it guards that path.

Not run: the Windows box, Linux tests, the GUI Playwright suite (no
assets changed), the full go test ./... . Not covered: an empty
settings.json with no .bak still reads as no list, matching Save, so a
file truncated to zero bytes before any second save opens a freshly
started magpie.
This commit is contained in:
yetone
2026-10-12 23:38:50 +08:00
parent 9dd5917a41
commit 7d9382db23
8 changed files with 337 additions and 38 deletions
+4 -2
View File
@@ -599,8 +599,10 @@ enabled gateway key, and the refusal names the address it came from. This
computer is always let in. The address is the connection's own, never a
forwarding header, so behind a proxy or tunnel every client has the proxy's
address: limit them at the proxy. A mistyped entry in `MAGPIE_ALLOW_IPS`
lets nothing in rather than everything. `magpie web`'s page honours the same
list.
lets nothing in rather than everything. When settings.json can't be read, or
doesn't parse and has no good backup, the list read last stays in force; if
none was read since magpie started, only this computer is let in until the
file is repaired. `magpie web`'s page honours the same list.
**Usage → Overview → Gateway keys** groups calls by the client's key, never
the provider's credential. **Usage → Requests** offers the same filter;
+1 -1
View File
@@ -16,7 +16,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
| Part | Responsibility | Source |
| --- | --- | --- |
| Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-<agent>` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. | [`gateway.go`](../../internal/gateway/gateway.go) |
| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/<token>` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) |
| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/<token>` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) |
| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-<slug>`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) |
| Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) |
| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight` (`weightedFirst`). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/provider/routing.go`](../../internal/provider/routing.go) |
+74 -23
View File
@@ -34,20 +34,58 @@ const AllowIPsEnv = "MAGPIE_ALLOW_IPS"
// AllowIPs is the allow list in force, as written, and whether
// MAGPIE_ALLOW_IPS set it. Empty: no list, every address let in.
func AllowIPs() (list []string, fromEnv bool) {
list, fromEnv, _ = allowList()
return list, fromEnv
}
// lastAllow is the Settings list as last read whole. settings.json that
// can't be read, or doesn't parse with no last good generation, holds a
// list nobody knows: it is never taken for "no list" (every address let
// in). The one read last stays in force, and with none read since magpie
// started, only this computer is let in.
var lastAllow struct {
sync.Mutex
list []string
read bool // list was read from a good settings.json
warned bool // the unknown read is logged, once until one reads again
}
// allowList is AllowIPs, and unknown when settings.json couldn't be read
// and no list was read before it: then only this computer is let in.
func allowList() (list []string, fromEnv, unknown bool) {
if v := strings.TrimSpace(os.Getenv(AllowIPsEnv)); v != "" {
return settings.SplitAllowIPs(v), true
return settings.SplitAllowIPs(v), true, false
}
return settings.Load().AllowIPs, false
s, err := settings.LoadChecked()
lastAllow.Lock()
defer lastAllow.Unlock()
if err == nil {
lastAllow.list, lastAllow.read, lastAllow.warned = s.AllowIPs, true, false
return s.AllowIPs, false, false
}
if !lastAllow.warned {
lastAllow.warned = true
if lastAllow.read {
log.Printf("allow list: %v; the list read last stays in force", err)
} else {
log.Printf("allow list: %v; only this computer is let in until it reads", err)
}
}
return lastAllow.list, false, !lastAllow.read
}
var warnedAllow sync.Map
// allowPrefixes is the list in force, read; on says one is set. An entry
// that doesn't read (a mistyped MAGPIE_ALLOW_IPS) lets nothing in and is
// logged once: the list stays on, so a typo never opens magpie to every
// address.
func allowPrefixes() (ps []netip.Prefix, on bool) {
list, _ := AllowIPs()
// allowPrefixes is the list in force, read; on says one is set, or that
// settings.json holds one nobody knows (unknown), which lets in only this
// computer. An entry that doesn't read (a mistyped MAGPIE_ALLOW_IPS) lets
// nothing in and is logged once: the list stays on, so a typo never opens
// magpie to every address.
func allowPrefixes() (ps []netip.Prefix, on, unknown bool) {
list, _, unknown := allowList()
if unknown {
return nil, true, true
}
for _, e := range list {
p, err := settings.ParseAllowIP(e)
if err != nil {
@@ -58,7 +96,7 @@ func allowPrefixes() (ps []netip.Prefix, on bool) {
}
ps = append(ps, p)
}
return ps, len(list) > 0
return ps, len(list) > 0, false
}
// peerAddr is the address r's connection came from; false when
@@ -99,7 +137,12 @@ var ownAddr = func(a netip.Addr) bool {
// AllowedFrom: a request from a may reach magpie under the allow list —
// there is none, a is this computer's, or a is in it.
func AllowedFrom(a netip.Addr) bool {
ps, on := allowPrefixes()
ps, on, _ := allowPrefixes()
return allowedIn(ps, on, a)
}
// allowedIn is AllowedFrom for the list ps (on: there is one).
func allowedIn(ps []netip.Prefix, on bool, a netip.Addr) bool {
if !on || a.IsLoopback() {
return true
}
@@ -135,21 +178,29 @@ func KeepsOut(list []string, r *http.Request) (string, bool) {
return a.String(), !allowedListFrom(list, a)
}
// allowed: r may reach magpie under the allow list; it names r's address
// when it may not.
func allowed(r *http.Request) (string, bool) {
if _, on := allowPrefixes(); !on {
return "", true
// allowed: r may reach magpie under the allow list; when it may not, it
// names r's address and says why.
func allowed(r *http.Request) (addr, why string, ok bool) {
ps, on, unknown := allowPrefixes()
if !on {
return "", "", true
}
a, ok := peerAddr(r)
if !ok {
return r.RemoteAddr, false
return r.RemoteAddr, notAllowed(r.RemoteAddr, unknown), false
}
return a.String(), AllowedFrom(a)
if allowedIn(ps, on, a) {
return a.String(), "", true
}
return a.String(), notAllowed(a.String(), unknown), false
}
// notAllowed says why a request from addr was refused.
func notAllowed(addr string) string {
// notAllowed says why a request from addr was refused: it isn't on the
// list, or (unknown) settings.json, which holds the list, can't be read.
func notAllowed(addr string, unknown bool) string {
if unknown {
return "magpie couldn't read its settings.json in " + settings.Dir() + ", which holds its allow list, so it answers only this computer until it can, and this request came from " + addr + ": repair that file, or set the list in " + AllowIPsEnv
}
return "magpie answers only the addresses on its allow list (" + AllowIPsEnv + ", or Settings → Network and sharing → Allowed addresses), and this request came from " + addr + ": add it there to let it in"
}
@@ -157,9 +208,9 @@ func notAllowed(addr string) string {
// 403, before anything else looks at it: the page `magpie web` serves.
func AllowGuard(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if addr, ok := allowed(r); !ok {
if addr, why, ok := allowed(r); !ok {
log.Printf("refused %s %s from %s: not on the allow list", r.Method, r.URL.Path, addr)
http.Error(w, notAllowed(addr), http.StatusForbidden)
http.Error(w, why, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
@@ -169,11 +220,11 @@ func AllowGuard(next http.Handler) http.Handler {
// refuseNotAllowed answers a gateway request from an address the allow
// list leaves out, in the error shape agents show; true when it did.
func refuseNotAllowed(w http.ResponseWriter, r *http.Request) bool {
addr, ok := allowed(r)
addr, why, ok := allowed(r)
if ok {
return false
}
log.Printf("refused %s %s from %s: not on the allow list", r.Method, r.URL.Path, addr)
writeError(w, provider.Chat, http.StatusForbidden, notAllowed(addr))
writeError(w, provider.Chat, http.StatusForbidden, why)
return true
}
+83
View File
@@ -5,10 +5,12 @@ import (
"net"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/lastgood"
"github.com/yetone/magpie/internal/settings"
)
@@ -154,3 +156,84 @@ func TestKeepsOut(t *testing.T) {
t.Error("loopback")
}
}
// settings.json that can't be read, or doesn't parse with no last good
// generation, holds a list nobody knows, and is never taken for no list:
// the list read last stays in force, and with none read since magpie
// started, only this computer is let in, told why. No file is no list.
func TestAllowListUnreadableSettings(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "0.0.0.0:3499")
t.Setenv(AllowIPsEnv, "")
forgetAllow := func() {
lastAllow.Lock()
lastAllow.list, lastAllow.read, lastAllow.warned = nil, false, false
lastAllow.Unlock()
}
forgetAllow()
t.Cleanup(forgetAllow)
secret, err := access.Update("add-key", access.Change{Name: "Laptop"})
if err != nil {
t.Fatal(err)
}
h := lanGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
check := func(name, from string, want int, says string) {
t.Helper()
r := httptest.NewRequest("POST", "/v1/messages", nil)
r.RemoteAddr = from
r.Header.Set("x-api-key", secret)
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != want || !strings.Contains(w.Body.String(), says) {
t.Errorf("%s: from %s: %d %s, want %d saying %q", name, from, w.Code, w.Body.String(), want, says)
}
}
garble := func() {
t.Helper()
os.Remove(lastgood.Bak(settings.Path()))
if err := os.WriteFile(settings.Path(), []byte(`{"allowIPs": ["198.51.100.7"`), 0o600); err != nil {
t.Fatal(err)
}
if _, err := settings.LoadChecked(); err == nil {
t.Fatal("the garbled settings.json read as good")
}
}
os.Remove(settings.Path())
check("no file", "203.0.113.9:5000", 200, "")
s := settings.Load()
s.AllowIPs = []string{"198.51.100.7"}
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
check("read", "203.0.113.9:5000", 403, "allow list")
check("read", "198.51.100.7:5000", 200, "")
// read once, then garbled: the list read stays
garble()
check("garbled after a read", "203.0.113.9:5000", 403, "allow list")
check("garbled after a read", "198.51.100.7:5000", 200, "")
check("garbled after a read", "127.0.0.1:5000", 200, "")
if l, _ := AllowIPs(); len(l) != 1 || l[0] != "198.51.100.7" {
t.Errorf("AllowIPs with the file garbled = %v, want the list read last", l)
}
// garbled before any read: only this computer
forgetAllow()
check("garbled, never read", "203.0.113.9:5000", 403, "settings.json")
check("garbled, never read", "198.51.100.7:5000", 403, "settings.json")
check("garbled, never read", "[2001:db8::9]:5000", 403, "settings.json")
check("garbled, never read", "127.0.0.1:5000", 200, "")
check("garbled, never read", "[::1]:5000", 200, "")
// the environment's list is judged as before
t.Setenv(AllowIPsEnv, "203.0.113.0/24")
check("env", "203.0.113.9:5000", 200, "")
check("env", "198.51.100.7:5000", 403, AllowIPsEnv)
t.Setenv(AllowIPsEnv, "")
// gone: no list, every address
os.Remove(settings.Path())
check("removed", "203.0.113.9:5000", 200, "")
}
+36
View File
@@ -3,6 +3,7 @@ package gui
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
@@ -63,3 +64,38 @@ func TestAllowIPsSetting(t *testing.T) {
t.Fatalf("emptied: %d %v", rec.Code, settings.Load().AllowIPs)
}
}
// settings.json that doesn't parse, with no last good generation, holds an
// allow list nobody knows: neither the Settings page's save nor the allow
// list's own writes the defaults (no list, every address let in) over it.
func TestAllowIPsUnreadableSettingsNotSavedOver(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv(gateway.AllowIPsEnv, "")
srv := Handler(nil, nil)
if err := os.MkdirAll(settings.Dir(), 0o755); err != nil {
t.Fatal(err)
}
garbled := []byte(`{"allowIPs": ["203.0.113.7"`)
if err := os.WriteFile(settings.Path(), garbled, 0o600); err != nil {
t.Fatal(err)
}
for _, c := range []struct{ path, body string }{
{"/api/settings", `{"theme":"dark","lang":"en"}`},
{"/api/settings/allowips", `{"ips":["10.0.0.0/8"]}`},
} {
rec := httptest.NewRecorder()
r := httptest.NewRequest("POST", c.path, strings.NewReader(c.body))
r.RemoteAddr = "127.0.0.1:50000"
srv.ServeHTTP(rec, r)
if rec.Code == http.StatusOK || !strings.Contains(rec.Body.String(), "could not read settings") {
t.Errorf("%s: %d %s, want refused", c.path, rec.Code, rec.Body)
}
if b, _ := os.ReadFile(settings.Path()); string(b) != string(garbled) {
t.Fatalf("%s wrote over the unreadable settings: %q", c.path, b)
}
}
}
+13 -3
View File
@@ -1050,8 +1050,14 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
return
}
// the Settings page sends its own choices; how the agents are
// arranged is the Agents page's, and the window's size its own; both stay as they are
cur := settings.Load()
// arranged is the Agents page's, and the window's size its own; both stay as they are.
// Unreadable settings are never carried as the defaults (an empty
// allow list, every address let in): Save would refuse them too.
cur, err := settings.LoadChecked()
if err != nil {
fail(rw, err)
return
}
var fields map[string]json.RawMessage
_ = json.Unmarshal(body, &fields)
// Older pages do not send fonts. An explicit null restores the
@@ -1696,7 +1702,11 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
fail(rw, fmt.Errorf("that allow list would shut out %s, the address this page is open from: add it first", addr))
return
}
s := settings.Load()
s, err := settings.LoadChecked()
if err != nil {
fail(rw, err)
return
}
s.AllowIPs = list
if err := settings.Save(s); err != nil {
fail(rw, err)
+90
View File
@@ -0,0 +1,90 @@
package settings
import (
"os"
"path/filepath"
"reflect"
"runtime"
"testing"
"github.com/yetone/magpie/internal/lastgood"
)
// LoadChecked tells settings that aren't there (no error) from settings
// nobody knows (an error): a file that can't be read, or doesn't parse
// with no last good generation. Load still reads the defaults for those,
// and Save refuses the same files it reports.
func TestLoadChecked(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
lastgood.Reset()
t.Cleanup(lastgood.Reset)
if s, err := LoadChecked(); err != nil || len(s.AllowIPs) != 0 {
t.Fatalf("no file: %v %v", s.AllowIPs, err)
}
if err := os.MkdirAll(Dir(), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(Path(), []byte(" \n"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadChecked(); err != nil {
t.Fatalf("an empty file: %v", err)
}
os.Remove(Path())
for _, list := range [][]string{{"10.0.0.0/8"}, {"198.51.100.7"}} {
if err := Save(Settings{AllowIPs: list}); err != nil {
t.Fatal(err)
}
}
if s, err := LoadChecked(); err != nil || len(s.AllowIPs) != 1 || s.AllowIPs[0] != "198.51.100.7" {
t.Fatalf("a good file: %v %v", s.AllowIPs, err)
}
// garbled, with its last good generation: that is read, no error
garbled := []byte(`{"allowIPs": ["198.51.100.7"`)
if err := os.WriteFile(Path(), garbled, 0o600); err != nil {
t.Fatal(err)
}
if s, err := LoadChecked(); err != nil || len(s.AllowIPs) != 1 || s.AllowIPs[0] != "10.0.0.0/8" {
t.Fatalf("garbled with a backup: %v %v", s.AllowIPs, err)
}
// and without one: unknown, and never saved over
if err := os.Remove(lastgood.Bak(Path())); err != nil {
t.Fatal(err)
}
if s, err := LoadChecked(); err == nil {
t.Fatalf("garbled with no backup read as good: %v", s.AllowIPs)
}
if s := Load(); !reflect.DeepEqual(s, Settings{}.normal()) {
t.Fatalf("Load of a garbled file changed: %+v", s)
}
if err := Save(Load()); err == nil {
t.Fatal("Save wrote the defaults over a garbled settings.json")
}
if b, _ := os.ReadFile(Path()); string(b) != string(garbled) {
t.Fatalf("the garbled file was written over: %q", b)
}
// one that can't be read at all
if runtime.GOOS == "windows" {
return
}
if err := os.WriteFile(Path(), []byte(`{"allowIPs":["10.0.0.0/8"]}`), 0o200); err != nil {
t.Fatal(err)
}
if err := os.Chmod(Path(), 0o200); err != nil {
t.Fatal(err)
}
if _, err := os.ReadFile(Path()); err == nil {
t.Skip("this process can read a write-only file")
}
if _, err := LoadChecked(); err == nil {
t.Fatal("an unreadable file read as good")
}
}
+36 -9
View File
@@ -868,23 +868,50 @@ func Load() Settings {
return load()
}
// LoadChecked is Load, and an error when what the file holds is unknown:
// it is there but can't be read, or it doesn't parse and has no last good
// generation to read instead. The Settings returned then are Load's (the
// defaults), which a caller guarding something with a setting (the
// gateway's allow list) must not take for the user's own: a failed read
// is unknown, never empty. No file, or an empty one, is no settings and
// not an error — the cases Save writes over, where it refuses the others.
func LoadChecked() (Settings, error) {
fileMu.RLock()
defer fileMu.RUnlock()
return loadChecked()
}
// load is called with fileMu held for reading or writing.
func load() Settings {
s, _ := loadChecked()
return s
}
// loadChecked is LoadChecked, called with fileMu held.
func loadChecked() (Settings, error) {
var s Settings
// read again only once the file changed: a look at the agents asks for
// the settings for every model of every agent (hundreds of reads, a
// fifth of the Agents page's wait)
if b, err := filememo.Read("settings", Path(), func(b []byte) ([]byte, error) { return b, nil }); err == nil {
// parsed once: this runs for every model of every agent
if err := json.Unmarshal(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")), &s); err != nil {
// one left all zero by a crash (#1505) is its last good generation
if bak, err := lastgood.Fallback(Path(), b, validSettings); err == nil {
s = Settings{}
_ = json.Unmarshal(bytes.TrimPrefix(bak, []byte("\xef\xbb\xbf")), &s)
}
b, err := filememo.Read("settings", Path(), func(b []byte) ([]byte, error) { return b, nil })
if err != nil {
if os.IsNotExist(err) {
return s.normal(), nil
}
return s.normal(), fmt.Errorf("could not read settings at %s: %w", Path(), err)
}
// parsed once: this runs for every model of every agent
if perr := json.Unmarshal(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")), &s); perr != nil {
// one left all zero by a crash (#1505) is its last good generation
bak, ferr := lastgood.Fallback(Path(), b, validSettings)
if ferr == nil {
s = Settings{}
_ = json.Unmarshal(bytes.TrimPrefix(bak, []byte("\xef\xbb\xbf")), &s)
} else if len(bytes.TrimSpace(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")))) != 0 {
err = fmt.Errorf("could not read settings at %s: %w", Path(), perr)
}
}
return s.normal()
return s.normal(), err
}
// validSettings is settings.json's contents read as Settings.