gateway: the management API leaves other keys that manage magpie alone

727e23637 added /v1/magpie/admin/ and left admin-key out of it so that "a
key can't give another more than it was given". But rotate-key was served
on any key: a key allowed to manage magpie from this computer only
(Admin local) could rotate a key allowed from anywhere (Admin any) and was
handed its new secret, or set one of its own choosing ("secret" in the
body). It then held a key that manages magpie from the network. It could
also turn off or remove that key, locking its owner out.

- internal/gui/admin.go adminMayChangeKey: a POST /gateway-keys/{action}
  naming another key that has Admin is 403. The caller's own key, keys
  without Admin and add-key go on as before. A gateway-keys file that
  can't be read is refused (unknown), not let through.
- docs/subsystems/gateway-routing.md says so.

Run (mote, at 2bcbae35e + this change):
- go test -count=1 -timeout 45m ./internal/gui/: ok 138.6s
- go vet ./internal/gui/ darwin, GOOS=linux -tags nogui, GOOS=windows: clean
- gofmt -l clean
Broken by hand: with the check skipped, TestAdminAPILeavesOtherManagingKeys
is red. A local key rotated the any key and got its secret
(sk-magpie-key-…), set "chosen-by-the-caller-1234" as its secret, turned it
off and removed it.
Not tried: a real gateway run over HTTP. The test drives serveAdmin with
the caller's identity in the context, as the gateway's admin() passes it on.
This commit is contained in:
yetone
2026-11-13 03:49:41 +08:00
parent 2bcbae35ef
commit 648cd3fdbb
3 changed files with 113 additions and 1 deletions
+4 -1
View File
@@ -1473,7 +1473,10 @@ Host must be `ownHost` (a rebound page's GET has no Origin), and from
anywhere else the key must be `AdminAny`. `Key.Admin` is set only by
`magpie gateway-key admin` and the app, never through the API, and
`adminOf` drops it for a read-only, Browser, issued, expiring or default
key. The route is in `readOnlyRefused`, so a read-only key never reaches
key. A key action through the API on another key that has `Admin`
(`adminMayChangeKey`) is 403: rotating it would hand the caller its new
secret, or set one the caller chose, so a `local` key would get an `any`
one or take over a peer's. The caller's own key is its to change. The route is in `readOnlyRefused`, so a read-only key never reaches
it. The handlers are built with no window, so a sign-in opens no browser.
Routing Groups and sign-in export are not in it yet (#6307).
+45
View File
@@ -1,12 +1,15 @@
package gui
import (
"bytes"
"encoding/json"
"io"
"net/http"
"slices"
"strings"
"sync"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
@@ -94,6 +97,9 @@ func adminAPI() http.Handler {
adminError(w, http.StatusNotFound, "this action is not in the management API")
return
}
if strings.HasPrefix(ar.pattern, "POST /gateway-keys/") && !adminMayChangeKey(w, r) {
return
}
to := r.URL.Path
if ar.to != "" {
to = strings.ReplaceAll(ar.to, "{action}", r.PathValue("action"))
@@ -126,6 +132,45 @@ func adminAPI() http.Handler {
return mux
}
// adminMayChangeKey refuses, with 403, a key action through the API on
// another key that may manage magpie. Rotating one hands the caller its
// new secret (or sets one the caller chose), so a key allowed from this
// computer only would become one allowed from anywhere, or take over a
// peer's; and turning one off or removing it locks its owner out. A key
// that manages magpie is changed by the command line and the app, as its
// Admin is set there (admin-key is left out above). The caller's own key
// stays its to change. The body is read and put back for the handler.
func adminMayChangeKey(w http.ResponseWriter, r *http.Request) bool {
body, err := io.ReadAll(r.Body)
if err != nil {
adminError(w, http.StatusBadRequest, err.Error())
return false
}
r.Body = io.NopCloser(bytes.NewReader(body))
var in struct {
Key string `json:"key"`
}
if json.Unmarshal(body, &in) != nil || in.Key == "" {
return true // add-key, or a body the handler refuses itself
}
if in.Key == access.Caller(r.Context()).KeyID {
return true
}
keys, err := access.List()
if err != nil {
// unknown: refused, not let through
adminError(w, http.StatusServiceUnavailable, "the gateway keys can't be read: "+err.Error())
return false
}
for _, k := range keys {
if k.ID == in.Key && k.Admin != "" {
adminError(w, http.StatusForbidden, "this key may manage magpie, so the management API doesn't change it: use `magpie gateway-key` or the app")
return false
}
}
return true
}
func adminError(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
+64
View File
@@ -125,3 +125,67 @@ func TestAdminRoutesEveryAPIRoute(t *testing.T) {
}
}
}
// A key allowed to manage magpie from this computer only can't rotate a
// key allowed from anywhere through the API (it would get that key's new
// secret, or set one of its own), nor turn off or remove another key that
// manages magpie. Its own key and keys that don't manage magpie it can.
func TestAdminAPILeavesOtherManagingKeys(t *testing.T) {
sandboxHome(t)
add := func(name string) string {
t.Helper()
if _, err := access.Update("add-key", access.Change{Name: name}); err != nil {
t.Fatal(err)
}
keys, _ := access.List()
return keys[len(keys)-1].ID
}
local, anyKey, plain := add("Local"), add("Any"), add("Plain")
if _, err := access.Update("admin-key", access.Change{Key: local, Admin: access.AdminLocal}); err != nil {
t.Fatal(err)
}
if _, err := access.Update("admin-key", access.Change{Key: anyKey, Admin: access.AdminAny}); err != nil {
t.Fatal(err)
}
as := func(action, body string) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest("POST", "/gateway-keys/"+action, strings.NewReader(body))
r = r.WithContext(access.WithIdentity(r.Context(), access.Identity{KeyID: local, Admin: access.AdminLocal}))
w := httptest.NewRecorder()
serveAdmin(w, r)
return w
}
for _, c := range []struct{ action, body string }{
{"rotate-key", `{"key":"` + anyKey + `"}`},
{"rotate-key", `{"key":"` + anyKey + `","secret":"chosen-by-the-caller-1234"}`},
{"off-key", `{"key":"` + anyKey + `"}`},
{"remove-key", `{"key":"` + anyKey + `"}`},
{"access-key", `{"key":"` + anyKey + `","readOnly":true}`},
} {
w := as(c.action, c.body)
if w.Code != http.StatusForbidden {
t.Errorf("%s %s: %d, want 403 (%s)", c.action, c.body, w.Code, w.Body)
}
if strings.Contains(w.Body.String(), `"secret":"magpie`) {
t.Errorf("%s told a secret: %s", c.action, w.Body)
}
}
keys, _ := access.List()
for _, k := range keys {
if k.ID == anyKey && (k.Off || k.Admin != access.AdminAny || k.ReadOnly) {
t.Errorf("the other managing key was changed: %+v", k)
}
}
if who, ok := access.Authenticate("chosen-by-the-caller-1234"); ok {
t.Errorf("the caller's chosen secret opens %q", who.KeyName)
}
for _, c := range []struct{ action, body string }{
{"rotate-key", `{"key":"` + local + `"}`},
{"rotate-key", `{"key":"` + plain + `"}`},
{"rename-key", `{"key":"` + plain + `","name":"Renamed"}`},
} {
if w := as(c.action, c.body); w.Code != 200 {
t.Errorf("%s %s: %d, want 200 (%s)", c.action, c.body, w.Code, w.Body)
}
}
}