fe61503e6had a Remote magpie whose address didn't dial look for it on the old address's /24 and this computer's private /24s, and sent GET /v1/models, signed with the provider's gateway key (Authorization, x-api-key and the provider's own headers), to every address that took the connection at the port. On a café's or hotel's network, or with the other computer off, anything listening there got the key in clear and, by answering {"data":[]}, became the provider: the failed request and every later one went to it.18a9a2d88turned the look off. Now an address that takes the connection is first asked to prove it holds the key, with nothing keyed sent: - B POSTs {"nonce": 32 random bytes hex, "key_id": sha256(key) hex} to /v1/magpie/prove (provider.RemoteProvePath), no key, no provider headers, no proxy, no redirects (proves in remote_moved.go). - A (gateway's remote_prove.go) finds the enabled gateway key with that sha256 (access.ProveSecret: constant-time compares over every key, the legacy settings sharing key too, then Check, so an off, expired or orphaned issued key has none) and answers HMAC-SHA256(key, "magpie-prove-v1\n" nonce "\n" address), the address being the one the connection reached it at (http.LocalAddrContextKey); 404 when no key matches. A host that relays B's nonce to A elsewhere gets a proof for A's address, which B, checking against the address it dialled with hmac.Equal, refuses. - Only after that does isRemote ask /v1/models with the key, as before. - The route goes through lanGuard like OIDC's trade (proveAsked: POST, exact path, no gateway key): from another machine only while shared, past the allow list and rebinding check; corsGuard still judges its Origin, the handler refuses anything fromBrowser, and an unknown id from another machine counts against tooManyAuthFails. readOnlyRoutes lists it (it carries no key and answers none). seekAt is lanNeighbours again: the old /24 and this computer's own private /24s, both behind the proof. Not found, and so safe: a remote magpie from before this route (404), one not shared (403), one reached through a port forward, NAT or a Docker port (it sees another local address than the one dialled), and one behind a proxy that needs the provider's headers. Each fails as beforefe61503e6and the user types the new address. Tests (local httptest servers only): - TestRemoteMagpieKeyGoesToNoNeighbour, rewritten from 18a9a2d88's "no address looked at": four impostors that list 200 for anything (no proof route; a well-formed proof under another key; a garbled proof; one relaying B's ask to the real magpie and handing back its proof) are asked only the proof, never see the key or the provider's custom header, and aren't saved; then the real magpie, last in the list, is found and saved. - TestRemoteProof: another key, nonce, address or port is another proof; an IPv4-mapped IPv6 address is the same address. - TestRemoteProveAnswersOnlyTheKeysHolder (gateway): from another machine while shared, the key's holder answers the right HMAC and never the key; an unknown id and a key turned off get 404; Origin, a Mozilla User-Agent and Sec-Fetch-Mode are refused; not shared, 403. - TestRemoteMagpieMovedIsFound now uses a real gateway key on A. Run on mote at this tree (base18a9a2d88): - gofmt -l internal cmd: clean - go vet ./internal/provider ./internal/gateway ./internal/access (darwin, with and without -tags nogui), GOOS=windows go vet, GOOS=linux go vet -tags nogui: ok - go test -tags nogui -count=1 -timeout 45m ./internal/provider ./internal/gateway ./internal/access: provider ok (206s), access ok, gateway FAIL on TestUnroutedHeldReportSaved only ("(under way)"), the open #4300, a file this change doesn't touch; it passes alone with -count=3 on mote. Rebased onto2000ae439(its gateway.go change, the Antigravity format check in models(), sits beside this one's route line). Rerun on mote at the rebased head: gofmt clean; the same four vets ok; go test -tags nogui -count=1 -run 'RemoteMagpie|RemoteProof|RemoteProve|LANNeighbours| Dialable|ReadOnlyKeyEveryRoute|OIDCToken|Antigravity|KeyPage' over the three packages: ok. The full suite was not run again. Broken by hand, each red: - isRemote without the proves check: the impostor with no proof route is sent the key and the header, is saved, and the real magpie is never reached. - RemoteProof without the address: the relaying impostor passes, is sent the key and saved; TestRemoteProof red too. Not tried: a real look across two computers on a LAN (A on mote, B in WSL asfe61503e6did); a real Windows A; IPv6 link-local addresses (not looked at). Residual: a user-chosen weak gateway key (8+ characters) can be guessed offline by an impostor from its sha256; magpie's own keys are 24 random bytes. Push rejected once; rebased ontof4068ccc2(proc only, none of this change's files). Rerun on mote there: gofmt, the same vets and the -run tests above: ok.
135 lines
5.1 KiB
Go
135 lines
5.1 KiB
Go
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
|
|
// (luckymanjc on Discord: A's router gives it a new IP each boot): the
|
|
// request that finds no one at the old one is answered from the address
|
|
// that lists for the provider's key, and the provider is saved there.
|
|
func TestRemoteMagpieMovedIsFound(t *testing.T) {
|
|
fresh(t)
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"sol","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}`)
|
|
}))
|
|
t.Cleanup(up.Close)
|
|
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: secrets[0], Chat: at})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
office, err := provider.Find(id)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := office.Fetch(context.Background()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// A's old address now answers nobody (nothing listens on port 1)
|
|
office, _ = provider.Find(id)
|
|
office.Chat, office.Responses, office.Anthropic, office.Decide = "127.0.0.1:1", "", "", ""
|
|
if err := provider.Save(*office); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(provider.SeekHere([]string{"127.0.0.1:1", at}))
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"office/fake/sol","messages":[{"role":"user","content":"hi"}]}`)))
|
|
if rec.Code != 200 {
|
|
t.Fatalf("status %d: %s", rec.Code, rec.Body)
|
|
}
|
|
office, _ = provider.Find(id)
|
|
if office.Chat != remote.URL+"/v1" {
|
|
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)
|
|
}
|
|
}
|