diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index b741810d3..90841b96d 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -1059,8 +1059,9 @@ the rule's key, named `repo@ref (run N)`, living no longer than the rule, so everything above about issued keys holds: bounded by its issuer, its spend counts against it, turning the issuer off stops both. -The route is the one exemption from `remoteKeyed` in `lanGuard` -(`oidcExchange`: that exact path, POST, no gateway key). It is answered +The route is one of two keyless exemptions from the key check in `lanGuard` +(`oidcExchange`: that exact path, POST, no gateway key); the other is a +magpie's proof, below. It is answered only while magpie is shared and past the allow list, and a refused token counts against `tooManyAuthFails` as a wrong key does. A read-only key is refused it. Covered by `TestOIDCTokenTradedForKey` @@ -1069,6 +1070,24 @@ refused it. Covered by `TestOIDCTokenTradedForKey` and `TestAddRefuses` ([`oidc_test.go`](../../internal/oidc/oidc_test.go)). Not tried: a real GitHub Actions run against a shared magpie. +`POST /v1/magpie/prove` (`provider.RemoteProvePath`, +[`remote_prove.go`](../../internal/gateway/remote_prove.go)) is how another +magpie looking for this one at a new address (providers-accounts, "A remote +magpie that moved") learns it holds that magpie's gateway key before +sending it: `{"nonce", "key_id"}` with `key_id` the key's sha256 in hex, +answered `{"proof"}`, HMAC-SHA256 under the key of the nonce and the +address the connection reached (`provider.RemoteProof`), or 404 when no +enabled key has that id (`access.ProveSecret`). It carries no key, so +`lanGuard` lets it by (`proveAsked`: that exact path, POST, no gateway key) +only while magpie is shared and past the allow list, the rebinding check +and the not-shared refusal still first; `corsGuard` still judges its +Origin, and the handler refuses anything from a browser (`fromBrowser`). An +unknown id from another machine counts against `tooManyAuthFails`. Only a +caller that already has the key's sha256 gets a proof, for a nonce and +address of its own choosing under a key it doesn't hold. Covered by +`TestRemoteProveAnswersOnlyTheKeysHolder` +([`remote_moved_test.go`](../../internal/gateway/remote_moved_test.go)). + ### The stats and management API Every route under `/v1/magpie/` answers a program on this computer, and diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 8055b45ff..276197a1a 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -61,7 +61,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold `priority` (`provider.CanFast` reads them with `RemoteTiers`; Ultrafast too where they hold `ultrafast`, `UltraOn`), and a fast pick of one goes on with `service_tier` `priority` on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's `speed`, has it turned into the tier the remote offers (`forwardTranslated`), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; `TestRemoteMagpieFastPick`, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | | Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' `magpie_via` ends with this magpie's own `Self` is kept, by provider id and the address it answered at, in `remote-self.json` (`noteSelf`; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (`SelfLeftOut` in `On`, `SwitchedOff`, `remoteMagpies`): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (`ThroughSelf` in `Resolve` and `ResolveRoute`), not passed through the gateway again. The Providers row says *This magpie* (greyed while left out) and its editor says why, with **Use it anyway** (`KeepSelf`, `provider/keepself`, `SetKeepSelf`), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. `KeepSelf` is this computer's own like `KeepLogin` (`Mirror`, `Restore`, blanked in davsync's `hashes`), since the other computer's copy points at this one, which is not itself (`TestRemoteMagpieThatIsThisOneIsLeftOut`, `TestRemoteSelfRecord`, `remote-self.test.cjs`). Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`remote_self.go`](../../internal/provider/remote_self.go) | -| A remote magpie that moved | Computer A's router hands it a new address now and then (luckymanjc on Discord), and B's Remote magpie, saved at the old one, reached nothing. When B can't connect to it at all (a dial error, `unconnected`), its list fetch (`fetch` in [`models.go`](../../internal/provider/models.go)) and the gateway's request (`forward` in [`gateway.go`](../../internal/gateway/gateway.go)) call `SeekMoved` ([`remote_moved.go`](../../internal/provider/remote_moved.go)): every address of the old one's /24 and of up to four of B's own private /24s is dialled at A's port (500ms each, 128 at once), and the first that lists `/v1/models` 200 for the provider's key and whose list this magpie didn't make (`magpie_via`) is saved as the provider's address and asked again. A name or a public address is never looked around, an address the user changed meanwhile stands, and a provider is looked for once a minute at most, callers at once sharing the look (`TestRemoteMagpieFoundMoved`, `TestRemoteMagpieNotFoundStays`, `TestRemoteMagpieMovedIsFound`). **Off for now:** the look sent the provider's gateway key to every address that took the connection, so anyone listening at that port on the network B is on got A's key and, answering 200, became the provider. `seekAt` looks nowhere (`TestRemoteMagpieKeyGoesToNoNeighbour`) until an address proves it holds the key before the key goes to it; tests look where `SeekHere` says. | +| A remote magpie that moved | Computer A's router hands it a new address now and then (luckymanjc on Discord), and B's Remote magpie, saved at the old one, reached nothing. When B can't connect to it at all (a dial error, `unconnected`), its list fetch (`fetch` in [`models.go`](../../internal/provider/models.go)) and the gateway's request (`forward` in [`gateway.go`](../../internal/gateway/gateway.go)) call `SeekMoved` ([`remote_moved.go`](../../internal/provider/remote_moved.go)): every address of the old one's /24 and of up to four of B's own private /24s is dialled at A's port (500ms each, 128 at once, `lanNeighbours`). Whatever takes the connection there may be anyone's (a café's network, A switched off), so it is sent neither the key nor the provider's headers until it proves it holds the key (`proves`): B POSTs a nonce of its own and `RemoteKeyID` (the key's sha256, hex) to `RemoteProvePath` (`/v1/magpie/prove`) with no key and no proxy, and checks with `hmac.Equal` that the answer is `RemoteProof`: HMAC-SHA256 under the key of the nonce and the address B dialled. A answers it ([`remote_prove.go`](../../internal/gateway/remote_prove.go)) for an enabled gateway key of that id (`access.ProveSecret`: constant-time compares over every key, then `Check`) at the address the connection reached it on (`http.LocalAddrContextKey`), so a host passing B's nonce on to A elsewhere hands back a proof for A's address, not its own; 404 for a key it hasn't or has turned off. Only an address that proved is asked `/v1/models` with the key, and the first that lists 200 and whose list this magpie didn't make (`magpie_via`) is saved as the provider's address and asked again. A magpie from before the route, one behind a port forward or NAT (it is reached at another address than its own), or one behind a proxy that needs the provider's headers, is not found, and the user types the new address. A name or a public address is never looked around, an address the user changed meanwhile stands, and a provider is looked for once a minute at most, callers at once sharing the look (`TestRemoteMagpieKeyGoesToNoNeighbour`: an impostor that lists 200 for anything, one with a proof under another key, one with a garbled proof and one relaying to the real magpie are sent no key or header and not saved, and the real one is; `TestRemoteProof`, `TestRemoteMagpieFoundMoved`, `TestRemoteMagpieNotFoundStays`, `TestRemoteMagpieMovedIsFound`, `TestRemoteProveAnswersOnlyTheKeysHolder`). | | A relay's Codex entries | A provider the user added by its address with a Responses URL may list its models in Codex's own shape (`slug`, `supported_reasoning_levels`, `shell_type`, `base_instructions`: `catalog.CodexEntry`), plainly or when asked with Codex's `client_version`, as sub2api does (ctopsc on Discord: GPT-6.1 Terra was handed models.dev's 922000 window where the relay said 272000). `fetchOne` keeps such a row whole (`catalog.Model.Codex`, with its window, max window and inputs read off it), and when the plain list has none it asks the same URL once more with `client_version` (`codexEntries`): only where the list is fetched (add, key change, Refresh), never per Codex poll. The answer only adds entries to models the plain list has; one that fails or can't be read keeps the last list's entries (failed read = unknown), one that answers plainly says there are none. `codexcat.listedEntry` hands Codex the relay's entry as given, `base_instructions` included, with magpie's slug, name, priority and " via magpie" description; the user's window, compaction, levels and image setting still win (levels keep the relay's descriptions). A saved list from before is enriched at its next Refresh. `TestCodexListedEntry`, `TestCodexListedEntryInPlainList`. | [`codex_entries.go`](../../internal/provider/codex_entries.go), [`live.go`](../../internal/catalog/live.go), [`codexcat.go`](../../internal/codexcat/codexcat.go) | | An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | | The maker's own price | A model priced at its maker (`MakerPrice`, a provider's `ListPrice` after its own catalog, `PricedName`; through `makerListPrice`) is priced at a models.dev provider that lists it as its own (`catalog.MakerPriced`): one whose entry's `canonical_model_id` names it as the maker, or whose id is the maker's with a region (`alibaba-cn`), never a plan's (`-plan`) and never at $0. A maker preset that is such an API is asked first, in preset order, then the other owners by id; only then the maker presets as before (`PricedBy`). A maker preset that resells another lab's model no longer prices it: Mistral's `deepseek-v4-1-flash-1017` at $0.30/$1.20 gave way to DeepSeek's $0.15/$0.60, and a lab that isn't a preset (Meta's `muse-spark`) is priced at all. So a subscription's model (Command Code's, bestony on Discord) is estimated at what its maker charges (`TestMakerPriceIsTheMakersOwn`). A model no maker lists (Kimi K2.5, GLM-5.2 Fast) stays unpriced; the user gives it a price or a same-as model. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | diff --git a/internal/access/access.go b/internal/access/access.go index 50d0e5a7e..4437c464d 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -626,6 +626,49 @@ func Authenticate(secret string) (Identity, bool) { return who, err == nil } +// ProveSecret is the enabled gateway key whose sha256 is id (hex), for a +// magpie's proof that it holds the key (provider.RemoteProvePath): one +// Authenticate takes, found by constant-time compares over every key, so +// which one matched, or whether any did, takes no different time. A key +// turned off, expired or whose issuer no longer lets it in, and a store +// that can't be read, have none. +func ProveSecret(id string) (string, bool) { + want, err := hex.DecodeString(id) + if err != nil || len(want) != sha256.Size { + return "", false + } + mu.Lock() + keys, err := load() + s := settings.Load() + mu.Unlock() + if err != nil { + return "", false + } + secrets := make([]string, 0, len(keys)+1) + for _, k := range keys { + secrets = append(secrets, k.Secret) + } + // the sharing key an older magpie kept in the settings alone, which + // Check takes while the store has none marked + if s.LANKey != "" { + secrets = append(secrets, s.LANKey) + } + found := "" + for _, secret := range secrets { + sum := sha256.Sum256([]byte(secret)) + if subtle.ConstantTimeCompare(sum[:], want) == 1 && secret != "" && found == "" { + found = secret + } + } + if found == "" { + return "", false + } + if _, err := Check(found); err != nil { + return "", false + } + return found, true +} + // On: the key with this id is one Authenticate takes, in the store and not // turned off, or the legacy sharing key not yet written there; false when // the store can't be read. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 33b3f1b33..f4280871f 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -988,6 +988,9 @@ func (s *Server) routes() *routeMux { // and one traded for an OIDC token, by a rule the user wrote // (oidc_keys.go) mux.HandleFunc("POST "+OIDCKeysPath, s.oidcIssueKey) + // a magpie's proof that it holds a gateway key, asked with no key by + // another magpie looking for it at a new address (remote_prove.go) + mux.HandleFunc("POST "+provider.RemoteProvePath, s.prove) mux.HandleFunc("GET "+KeyPagePath, s.keyPage) mux.HandleFunc("GET "+keyPageData, s.keyInfo) // the Claude Code processes the Claude subscription runs, for magpie diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index 6af6e719c..4bacd78e9 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -490,6 +490,13 @@ func lanGuard(next http.Handler) http.Handler { next.ServeHTTP(w, r) return } + // a magpie's proof that it holds a key is asked with none: the + // handler answers only a key's holder, refuses a browser, and + // counts an unknown key against tooManyAuthFails (remote_prove.go) + if remote && proveAsked(r) { + next.ServeHTTP(w, r) + return + } if remote || managedKey(r) { var ok bool r, ok = identifyCaller(w, r) diff --git a/internal/gateway/readonly.go b/internal/gateway/readonly.go index 79570980d..42a6c0b80 100644 --- a/internal/gateway/readonly.go +++ b/internal/gateway/readonly.go @@ -43,6 +43,8 @@ var readOnlyRoutes = map[string]bool{ "GET " + OwnMCPPath: true, "GET " + KeyPagePath: true, "GET " + keyPageData: true, + // a proof carries no key, and answers none (remote_prove.go) + "POST " + provider.RemoteProvePath: true, } // ReadOnlyCode is the error code a read-only key is refused a route with. diff --git a/internal/gateway/remote_moved_test.go b/internal/gateway/remote_moved_test.go index 24d78d14b..880965fe6 100644 --- a/internal/gateway/remote_moved_test.go +++ b/internal/gateway/remote_moved_test.go @@ -2,13 +2,18 @@ package gateway import ( "context" + "encoding/hex" + "encoding/json" "io" + "net" "net/http" "net/http/httptest" "strings" "testing" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" ) // A Remote magpie whose computer came back at another address @@ -25,11 +30,13 @@ func TestRemoteMagpieMovedIsFound(t *testing.T) { if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"sol"}, Chat: up.URL + "/v1"}); err != nil { t.Fatal(err) } + // the key B holds is one of A's gateway keys, which A proves it holds + _, secrets := newCaller(t, "B") h := New().Handler() remote := httptest.NewServer(h) t.Cleanup(remote.Close) at := strings.TrimPrefix(remote.URL, "http://") - id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: "secret", Chat: at}) + id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: secrets[0], Chat: at}) if err != nil { t.Fatal(err) } @@ -57,3 +64,71 @@ func TestRemoteMagpieMovedIsFound(t *testing.T) { t.Errorf("saved at %q, want %s/v1", office.Chat, remote.URL) } } + +// A magpie proves it holds a gateway key to another computer that asks +// with no key (provider.RemoteProvePath), while it is shared: the HMAC of +// the asker's nonce and the address it was reached at, under the key the +// id names. A key it hasn't, or has turned off, gets 404; a web page and +// any ask while it isn't shared get nothing; the key never goes back. +func TestRemoteProveAnswersOnlyTheKeysHolder(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + resetAuthThrottle() + t.Cleanup(resetAuthThrottle) + keys, secrets := newCaller(t, "B") + h := lanGuard(New().Handler()) + const nonce = "00112233445566778899aabbccddeeff" + here := &net.TCPAddr{IP: net.ParseIP("192.168.1.2"), Port: 3425} + ask := func(keyID string, hdr ...string) *httptest.ResponseRecorder { + body, _ := json.Marshal(map[string]string{"nonce": nonce, "key_id": keyID}) + r := httptest.NewRequest("POST", provider.RemoteProvePath, strings.NewReader(string(body))) + r = r.WithContext(context.WithValue(r.Context(), http.LocalAddrContextKey, net.Addr(here))) + r.RemoteAddr, r.Host = fromThere, "192.168.1.2:3425" + r.Header.Set("Content-Type", "application/json") + for i := 0; i+1 < len(hdr); i += 2 { + r.Header.Set(hdr[i], hdr[i+1]) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + w := ask(provider.RemoteKeyID(secrets[0])) + if w.Code != http.StatusOK { + t.Fatalf("the key's holder: %d %s", w.Code, w.Body) + } + if strings.Contains(w.Body.String(), secrets[0]) { + t.Fatal("the key went back") + } + var out struct { + Proof string `json:"proof"` + } + json.Unmarshal(w.Body.Bytes(), &out) + if want := hex.EncodeToString(provider.RemoteProof(secrets[0], nonce, "192.168.1.2:3425")); out.Proof != want { + t.Errorf("proof %q, want %q", out.Proof, want) + } + if w := ask(provider.RemoteKeyID("sk-magpie-key-not-here")); w.Code != http.StatusNotFound { + t.Errorf("a key it hasn't: %d %s", w.Code, w.Body) + } + for _, hdr := range [][]string{{"Origin", "http://192.168.1.2:3425"}, {"User-Agent", "Mozilla/5.0"}, {"Sec-Fetch-Mode", "cors"}} { + if w := ask(provider.RemoteKeyID(secrets[0]), hdr...); w.Code == http.StatusOK { + t.Errorf("a browser (%s): %d", hdr[0], w.Code) + } + } + if _, err := access.Update("off-key", access.Change{Key: keys[0].ID}); err != nil { + t.Fatal(err) + } + if w := ask(provider.RemoteKeyID(secrets[0])); w.Code != http.StatusNotFound { + t.Errorf("a key turned off: %d %s", w.Code, w.Body) + } + if _, err := access.Update("on-key", access.Change{Key: keys[0].ID}); err != nil { + t.Fatal(err) + } + s := settings.Load() + s.LAN = false + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if w := ask(provider.RemoteKeyID(secrets[0])); w.Code != http.StatusForbidden { + t.Errorf("not shared: %d %s", w.Code, w.Body) + } +} diff --git a/internal/gateway/remote_prove.go b/internal/gateway/remote_prove.go new file mode 100644 index 000000000..43f0d2ae2 --- /dev/null +++ b/internal/gateway/remote_prove.go @@ -0,0 +1,79 @@ +package gateway + +import ( + "encoding/hex" + "encoding/json" + "io" + "log" + "net" + "net/http" + "strconv" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// A magpie looking for its Remote magpie at a new address (provider's +// remote_moved.go) asks each address that takes the connection to prove, +// before anything keyed is sent there, that it holds the provider's +// gateway key: it POSTs a nonce of its own and the key's sha256 +// (provider.RemoteKeyID) to provider.RemoteProvePath, with no key. This +// gateway answers the HMAC of the nonce and the address it was reached at +// (provider.RemoteProof) under its enabled gateway key of that id, or 404 +// when it has none. +// +// The route carries no key, so lanGuard lets it through to here +// (proveAsked) the way it does a CI job's OIDC trade: from another +// machine only while magpie is shared, past the allow list. A web page is +// refused (fromBrowser): only a magpie asks this. An ask for a key this +// gateway doesn't have counts against the failed authentications another +// machine may make (tooManyAuthFails), as a wrong key does, and costs one +// sha256 per key. The answer tells a caller nothing it didn't know: only +// one that already has the key's sha256 gets a proof, and the proof is +// for a nonce and an address of the asker's choosing, under a key it +// doesn't have. + +// proveAsked: r is a magpie's ask for a proof, which carries no key. +func proveAsked(r *http.Request) bool { + return r.Method == http.MethodPost && r.URL.Path == provider.RemoteProvePath && r.URL.RawPath == "" && !managedKey(r) +} + +// isHex: s is hex of between least and most characters. +func isHex(s string, least, most int) bool { + if len(s) < least || len(s) > most { + return false + } + _, err := hex.DecodeString(s) + return err == nil +} + +func (s *Server) prove(w http.ResponseWriter, r *http.Request) { + if fromBrowser(r) { + log.Printf("refused %s %s from %s: a browser asked for a proof", r.Method, r.URL.Path, r.RemoteAddr) + writeError(w, provider.Chat, http.StatusForbidden, "only a magpie asks this") + return + } + var in struct { + Nonce string `json:"nonce"` + KeyID string `json:"key_id"` + } + b, _ := io.ReadAll(io.LimitReader(r.Body, 4<<10)) + if json.Unmarshal(b, &in) != nil || !isHex(in.Nonce, 32, 128) || !isHex(in.KeyID, 64, 64) { + writeError(w, provider.Chat, http.StatusBadRequest, `send {"nonce": hex, "key_id": hex sha256 of the key}`) + return + } + at, _ := r.Context().Value(http.LocalAddrContextKey).(net.Addr) + key, ok := access.ProveSecret(in.KeyID) + if !ok || at == nil { + if !local(r) { + if over, retry := tooManyAuthFails(); over { + w.Header().Set("Retry-After", strconv.Itoa(int(retry.Seconds())+1)) + writeError(w, provider.Chat, http.StatusTooManyRequests, "too many failed authentications; slow down") + return + } + } + writeError(w, provider.Chat, http.StatusNotFound, "no enabled gateway key here has that id") + return + } + writeJSON(w, http.StatusOK, map[string]string{"proof": hex.EncodeToString(provider.RemoteProof(key, in.Nonce, at.String()))}) +} diff --git a/internal/provider/remote_moved.go b/internal/provider/remote_moved.go index 3c71ce289..73b387bdc 100644 --- a/internal/provider/remote_moved.go +++ b/internal/provider/remote_moved.go @@ -6,12 +6,23 @@ package provider // one, reached nothing until the user typed the new one in. So when B // can't connect to it at all, B looks for it on the networks it shares // with it: every address of the old one's /24 and of each of B's own -// private IPv4 networks, at the port A served on. An address that takes -// the connection is A when it answers the model list 200 for the -// provider's own key: a gateway key is A's secret, and another magpie, -// or anything else, answers 401 or isn't a magpie at all. One whose list -// this magpie made (its magpie_via ends with catalog.Self, remote_self.go) -// is this magpie and is passed over. The address found is saved as the +// private IPv4 networks, at the port A served on. +// +// Whatever takes the connection there may be anyone's: on a café's or a +// hotel's network, or with A simply off, any host listening on that port +// would have been handed the provider's key in clear and, answering a +// list, become the provider, given the user's prompts and files. So the +// key, and the provider's own headers, go to no address that hasn't +// proved first that it holds the key (proves): B sends a nonce of its +// own and the key's id (sha256 of the key, RemoteKeyID) to +// RemoteProvePath, which needs no key, and only a magpie with an enabled +// gateway key of that id answers the HMAC of the nonce and the address +// it was reached at (RemoteProof) under the key. Another magpie, an older +// one without the route, and anything else answer nothing B can check, +// and are passed over without a keyed request. An address that proved +// is then asked its model list with the key; one whose list this magpie +// made (its magpie_via ends with catalog.Self, remote_self.go) is this +// magpie and is passed over. The address found is saved as the // provider's, as if the user had typed it, and the request or list that // failed is asked there. // @@ -20,10 +31,17 @@ package provider // looked for. A look is made at most once a minute for each provider. import ( + "bytes" "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/hex" "encoding/json" + "io" "log" "net" + "net/http" "net/url" "regexp" "strings" @@ -56,14 +74,10 @@ var seekMu sync.Mutex var seekLast = map[string]time.Time{} // seekAt is the addresses (host:port) a Remote magpie last at host:port -// may be at now, nearest first. Tests give their own. -// Nowhere, for now: a look sent the provider's gateway key to every -// address on the network that took a connection at the port, and saved -// the first that listed 200 for it, so anyone on a café's network -// listening there got the key, and became the provider by answering. -// lanNeighbours comes back once an address proves it holds the key -// before the key is sent to it. Tests look where they say (SeekHere). -var seekAt = func(host, port string) []string { return nil } +// may be at now, nearest first. Tests give their own. Whatever takes the +// connection at one is sent nothing keyed until it proves it holds the +// key (isRemote, proves). +var seekAt = lanNeighbours // SeekHere has every look made at ats alone, as if any look made before // were long ago, until restore: for the gateway's tests, whose Remote @@ -167,7 +181,7 @@ func seekMoved(ctx context.Context, id string) (*Provider, bool) { if ctx.Err() != nil { return nil, false } - if !isRemote(ctx, *p, u.Scheme+"://"+at) { + if !isRemote(ctx, *p, u.Scheme, at) { continue } q, err := Find(id) @@ -187,10 +201,14 @@ func seekMoved(ctx context.Context, id string) (*Provider, bool) { return nil, false } -// isRemote says the magpie at root is p's: it lists for p's key, and -// isn't this magpie. -func isRemote(ctx context.Context, p Provider, root string) bool { - p.Chat, p.Responses, p.Anthropic, p.Decide = root, "", "", "" +// isRemote says the magpie at at is p's: it proves it holds p's key, then +// lists for it, and isn't this magpie. The key goes out only after the +// proof. +func isRemote(ctx context.Context, p Provider, scheme, at string) bool { + if !proves(ctx, scheme, at, p.Key) { + return false + } + p.Chat, p.Responses, p.Anthropic, p.Decide = scheme+"://"+at, "", "", "" p.remoteMagpieEndpoints() b, err := remoteBody(ctx, p, "GET", "/v1/models", seekAnswer) if err != nil { @@ -213,6 +231,92 @@ func isRemote(ctx context.Context, p Provider, root string) bool { return true } +// RemoteProvePath is where a magpie proves, with no key sent to it, that +// it holds a gateway key: POST {"nonce": hex, "key_id": RemoteKeyID(key)} +// is answered {"proof": hex of RemoteProof(key, nonce, the address it was +// reached at)}, or 404 when no enabled gateway key there has that id +// (the gateway's remote_prove.go). +const RemoteProvePath = "/v1/magpie/prove" + +// RemoteKeyID is the id a proof names key by: its sha256, in hex. +func RemoteKeyID(key string) string { + sum := sha256.Sum256([]byte(key)) + return hex.EncodeToString(sum[:]) +} + +// RemoteProof is what a magpie holding key, reached at at (host:port), +// answers nonce with: HMAC-SHA256 under key of the nonce and the address. +// The address is in it so that a host passing B's nonce on to the real +// magpie elsewhere gets a proof for that magpie's address, not its own. +func RemoteProof(key, nonce, at string) []byte { + m := hmac.New(sha256.New, []byte(key)) + io.WriteString(m, "magpie-prove-v1\n"+nonce+"\n"+proofAt(at)) + return m.Sum(nil) +} + +// proofAt is at with its IP written one way (an IPv4 address mapped into +// IPv6 as plain IPv4), as both sides of a proof write it. +func proofAt(at string) string { + host, port, err := net.SplitHostPort(at) + if err != nil { + return at + } + if ip := net.ParseIP(host); ip != nil { + if v4 := ip.To4(); v4 != nil { + ip = v4 + } + host = ip.String() + } + return net.JoinHostPort(host, port) +} + +// proveClient asks for a proof straight at the address dialled, as +// dialable dialled it (no proxy), and follows no redirect. +var proveClient = func() *http.Client { + t := http.DefaultTransport.(*http.Transport).Clone() + t.Proxy = nil + return &http.Client{Transport: t, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} +}() + +// proves says the magpie at at holds key: it answered a nonce of ours with +// the proof only key's holder, reached at at, can make. Neither key nor +// any header of the provider's own goes with the ask. +func proves(ctx context.Context, scheme, at, key string) bool { + if key == "" { + return false + } + n := make([]byte, 32) + if _, err := rand.Read(n); err != nil { + return false + } + nonce := hex.EncodeToString(n) + body, _ := json.Marshal(map[string]string{"nonce": nonce, "key_id": RemoteKeyID(key)}) + ctx, cancel := context.WithTimeout(ctx, seekAnswer) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, scheme+"://"+at+RemoteProvePath, bytes.NewReader(body)) + if err != nil { + return false + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + res, err := proveClient.Do(req) + if err != nil { + return false + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return false + } + var out struct { + Proof string `json:"proof"` + } + if json.NewDecoder(io.LimitReader(res.Body, 4<<10)).Decode(&out) != nil { + return false + } + got, err := hex.DecodeString(out.Proof) + return err == nil && hmac.Equal(got, RemoteProof(key, nonce, at)) +} + // dialable is the addresses of ats that take a connection, in ats' order. func dialable(ctx context.Context, ats []string) []string { ok := make([]bool, len(ats)) diff --git a/internal/provider/remote_moved_test.go b/internal/provider/remote_moved_test.go index 9b80a5483..e81cbc19f 100644 --- a/internal/provider/remote_moved_test.go +++ b/internal/provider/remote_moved_test.go @@ -2,24 +2,34 @@ package provider import ( "context" + "crypto/hmac" + "encoding/hex" + "encoding/json" "io" + "net" "net/http" "net/http/httptest" "slices" "strings" + "sync" "sync/atomic" "testing" "github.com/yetone/magpie/internal/catalog" ) -// a magpie on 127.0.0.1 that lists for key alone, its list made by lister +// a magpie on 127.0.0.1 that proves it holds key and lists for key +// alone, its list made by lister func movedMagpie(t *testing.T, key, lister string, hits *atomic.Int32) string { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if hits != nil { hits.Add(1) } + if r.URL.Path == RemoteProvePath { + answerProof(w, r, key) + return + } if r.Header.Get("x-api-key") != key { w.WriteHeader(http.StatusUnauthorized) io.WriteString(w, `{"error":{"message":"send an enabled gateway key"}}`) @@ -32,6 +42,73 @@ func movedMagpie(t *testing.T, key, lister string, hits *atomic.Int32) string { return strings.TrimPrefix(srv.URL, "http://") } +// answerProof answers a proof's ask as a magpie holding key does, at the +// address the connection came to. +func answerProof(w http.ResponseWriter, r *http.Request, key string) { + var in struct { + Nonce string `json:"nonce"` + KeyID string `json:"key_id"` + } + if json.NewDecoder(r.Body).Decode(&in) != nil || in.KeyID != RemoteKeyID(key) { + http.NotFound(w, r) + return + } + at := r.Context().Value(http.LocalAddrContextKey).(net.Addr).String() + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{"proof": hex.EncodeToString(RemoteProof(key, in.Nonce, at))}) +} + +// heard is every request an impostor was sent, its headers as they came. +type heard struct { + mu sync.Mutex + reqs []*http.Request +} + +func (h *heard) all() []*http.Request { + h.mu.Lock() + defer h.mu.Unlock() + return slices.Clone(h.reqs) +} + +// impostor is anything on the network that takes the connection at the +// port and lists 200 for any request, key or none; its proof is what +// prove writes (none: no such route). +func impostor(t *testing.T, prove func(w http.ResponseWriter, r *http.Request)) (string, *heard) { + t.Helper() + got := &heard{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got.mu.Lock() + got.reqs = append(got.reqs, r.Clone(context.Background())) + got.mu.Unlock() + if r.URL.Path == RemoteProvePath && prove != nil { + prove(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"object":"list","data":[]}`) + })) + t.Cleanup(srv.Close) + return strings.TrimPrefix(srv.URL, "http://"), got +} + +// keyHeard: one of reqs carried key or the provider's own header anywhere +// in its headers or its address. +func keyHeard(reqs []*http.Request, key, header string) bool { + for _, r := range reqs { + if strings.Contains(r.URL.String(), key) || r.Header.Get(header) != "" { + return true + } + for _, vs := range r.Header { + for _, v := range vs { + if strings.Contains(v, key) { + return true + } + } + } + } + return false +} + // nobody listens on port 1 const movedAway = "127.0.0.1:1" @@ -154,16 +231,93 @@ func TestDialable(t *testing.T) { } } -// Nothing is looked for on this computer's networks: a look sends the -// provider's key to whatever takes the connection, so until an address -// proves it holds the key first, no address is given to it. +// Whatever takes the connection on the network B is on (a café's, a +// hotel's, or A switched off) is sent neither the provider's key nor its +// own headers before it proves it holds the key, and isn't saved: one +// that lists 200 for anything and has no proof, one whose proof is made +// under another key, and one that passes B's nonce on to the real magpie +// elsewhere and hands back that magpie's proof. Only the real magpie, +// which proves it, is then asked with the key, and saved. func TestRemoteMagpieKeyGoesToNoNeighbour(t *testing.T) { - seekMu.Lock() - look := seekAt - seekMu.Unlock() - for _, host := range []string{"192.168.77.20", "10.0.0.5", "172.16.3.4"} { - if got := look(host, "3425"); len(got) != 0 { - t.Errorf("%s: looked at %d addresses (%v ...), want none", host, len(got), got[0]) + isolate(t) + isolateFetchHome(t) + const key, header = "sk-magpie-key-secret-of-a", "X-Office-Proxy" + real := movedMagpie(t, key, "a", nil) + silent, silentHeard := impostor(t, nil) + // a proof made the right way under a key of its own + wrong, wrongHeard := impostor(t, func(w http.ResponseWriter, r *http.Request) { + var in struct { + Nonce string `json:"nonce"` + } + json.NewDecoder(r.Body).Decode(&in) + at := r.Context().Value(http.LocalAddrContextKey).(net.Addr).String() + io.WriteString(w, `{"proof":"`+hex.EncodeToString(RemoteProof("sk-magpie-key-a-guess", in.Nonce, at))+`"}`) + }) + garbled, garbledHeard := impostor(t, func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `{"proof":"`+strings.Repeat("ab", 32)+`"}`) + }) + // a relay: B's ask, nonce and key id as they came, put to the real + // magpie, and its answer handed back + relay, relayHeard := impostor(t, func(w http.ResponseWriter, r *http.Request) { + res, err := http.Post("http://"+real+RemoteProvePath, "application/json", r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer res.Body.Close() + w.WriteHeader(res.StatusCode) + io.Copy(w, res.Body) + }) + asked := seekHere(t, movedAway, silent, wrong, garbled, relay) + id, err := Add(Provider{ID: "office", Name: "Office", Preset: RemoteMagpiePreset, Key: key, Chat: movedAway, Headers: map[string]string{header: "office-proxy-token"}}) + if err != nil { + t.Fatal(err) + } + p, _ := Find(id) + if _, err := p.Fetch(context.Background()); err == nil { + t.Fatal("fetch answered with no magpie of the key about") + } + if asked.Load() != 1 { + t.Fatalf("looked %d times", asked.Load()) + } + for name, h := range map[string]*heard{"silent": silentHeard, "wrong": wrongHeard, "garbled": garbledHeard, "relay": relayHeard} { + reqs := h.all() + if len(reqs) == 0 { + t.Errorf("%s: asked nothing (the proof was never asked)", name) + } + if keyHeard(reqs, key, header) { + t.Errorf("%s: was sent the key or the provider's header", name) + } + for _, r := range reqs { + if r.URL.Path != RemoteProvePath { + t.Errorf("%s: asked %s %s before a proof", name, r.Method, r.URL.Path) + } + } + } + if q, _ := Find(id); q.Chat != "http://"+movedAway+"/v1" { + t.Errorf("saved at %q, want the old address", q.Chat) + } + + // the real magpie, after them all, proves it and is saved + seekHere(t, movedAway, silent, wrong, garbled, relay, real) + p, _ = Find(id) + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatalf("fetch: %v", err) + } + if q, _ := Find(id); q.Chat != "http://"+real+"/v1" { + t.Errorf("saved at %q, want %s", q.Chat, real) + } +} + +// The proof: only key's holder, reached at the address asked, makes it. +func TestRemoteProof(t *testing.T) { + a := RemoteProof("k1", "00ff", "10.0.0.5:3425") + if !hmac.Equal(a, RemoteProof("k1", "00ff", "[::ffff:10.0.0.5]:3425")) { + t.Error("an IPv4 address mapped into IPv6 is another address") + } + for _, b := range [][]byte{RemoteProof("k2", "00ff", "10.0.0.5:3425"), RemoteProof("k1", "00fe", "10.0.0.5:3425"), RemoteProof("k1", "00ff", "10.0.0.6:3425"), RemoteProof("k1", "00ff", "10.0.0.5:3426")} { + if hmac.Equal(a, b) { + t.Error("a proof for another key, nonce or address is the same") } } }