Files
magpie/internal/oidc/oidc_test.go
T
yetone 5a56bc7d73 gateway: a CI job trades its OIDC token for a short-lived key (#4531)
xazaj on X asked for GitHub OIDC: a GitHub Actions job should get a
gateway key without a long-lived magpie key in the repository's secrets.

A rule (magpie gateway-key oidc add --key <id> --repo owner/name
[--ref …] [--environment …] [--claim k=v] [--ttl 1h] [--issuer URL]
[--audience a]; oidc list, oidc remove) names an issuer (GitHub Actions'
by default, any https issuer), an audience (magpie-<rule id> by default,
so a token asked for one rule opens no other, and the workflow needn't
know the gateway's address), claims (exact or path.Match globs) and the
gateway key the keys are issued under, which must be let issue. A GitHub
rule names the repository or its owner with no wildcard, or every
repository on GitHub could get in. No rule, no exchange.

POST /v1/magpie/keys/oidc with Authorization: Bearer <token> and an
optional {"ttl","models"} verifies the token (RS256 only, keys from the
issuer's discovery document's https jwks_uri, exp required, nbf/iat with
a minute's leeway, the rule's aud and claims, a jti traded once) and
issues a key through access.IssueKey under the rule's key, named
repo@ref (run N), living no longer than the rule. Everything issued keys
guarantee holds: bounded by the issuer's models and accounts, its spend
counted against the issuer, stopped when the issuer is turned off.

- A token is judged only against rules naming its iss, so it can't make
  magpie fetch from a URL of its choosing.
- Keys are cached an hour per issuer, read by one request at a time with
  no lock held across the fetch, asked again for an unknown kid at most
  every 10s, and kept while the issuer is down; with none ever read,
  nothing is let in.
- The route is lanGuard's one exemption from remoteKeyed (that exact
  path, POST, no gateway key): only while shared, past the allow list,
  and a refused token counts against tooManyAuthFails (429 past the
  burst). A read-only key is refused it.

The issue's open questions, decided: rules are generic from the start
(the GitHub repository rule applies to GitHub's issuer); rules are CLI
and file only for now (oidc-rules.json), no GUI.

Docs: docs/subsystems/gateway-routing.md (Trading an OIDC token for a
key, routes table) and site/public/docs remote in en, zh and ja, with
the workflow snippet.

Tests: TestOIDCTokenTradedForKey (no rule, a traded key that works on
chat with its TTL capped and its name, a model past the issuer, another
branch, no token, 51 bad tokens -> 429, issuer turned off, a token on a
model route, loopback, not shared -> 403); TestMatchEachCheck (14 bad
tokens, list aud, replay, the refusal naming the claims);
TestKeysCachedAndKept (8 concurrent tokens one fetch, rotation, a made-up
kid inside and past the gap, the issuer down 2h later, an unnamed issuer
never fetched); TestUnreadKeysLetNothingIn; TestAddRefuses;
TestGatewayKeyOIDCCLI; TestReadOnlyKeyEveryRoute with the new route.
A JWKS from an httptest TLS server, never the network.

Broken by hand, each red then restored: the signature check, the claims
match, the jti check, the exp check, the refetch gap, the GitHub scope
rule, the lanGuard exemption, the throttle and the TTL cap.

Run at this head (rebased on 6a7a690be), on mote: go test ./internal/oidc/...
./internal/cli (whole packages) and go test -run 'OIDC|ReadOnlyKeyEveryRoute|
KeysEndpoint|IssuedKey|AuthThrottle|Route' ./internal/gateway: ok; gofmt -l
clean. At the 13aa33eac base: go vet (darwin, GOOS=linux -tags nogui,
GOOS=windows): ok; node --test site/*.test.mjs: 63 pass.
Full suite (-tags nogui -timeout 45m ./...) on the Linux box at the
13aa33eac base, still running when this was pushed (mote had two other
sessions' suites at load 291); so far every package ok except
internal/agent's TestInstalledVersion, TestGrokInstalled,
TestCopilotFolderFromAnIDEPluginIsNotTheCLI and TestOmpDetectedWithPiDir,
the WSL box's fake-binary reds filed as #4033 and #3548. The rest of the
run goes on #4531.

Not tried: a real GitHub Actions run against a shared magpie; a
connection open when an exchanged key expires.
2026-11-01 05:39:02 +08:00

214 lines
8.4 KiB
Go

package oidc_test
import (
"context"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/oidc"
"github.com/yetone/magpie/internal/oidc/oidctest"
"github.com/yetone/magpie/internal/testenv"
)
func TestMain(m *testing.M) { testenv.Main(m) }
// issuerKey is a gateway key let issue keys, as a rule names.
func issuerKey(t *testing.T) string {
t.Helper()
if _, err := access.Update("add-key", access.Change{Name: "CI"}); err != nil {
t.Fatal(err)
}
keys, _ := access.List()
id := keys[len(keys)-1].ID
if _, err := access.Update("issuer-key", access.Change{Key: id, Issues: true}); err != nil {
t.Fatal(err)
}
return id
}
var jtis atomic.Int64
func claims(is *oidctest.Issuer, aud string, over map[string]any) map[string]any {
now := time.Now().Unix()
c := map[string]any{"iss": is.URL, "aud": aud, "sub": "repo:acme/app:ref:refs/heads/main",
"repository": "acme/app", "repository_owner": "acme", "ref": "refs/heads/main",
"run_id": "42", "iat": now, "nbf": now, "exp": now + 300, "jti": strconv.FormatInt(jtis.Add(1), 10)}
for k, v := range over {
if v == nil {
delete(c, k)
} else {
c[k] = v
}
}
return c
}
// A token from the rule's issuer, with its audience and every claim it
// names, matches; one that is off in any single way doesn't. Each case
// changes one thing from the one that matches.
func TestMatchEachCheck(t *testing.T) {
is := oidctest.New(t)
key := issuerKey(t)
r, err := oidc.Add(oidc.Rule{Key: key, Issuer: is.URL, Claims: map[string]string{"repository": "acme/app", "ref": "refs/heads/*"}})
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(r.Audience, "magpie-") || r.Lifetime() != oidc.DefaultTTL {
t.Fatalf("defaults: %+v", r)
}
ctx := context.Background()
good := is.Sign(t, "k1", claims(is, r.Audience, nil))
got, c, err := oidc.Match(ctx, good)
if err != nil || got.ID != r.ID || c.Str("run_id") != "42" {
t.Fatal(got, c, err)
}
if _, _, err := oidc.Match(ctx, good); err == nil || !strings.Contains(err.Error(), "already") {
t.Fatal("a token traded twice:", err)
}
stranger := is.AddKey(t, "spare")
now := time.Now().Unix()
for name, tok := range map[string]string{
"another repository": is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"repository": "evil/app"})),
"a tag, not a branch": is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"ref": "refs/tags/v1"})),
"no ref": is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"ref": nil})),
"another audience": is.Sign(t, "k1", claims(is, "magpie-other", nil)),
"no audience": is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"aud": nil})),
"expired": is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"exp": now - 120})),
"no expiry": is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"exp": nil})),
"not yet valid": is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"nbf": now + 600})),
"issued in the future": is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"iat": now + 600})),
"another issuer": is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"iss": "https://evil.example"})),
"signed by another key": is.Sign(t, "k1", claims(is, r.Audience, nil), stranger),
"an unknown key id": is.Sign(t, "nope", claims(is, r.Audience, nil), stranger),
"not a JWT": "abc.def",
"alg none": "eyJhbGciOiJub25lIn0." + strings.Split(good, ".")[1] + ".",
} {
if _, _, err := oidc.Match(ctx, tok); err == nil {
t.Errorf("%s matched", name)
}
}
// a list audience holding the rule's matches too
if _, _, err := oidc.Match(ctx, is.Sign(t, "k1", claims(is, "", map[string]any{"aud": []string{"x", r.Audience}}))); err != nil {
t.Fatal("a list audience:", err)
}
// the refusal says the claims, so a workflow's author sees which is off
_, _, err = oidc.Match(ctx, is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"repository": "evil/app"})))
if err == nil || !strings.Contains(err.Error(), `repository="evil/app"`) {
t.Fatal(err)
}
}
// Keys are read once, again for a key id they don't have at most once in
// ten seconds, and kept as last read while the issuer can't be reached; an
// issuer no rule names is never asked.
func TestKeysCachedAndKept(t *testing.T) {
is := oidctest.New(t)
key := issuerKey(t)
r, err := oidc.Add(oidc.Rule{Key: key, Issuer: is.URL, Claims: map[string]string{"repository": "acme/app"}})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
var wg sync.WaitGroup
for range 8 {
wg.Add(1)
go func() {
defer wg.Done()
if _, _, err := oidc.Match(ctx, is.Sign(t, "k1", claims(is, r.Audience, nil))); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
if n := is.Fetches.Load(); n != 1 {
t.Fatalf("keys read %d times for eight tokens", n)
}
// a rotated key is read for, once; a made-up one again only after a minute
is.AddKey(t, "k2")
clock := time.Now().Add(11 * time.Second)
oidc.Now = func() time.Time { return clock }
t.Cleanup(func() { oidc.Now = time.Now })
if _, _, err := oidc.Match(ctx, is.Sign(t, "k2", claims(is, r.Audience, nil))); err != nil {
t.Fatal("a rotated key:", err)
}
stray := is.AddKey(t, "k3")
clock = clock.Add(11 * time.Second)
for range 5 {
oidc.Match(ctx, is.Sign(t, "zz", claims(is, r.Audience, nil), stray))
}
if n := is.Fetches.Load(); n != 3 {
t.Fatalf("keys read %d times, want 3 (first, k2, one for zz)", n)
}
// the issuer down: the keys as last read still serve, past their hour
is.Down.Store(true)
clock = clock.Add(2 * time.Hour)
if _, _, err := oidc.Match(ctx, is.Sign(t, "k1", claims(is, r.Audience, map[string]any{"exp": clock.Unix() + 60, "iat": clock.Unix(), "nbf": clock.Unix()}))); err != nil {
t.Fatal("kept keys:", err)
}
// an issuer no rule names is never asked for keys
before := is.Fetches.Load()
is.Down.Store(false)
other := oidctest.New(t)
if _, _, err := oidc.Match(ctx, other.Sign(t, "k1", claims(other, r.Audience, nil))); err == nil {
t.Fatal("matched an issuer no rule names")
}
if other.Fetches.Load() != 0 || is.Fetches.Load() != before {
t.Fatal("asked an issuer no rule names for keys")
}
}
// An issuer that can't be read, with no keys read before, lets nothing in.
func TestUnreadKeysLetNothingIn(t *testing.T) {
is := oidctest.New(t)
is.Down.Store(true)
r, err := oidc.Add(oidc.Rule{Key: issuerKey(t), Issuer: is.URL, Claims: map[string]string{"repository": "acme/app"}})
if err != nil {
t.Fatal(err)
}
if _, _, err := oidc.Match(context.Background(), is.Sign(t, "k1", claims(is, r.Audience, nil))); err == nil || !strings.Contains(err.Error(), "can't be read") {
t.Fatal(err)
}
}
// A rule that would let in any repository's workflow on GitHub, a key not
// let issue keys, and a TTL out of bounds are refused.
func TestAddRefuses(t *testing.T) {
key := issuerKey(t)
if _, err := access.Update("add-key", access.Change{Name: "plain"}); err != nil {
t.Fatal(err)
}
keys, _ := access.List()
plain := keys[len(keys)-1].ID
for name, r := range map[string]oidc.Rule{
"GitHub, no repository": {Key: key, Claims: map[string]string{"ref": "refs/heads/main"}},
"GitHub, a wildcard owner": {Key: key, Claims: map[string]string{"repository_owner": "*"}},
"GitHub, a wildcard repo": {Key: key, Claims: map[string]string{"repository": "acme/*"}},
"no claims": {Key: key, Issuer: "https://idp.example"},
"http issuer": {Key: key, Issuer: "http://idp.example", Claims: map[string]string{"sub": "x"}},
"a key not let issue": {Key: plain, Claims: map[string]string{"repository": "acme/app"}},
"no such key": {Key: "nope", Claims: map[string]string{"repository": "acme/app"}},
"a ttl too long": {Key: key, Claims: map[string]string{"repository": "acme/app"}, TTL: int64(31 * 24 * 3600)},
"a ttl too short": {Key: key, Claims: map[string]string{"repository": "acme/app"}, TTL: 10},
"a pattern path.Match refuses": {Key: key, Claims: map[string]string{"repository": "acme/app", "ref": "["}},
} {
if _, err := oidc.Add(r); err == nil {
t.Errorf("%s: added", name)
}
}
r, err := oidc.Add(oidc.Rule{Key: key, Claims: map[string]string{"repository_owner": "acme"}})
if err != nil || r.Issuer != oidc.GitHub {
t.Fatal(r, err)
}
if err := oidc.Remove(r.ID); err != nil {
t.Fatal(err)
}
if err := oidc.Remove(r.ID); err == nil {
t.Fatal("removed twice")
}
}