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.
This commit is contained in:
@@ -683,6 +683,52 @@ gone. A turned-off key on loopback is unchanged: it reads as no key.
|
||||
`TestIssuedKeyBoundedByIssuer` in
|
||||
[`issue_test.go`](../../internal/access/issue_test.go).
|
||||
|
||||
### Trading an OIDC token for a key
|
||||
|
||||
A CI job need keep no gateway key in its secrets (#4531, xazaj on X): it
|
||||
trades its OIDC token for a short-lived key. The user writes a rule
|
||||
([`internal/oidc`](../../internal/oidc/rules.go), kept in
|
||||
`oidc-rules.json`) with `magpie gateway-key oidc add --key <id> --repo
|
||||
owner/name [--ref refs/heads/main] [--environment e] [--claim k=v] [--ttl
|
||||
1h] [--issuer URL] [--audience a]`; `oidc list` and `oidc remove <id>`
|
||||
manage them. No rule, no exchange. A rule names:
|
||||
|
||||
- the issuer, GitHub Actions' (`token.actions.githubusercontent.com`)
|
||||
by default, https only;
|
||||
- the audience, `magpie-<rule id>` by default, so a token asked for one
|
||||
rule opens no other;
|
||||
- the claims the token must have, each exact or a `path.Match` glob. A
|
||||
GitHub rule names `repository`, `repository_owner` or their ids with no
|
||||
wildcard, or any repository's workflow could get a token GitHub signs;
|
||||
- the gateway key the keys are issued under, which must be let issue
|
||||
(`Key.Issues`) and not be issued itself, and how long they live (1h by
|
||||
default, `MinTTL` to `MaxTTL`).
|
||||
|
||||
`POST /v1/magpie/keys/oidc` with `Authorization: Bearer <token>` and an
|
||||
optional `{"ttl", "models"}` ([`oidc_keys.go`](../../internal/gateway/oidc_keys.go))
|
||||
verifies the token (`oidc.Match`, [`verify.go`](../../internal/oidc/verify.go)):
|
||||
RS256 alone, signed by a key from the issuer's discovery document's https
|
||||
`jwks_uri`, `exp` required, `nbf`/`iat` with a minute's leeway, the rule's
|
||||
audience and claims, and a `jti` traded once until it expires. 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, asked again for an unknown `kid` at most every 10s,
|
||||
and the last good keys keep serving while the issuer is down; with none
|
||||
ever read nothing is let in. A matching token gets `access.IssueKey` under
|
||||
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
|
||||
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`
|
||||
([`oidc_keys_test.go`](../../internal/gateway/oidc_keys_test.go)),
|
||||
`TestMatchEachCheck`, `TestKeysCachedAndKept`, `TestUnreadKeysLetNothingIn`
|
||||
and `TestAddRefuses` ([`oidc_test.go`](../../internal/oidc/oidc_test.go)).
|
||||
Not tried: a real GitHub Actions run against a shared magpie.
|
||||
|
||||
### The stats and management API
|
||||
|
||||
Every route under `/v1/magpie/` answers a program on this computer, and
|
||||
@@ -699,6 +745,7 @@ told its own calls and limit alone:
|
||||
| `GET /v1/magpie/limit` | the key's own limits, its `expires`, and `issuerLimits` |
|
||||
| `GET /v1/magpie/concurrency` | requests in flight per account |
|
||||
| `POST`/`GET /v1/magpie/keys`, `DELETE /v1/magpie/keys/{id}` | short-lived keys, above |
|
||||
| `POST /v1/magpie/keys/oidc` | an OIDC token traded for a short-lived key, above |
|
||||
|
||||
## Turning provider search off
|
||||
|
||||
|
||||
@@ -75,3 +75,48 @@ func TestGatewayKeyIssueCLI(t *testing.T) {
|
||||
t.Fatal("help:", help)
|
||||
}
|
||||
}
|
||||
|
||||
// magpie gateway-key oidc adds, lists and removes the rules a CI job's
|
||||
// token is traded by; a rule open to every repository is refused.
|
||||
func TestGatewayKeyOIDCCLI(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("USERPROFILE", os.Getenv("HOME"))
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
call := func(args ...string) (string, error) {
|
||||
var out bytes.Buffer
|
||||
err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...))
|
||||
return strings.TrimSpace(out.String()), err
|
||||
}
|
||||
call("add", "CI")
|
||||
keys, _ := access.List()
|
||||
id := keys[0].ID
|
||||
if _, err := call("oidc", "add", "--key", id, "--repo", "acme/app"); err == nil || !strings.Contains(err.Error(), "issuer "+id+" on") {
|
||||
t.Fatal("a key not let issue:", err)
|
||||
}
|
||||
call("issuer", id, "on")
|
||||
for _, bad := range [][]string{{"oidc", "add", "--key", id, "--ref", "refs/heads/main"}, {"oidc", "add", "--key", id, "--owner", "*"},
|
||||
{"oidc", "add", "--repo", "acme/app"}, {"oidc", "add", "--key", id, "--repo"}, {"oidc", "add", "--key", id, "--repo", "acme/app", "--ttl", "soon"},
|
||||
{"oidc", "add", "--key", id, "--repo", "acme/app", "--ttl", "100ms"}, {"oidc", "add", "--key", id, "--what", "x"}, {"oidc", "remove"}, {"oidc", "maybe"}} {
|
||||
if _, err := call(bad...); err == nil {
|
||||
t.Error("accepted", bad)
|
||||
}
|
||||
}
|
||||
got, err := call("oidc", "add", "--key", id, "--repo", "acme/app", "--environment", "prod", "--ttl", "30m")
|
||||
if err != nil || !strings.Contains(got, "audience magpie-") || !strings.Contains(got, "30m0s") {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
list, _ := call("oidc", "list")
|
||||
if !strings.Contains(list, "environment=prod repository=acme/app") || !strings.Contains(list, "token.actions.githubusercontent.com") {
|
||||
t.Fatal("list:", list)
|
||||
}
|
||||
ruleID := strings.Fields(strings.Split(list, "\n")[1])[0]
|
||||
if _, err := call("oidc", "remove", ruleID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if list, _ := call("oidc"); !strings.Contains(list, "No OIDC rules") {
|
||||
t.Fatal("after remove:", list)
|
||||
}
|
||||
if help := helpFor([]string{"gateway-key", "--help"}); !strings.Contains(help, "gateway-key oidc add") {
|
||||
t.Fatal("help:", help)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/budget"
|
||||
"github.com/yetone/magpie/internal/oidc"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -57,6 +59,10 @@ func gatewayKeysTo(out io.Writer, args []string) error {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
return gatewayKeyIssuer(out, args[1:])
|
||||
}
|
||||
if action == "oidc" {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
return gatewayKeyOIDC(out, args[1:])
|
||||
}
|
||||
// add <name> --read-only: a key that reads stats and uses no model
|
||||
// (Steven on Discord: a desk display)
|
||||
readOnly := false
|
||||
@@ -85,7 +91,7 @@ func gatewayKeysTo(out io.Writer, args []string) error {
|
||||
args = args[:2]
|
||||
}
|
||||
if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) {
|
||||
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] [--read-only] | rotate <id> | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off] | access <id> [read-only | full] | move <id> <place> | issue --ttl <duration> [--name <name>] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] | issuer <id> [on | off]")
|
||||
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] [--read-only] | rotate <id> | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off] | access <id> [read-only | full] | move <id> <place> | issue --ttl <duration> [--name <name>] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] | issuer <id> [on | off] | oidc [list | add --key <id> --repo owner/name … | remove <rule id>]")
|
||||
}
|
||||
switch action {
|
||||
case "list", "add", "rotate", "remove":
|
||||
@@ -724,3 +730,102 @@ func gatewayKeyIssuer(out io.Writer, args []string) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// gatewayKeyOIDC writes the rules a CI job's OIDC token is traded for a
|
||||
// key by (#4531, package oidc):
|
||||
//
|
||||
// magpie gateway-key oidc [list]
|
||||
// magpie gateway-key oidc add --key <id> --repo owner/name [--owner o] [--ref r] [--environment e] [--claim name=value]… [--ttl 1h] [--issuer URL] [--audience aud]
|
||||
// magpie gateway-key oidc remove <rule id>
|
||||
func gatewayKeyOIDC(out io.Writer, args []string) error {
|
||||
usage := fmt.Errorf("usage: magpie gateway-key oidc [list] | add --key <id> --repo owner/name [--owner <owner>] [--ref refs/heads/main] [--environment <name>] [--claim name=value]… [--ttl 1h] [--issuer URL] [--audience <aud>] | remove <rule id>")
|
||||
if len(args) == 0 || args[0] == "list" {
|
||||
if len(args) > 1 {
|
||||
return usage
|
||||
}
|
||||
rules, err := oidc.List()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rules) == 0 {
|
||||
_, err = fmt.Fprintln(out, "No OIDC rules: magpie gateway-key oidc add --key <id> --repo owner/name")
|
||||
return err
|
||||
}
|
||||
w := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
|
||||
fmt.Fprintln(w, "ID\tKEY\tTTL\tAUDIENCE\tCLAIMS\tISSUER")
|
||||
for _, r := range rules {
|
||||
names := slices.Sorted(maps.Keys(r.Claims))
|
||||
claims := make([]string, len(names))
|
||||
for i, k := range names {
|
||||
claims[i] = k + "=" + r.Claims[k]
|
||||
}
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", r.ID, r.Key, r.Lifetime(), r.Audience, strings.Join(claims, " "), r.Issuer)
|
||||
}
|
||||
return w.Flush()
|
||||
}
|
||||
switch args[0] {
|
||||
case "remove":
|
||||
if len(args) != 2 {
|
||||
return usage
|
||||
}
|
||||
if err := oidc.Remove(args[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := fmt.Fprintln(out, "OIDC rule removed")
|
||||
return err
|
||||
case "add":
|
||||
default:
|
||||
return usage
|
||||
}
|
||||
r := oidc.Rule{Claims: map[string]string{}}
|
||||
rest := args[1:]
|
||||
for len(rest) > 0 {
|
||||
if len(rest) < 2 || strings.HasPrefix(rest[1], "--") {
|
||||
return usage
|
||||
}
|
||||
flag, v := rest[0], rest[1]
|
||||
rest = rest[2:]
|
||||
switch flag {
|
||||
case "--key":
|
||||
r.Key = v
|
||||
case "--repo":
|
||||
r.Claims["repository"] = v
|
||||
case "--owner":
|
||||
r.Claims["repository_owner"] = v
|
||||
case "--ref":
|
||||
r.Claims["ref"] = v
|
||||
case "--environment":
|
||||
r.Claims["environment"] = v
|
||||
case "--claim":
|
||||
k, val, ok := strings.Cut(v, "=")
|
||||
if !ok {
|
||||
return usage
|
||||
}
|
||||
r.Claims[k] = val
|
||||
case "--ttl":
|
||||
d, err := time.ParseDuration(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("--ttl is a duration such as 1h or 30m: %q", v)
|
||||
}
|
||||
r.TTL = int64(d / time.Second)
|
||||
if r.TTL == 0 {
|
||||
r.TTL = -1 // refused below as too short, not taken as the default
|
||||
}
|
||||
case "--issuer":
|
||||
r.Issuer = v
|
||||
case "--audience":
|
||||
r.Audience = v
|
||||
default:
|
||||
return usage
|
||||
}
|
||||
}
|
||||
if r.Key == "" {
|
||||
return usage
|
||||
}
|
||||
r, err := oidc.Add(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintf(out, "OIDC rule %s: a token from %s with audience %s and %d claim(s) matched gets a key issued under %s, living up to %s.\nPOST it to /v1/magpie/keys/oidc as Authorization: Bearer <token>.\n", r.ID, r.Issuer, r.Audience, len(r.Claims), r.Key, r.Lifetime())
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -133,6 +133,8 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie gateway-key issue --ttl 1h [--name n] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] [--json]
|
||||
a short-lived key (1m to 30 days) that stops working by itself; --from holds it to a key that issues keys; prints the key
|
||||
magpie gateway-key issuer <id> [on|off] let a key issue short-lived keys under itself (POST /v1/magpie/keys with it), each held to its models, accounts, limits and life
|
||||
magpie gateway-key oidc add --key <id> --repo owner/name [--ref refs/heads/main] [--environment name] [--claim name=value]… [--ttl 1h] [--issuer URL] [--audience aud]
|
||||
let a CI job's OIDC token (GitHub Actions by default) be traded for a key issued under <id> (POST /v1/magpie/keys/oidc); oidc list | remove <rule id>
|
||||
magpie mcp image the image and video generation MCP server an agent is given from the library (stdio)
|
||||
magpie tools [<name>] the tools magpie's MCP servers give agents (images, vision, web search, plugins'), with their parameters
|
||||
magpie tool <name> [--<param> <value>…] [<words>] [-o <file|folder>] [--json] call one through the running magpie; an image or video it makes is saved
|
||||
|
||||
@@ -830,6 +830,9 @@ func (s *Server) routes() *routeMux {
|
||||
mux.HandleFunc("POST "+KeysPath, s.issueKey)
|
||||
mux.HandleFunc("GET "+KeysPath, s.issuedKeys)
|
||||
mux.HandleFunc("DELETE "+KeysPath+"/{id}", s.revokeIssuedKey)
|
||||
// and one traded for an OIDC token, by a rule the user wrote
|
||||
// (oidc_keys.go)
|
||||
mux.HandleFunc("POST "+OIDCKeysPath, s.oidcIssueKey)
|
||||
mux.HandleFunc("GET "+KeyPagePath, s.keyPage)
|
||||
mux.HandleFunc("GET "+keyPageData, s.keyInfo)
|
||||
// the Claude Code processes the Claude subscription runs, for magpie
|
||||
|
||||
@@ -381,6 +381,13 @@ func lanGuard(next http.Handler) http.Handler {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
// a CI job's OIDC token traded for a key carries the token, not a
|
||||
// key: the handler verifies it, and counts one it refuses against
|
||||
// tooManyAuthFails (oidc_keys.go)
|
||||
if remote && oidcExchange(r) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if remote || managedKey(r) {
|
||||
var ok bool
|
||||
r, ok = identifyCaller(w, r)
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/oidc"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// OIDCKeysPath trades an OIDC token for a short-lived gateway key (#4531):
|
||||
// a GitHub Actions job asks GitHub for a token with the rule's audience
|
||||
// and POSTs it here as Authorization: Bearer <token>, with no gateway
|
||||
// key, and gets a key issued under the rule's gateway key (package oidc).
|
||||
// The body is optional: {"ttl": "30m", "models": […]}, each no more than
|
||||
// the rule and its key allow.
|
||||
//
|
||||
// It is answered from another machine only while the gateway is shared,
|
||||
// past the allow list, as every route is (lanGuard); a token that isn't
|
||||
// let in counts against the failed authentications another machine may
|
||||
// make (tooManyAuthFails), as a wrong key does.
|
||||
const OIDCKeysPath = KeysPath + "/oidc"
|
||||
|
||||
// oidcExchange: r is a token's trade, which carries a token, not a key.
|
||||
func oidcExchange(r *http.Request) bool {
|
||||
return r.Method == http.MethodPost && r.URL.Path == OIDCKeysPath && r.URL.RawPath == "" && !managedKey(r)
|
||||
}
|
||||
|
||||
func (s *Server) oidcIssueKey(w http.ResponseWriter, r *http.Request) {
|
||||
token := ""
|
||||
if a := r.Header.Get("Authorization"); len(a) > 7 && strings.EqualFold(a[:7], "Bearer ") {
|
||||
token = strings.TrimSpace(a[7:])
|
||||
}
|
||||
refuse := func(why string) {
|
||||
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
|
||||
}
|
||||
}
|
||||
log.Printf("refused %s %s from %s: %s", r.Method, r.URL.Path, r.RemoteAddr, why)
|
||||
writeError(w, provider.Chat, http.StatusUnauthorized, why)
|
||||
}
|
||||
if token == "" {
|
||||
refuse("send the OIDC token as Authorization: Bearer <token>")
|
||||
return
|
||||
}
|
||||
rule, claims, err := oidc.Match(r.Context(), token)
|
||||
if err != nil {
|
||||
refuse(err.Error())
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
TTL json.RawMessage `json:"ttl"`
|
||||
Models []string `json:"models"`
|
||||
}
|
||||
if b, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)); len(strings.TrimSpace(string(b))) > 0 {
|
||||
if err := json.Unmarshal(b, &in); err != nil {
|
||||
writeError(w, provider.Chat, http.StatusBadRequest, "the body is empty or a JSON object: {\"ttl\": \"30m\", \"models\": […]}")
|
||||
return
|
||||
}
|
||||
}
|
||||
ttl := rule.Lifetime()
|
||||
if len(in.TTL) > 0 {
|
||||
asked, err := parseTTL(in.TTL)
|
||||
if err != nil {
|
||||
writeError(w, provider.Chat, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
ttl = min(asked, ttl) // never longer than the rule says
|
||||
}
|
||||
k, err := access.IssueKey(access.Issue{Name: oidcKeyName(claims), TTL: ttl, Models: in.Models, Issuer: rule.Key})
|
||||
if err != nil {
|
||||
writeError(w, provider.Chat, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
log.Printf("issued gateway key %s (%s) for an OIDC token by rule %s", k.ID, k.Name, rule.ID)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusCreated, k)
|
||||
}
|
||||
|
||||
// oidcKeyName names a key by what asked for it: a GitHub job's
|
||||
// repository, ref and run, another issuer's subject.
|
||||
func oidcKeyName(c oidc.Claims) string {
|
||||
name := c.Str("sub")
|
||||
if repo := c.Str("repository"); repo != "" {
|
||||
name = repo
|
||||
if ref := c.Str("ref"); ref != "" {
|
||||
name += "@" + strings.TrimPrefix(strings.TrimPrefix(ref, "refs/heads/"), "refs/")
|
||||
}
|
||||
if run := c.Str("run_id"); run != "" {
|
||||
name += " (run " + run + ")"
|
||||
}
|
||||
}
|
||||
name = strings.Map(func(r rune) rune {
|
||||
if r < 32 || r == 127 {
|
||||
return ' '
|
||||
}
|
||||
return r
|
||||
}, name)
|
||||
if utf8.RuneCountInString(name) > 120 {
|
||||
name = string([]rune(name)[:119]) + "…"
|
||||
}
|
||||
if strings.TrimSpace(name) == "" {
|
||||
name = "OIDC"
|
||||
}
|
||||
return name
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/budget"
|
||||
"github.com/yetone/magpie/internal/oidc"
|
||||
"github.com/yetone/magpie/internal/oidc/oidctest"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// #4531 (xazaj on X): a GitHub Actions job trades its OIDC token for a
|
||||
// short-lived key from another machine, with no gateway key of its own.
|
||||
// The key is issued under the rule's key, lives no longer than the rule
|
||||
// says, and works; a token no rule takes, a refused one past the burst,
|
||||
// and any token while magpie isn't shared get nothing.
|
||||
func TestOIDCTokenTradedForKey(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
budget.Forget()
|
||||
limitedUpstream(t, 0)
|
||||
resetAuthThrottle()
|
||||
t.Cleanup(resetAuthThrottle)
|
||||
is := oidctest.New(t)
|
||||
keys, _ := newCaller(t, "CI")
|
||||
h := lanGuard(New().Handler())
|
||||
now := time.Now().Unix()
|
||||
jti := 0
|
||||
token := func(aud string, over map[string]any) string {
|
||||
jti++
|
||||
c := map[string]any{"iss": is.URL, "aud": aud, "repository": "acme/app", "ref": "refs/heads/main", "run_id": "42",
|
||||
"sub": "repo:acme/app:ref:refs/heads/main", "iat": now, "exp": now + 300, "jti": strings.Repeat("j", jti)}
|
||||
for k, v := range over {
|
||||
c[k] = v
|
||||
}
|
||||
return is.Sign(t, "k1", c)
|
||||
}
|
||||
|
||||
if w := keysCall(h, "POST", OIDCKeysPath, fromThere, token("magpie-x", nil), ""); w.Code != http.StatusUnauthorized || !strings.Contains(w.Body.String(), "no rule") {
|
||||
t.Fatal("no rule:", w.Code, w.Body.String())
|
||||
}
|
||||
if _, err := access.Update("issuer-key", access.Change{Key: keys[0].ID, Issues: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"plan/m1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rule, err := oidc.Add(oidc.Rule{Key: keys[0].ID, Issuer: is.URL, Claims: map[string]string{"repository": "acme/app", "ref": "refs/heads/main"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := keysCall(h, "POST", OIDCKeysPath, fromThere, token(rule.Audience, nil), `{"ttl":"48h"}`)
|
||||
k := issuedFrom(t, w)
|
||||
if k.Issuer != keys[0].ID || k.Name != "acme/app@main (run 42)" || time.Until(k.Expires) > time.Hour || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("%+v", k)
|
||||
}
|
||||
if w := keysCall(h, "POST", "/v1/chat/completions", fromThere, k.Key, chatReq); w.Code != 200 {
|
||||
t.Fatal("the key traded for:", w.Code, w.Body.String())
|
||||
}
|
||||
// bounded by its issuer: a model the rule's key may not use is refused
|
||||
if w := keysCall(h, "POST", OIDCKeysPath, fromThere, token(rule.Audience, nil), `{"models":["other/m2"]}`); w.Code != http.StatusBadRequest {
|
||||
t.Fatal("issued a model its issuer may not use:", w.Code, w.Body.String())
|
||||
}
|
||||
// a token from a branch the rule doesn't name, and none at all
|
||||
if w := keysCall(h, "POST", OIDCKeysPath, fromThere, token(rule.Audience, map[string]any{"ref": "refs/heads/fork"}), ""); w.Code != http.StatusUnauthorized || strings.Contains(w.Body.String(), access.Prefix) {
|
||||
t.Fatal("another branch:", w.Code, w.Body.String())
|
||||
}
|
||||
if w := keysCall(h, "POST", OIDCKeysPath, fromThere, "", ""); w.Code != http.StatusUnauthorized {
|
||||
t.Fatal("no token:", w.Code, w.Body.String())
|
||||
}
|
||||
// refused tokens count against the failed authentications
|
||||
var last int
|
||||
for range authFailBurst + 1 {
|
||||
last = keysCall(h, "POST", OIDCKeysPath, fromThere, "not.a.jwt", "").Code
|
||||
}
|
||||
if last != http.StatusTooManyRequests {
|
||||
t.Fatal("refused tokens weren't counted:", last)
|
||||
}
|
||||
resetAuthThrottle()
|
||||
// the issuer turned off: the rule issues nothing
|
||||
if _, err := access.Update("issuer-key", access.Change{Key: keys[0].ID, Issues: false}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := keysCall(h, "POST", OIDCKeysPath, fromThere, token(rule.Audience, nil), ""); w.Code == http.StatusCreated {
|
||||
t.Fatal("issued under a key no longer let issue")
|
||||
}
|
||||
if _, err := access.Update("issuer-key", access.Change{Key: keys[0].ID, Issues: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the exemption is this route alone: a token on a model route is a wrong key
|
||||
if w := keysCall(h, "POST", "/v1/chat/completions", fromThere, token(rule.Audience, nil), chatReq); w.Code != http.StatusUnauthorized {
|
||||
t.Fatal("a token on a model route:", w.Code, w.Body.String())
|
||||
}
|
||||
// this computer may trade one too
|
||||
issuedFrom(t, keysCall(h, "POST", OIDCKeysPath, fromHere, token(rule.Audience, nil), ""))
|
||||
// not shared: another machine gets nothing, token or not
|
||||
s := settings.Load()
|
||||
s.LAN = false
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := keysCall(h, "POST", OIDCKeysPath, fromThere, token(rule.Audience, nil), ""); w.Code != http.StatusForbidden {
|
||||
t.Fatal("not shared:", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ var readOnlyRefused = []string{
|
||||
"GET /v1/magpie/route", "GET /v1/magpie/trace",
|
||||
"GET " + ClaudeRunsPath, "GET " + HeapPath, "GET " + CPUPath, "GET " + GoroutinesPath,
|
||||
"POST " + RestartPath,
|
||||
"POST " + KeysPath, "GET " + KeysPath, "DELETE " + KeysPath + "/{id}",
|
||||
"POST " + KeysPath, "GET " + KeysPath, "DELETE " + KeysPath + "/{id}", "POST " + OIDCKeysPath,
|
||||
"GET /v1/magpie/omarchy", "OPTIONS /v1/magpie/omarchy",
|
||||
// models, a WebSocket's upgrade and count_tokens among them
|
||||
"POST /v1/chat/completions", "POST /chat/completions",
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Package oidctest serves an OIDC issuer on an httptest TLS server for the
|
||||
// tests of package oidc and the gateway: its discovery document, its keys
|
||||
// and the tokens it signs, never reaching the network.
|
||||
package oidctest
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/oidc"
|
||||
)
|
||||
|
||||
// Issuer is one issuer. Fetches counts the times its keys were read;
|
||||
// Down makes it answer 503.
|
||||
type Issuer struct {
|
||||
URL string
|
||||
Fetches atomic.Int32
|
||||
Down atomic.Bool
|
||||
mu sync.Mutex
|
||||
keys map[string]*rsa.PrivateKey
|
||||
}
|
||||
|
||||
// New starts an issuer with one key, "k1", and points oidc.Client at it.
|
||||
func New(t testing.TB) *Issuer {
|
||||
t.Helper()
|
||||
is := &Issuer{keys: map[string]*rsa.PrivateKey{}}
|
||||
is.AddKey(t, "k1")
|
||||
srv := httptest.NewTLSServer(http.HandlerFunc(is.serve))
|
||||
t.Cleanup(srv.Close)
|
||||
is.URL = srv.URL
|
||||
was := oidc.Client
|
||||
oidc.Client = srv.Client()
|
||||
t.Cleanup(func() { oidc.Client = was })
|
||||
return is
|
||||
}
|
||||
|
||||
// AddKey makes the issuer sign with a new key kid as well.
|
||||
func (is *Issuer) AddKey(t testing.TB, kid string) *rsa.PrivateKey {
|
||||
t.Helper()
|
||||
k, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
is.mu.Lock()
|
||||
is.keys[kid] = k
|
||||
is.mu.Unlock()
|
||||
return k
|
||||
}
|
||||
|
||||
func (is *Issuer) serve(w http.ResponseWriter, r *http.Request) {
|
||||
if is.Down.Load() {
|
||||
http.Error(w, "down", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/.well-known/openid-configuration":
|
||||
json.NewEncoder(w).Encode(map[string]string{"issuer": is.URL, "jwks_uri": is.URL + "/jwks"})
|
||||
case "/jwks":
|
||||
is.Fetches.Add(1)
|
||||
is.mu.Lock()
|
||||
var keys []map[string]string
|
||||
for kid, k := range is.keys {
|
||||
keys = append(keys, map[string]string{"kty": "RSA", "kid": kid, "use": "sig", "alg": "RS256",
|
||||
"n": b64(k.N.Bytes()), "e": b64(big.NewInt(int64(k.E)).Bytes())})
|
||||
}
|
||||
is.mu.Unlock()
|
||||
json.NewEncoder(w).Encode(map[string]any{"keys": keys})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
|
||||
|
||||
// Sign makes a token with claims, signed by the key kid (alg RS256), or
|
||||
// by key when it is given (a key the issuer doesn't list).
|
||||
func (is *Issuer) Sign(t testing.TB, kid string, claims map[string]any, key ...*rsa.PrivateKey) string {
|
||||
t.Helper()
|
||||
is.mu.Lock()
|
||||
k := is.keys[kid]
|
||||
is.mu.Unlock()
|
||||
if len(key) > 0 {
|
||||
k = key[0]
|
||||
}
|
||||
h, _ := json.Marshal(map[string]string{"alg": "RS256", "typ": "JWT", "kid": kid})
|
||||
c, _ := json.Marshal(claims)
|
||||
in := b64(h) + "." + b64(c)
|
||||
sum := sha256.Sum256([]byte(in))
|
||||
sig, err := rsa.SignPKCS1v15(rand.Reader, k, crypto.SHA256, sum[:])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return in + "." + b64(sig)
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// Package oidc lets a CI job trade an OIDC token for a short-lived gateway
|
||||
// key (#4531, xazaj on X: GitHub Actions' token in place of a key kept in
|
||||
// the repository's secrets). The user writes a rule: which issuer, which
|
||||
// audience, which claims (repository, ref, environment…), and which of
|
||||
// their gateway keys the key is issued under; a token that is signed by
|
||||
// that issuer and matches every claim gets a key, held to everything that
|
||||
// gateway key is held to and living no longer than the rule says.
|
||||
//
|
||||
// No rule, no exchange: none is made by default.
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// GitHub is GitHub Actions' issuer, a rule's when it names none.
|
||||
const GitHub = "https://token.actions.githubusercontent.com"
|
||||
|
||||
// DefaultTTL is how long a key lives when the rule says nothing.
|
||||
const DefaultTTL = time.Hour
|
||||
|
||||
// githubScopes are the claims of which a GitHub rule names one, with no
|
||||
// wildcard: without it, any repository's workflow on GitHub could get a
|
||||
// token GitHub signs with the rule's audience.
|
||||
var githubScopes = []string{"repository", "repository_owner", "repository_id", "repository_owner_id"}
|
||||
|
||||
// Rule is one way in.
|
||||
type Rule struct {
|
||||
ID string `json:"id"`
|
||||
// Key is the id of the gateway key the keys are issued under; it must
|
||||
// be let issue keys (magpie gateway-key issuer <id> on).
|
||||
Key string `json:"key"`
|
||||
Issuer string `json:"issuer"`
|
||||
// Audience is the token's aud the rule takes: by default
|
||||
// "magpie-<id>", so a token asked for one rule opens no other.
|
||||
Audience string `json:"audience"`
|
||||
// Claims each name a claim and the value it must have: exact, or a
|
||||
// glob as path.Match reads it ("refs/heads/release/*").
|
||||
Claims map[string]string `json:"claims"`
|
||||
// TTL is the longest a key it issues lives, in seconds.
|
||||
TTL int64 `json:"ttl"`
|
||||
}
|
||||
|
||||
// Lifetime is the rule's TTL as a duration.
|
||||
func (r Rule) Lifetime() time.Duration { return time.Duration(r.TTL) * time.Second }
|
||||
|
||||
var mu = filelock.Mutex{Path: func() string { return Path() + ".lock" }}
|
||||
|
||||
// Path is the rules' file.
|
||||
func Path() string { return filepath.Join(settings.Dir(), "oidc-rules.json") }
|
||||
|
||||
// load reads the rules; a file that can't be read or parsed is an error,
|
||||
// never "no rules" read as something else.
|
||||
func load() ([]Rule, error) {
|
||||
b, err := os.ReadFile(Path())
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var rules []Rule
|
||||
if err := json.Unmarshal(b, &rules); err != nil {
|
||||
return nil, fmt.Errorf("%s can't be read: %w", Path(), err)
|
||||
}
|
||||
return rules, nil
|
||||
}
|
||||
|
||||
func save(rules []Rule) error {
|
||||
b, err := json.MarshalIndent(rules, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(Path()), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return edit.WriteAtomic(Path(), append(b, '\n'))
|
||||
}
|
||||
|
||||
// List is every rule.
|
||||
func List() ([]Rule, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return load()
|
||||
}
|
||||
|
||||
// Add checks r and keeps it, and gives it back with its id and defaults.
|
||||
func Add(r Rule) (Rule, error) {
|
||||
r.Issuer = strings.TrimRight(strings.TrimSpace(r.Issuer), "/")
|
||||
if r.Issuer == "" {
|
||||
r.Issuer = GitHub
|
||||
}
|
||||
if u, err := url.Parse(r.Issuer); err != nil || u.Scheme != "https" || u.Host == "" || u.RawQuery != "" || u.Fragment != "" {
|
||||
return Rule{}, fmt.Errorf("the issuer is an https URL, such as %s", GitHub)
|
||||
}
|
||||
if len(r.Claims) == 0 {
|
||||
return Rule{}, errors.New("a rule names at least one claim the token must have, such as repository=owner/name")
|
||||
}
|
||||
for k, v := range r.Claims {
|
||||
if strings.TrimSpace(k) != k || k == "" || v == "" {
|
||||
return Rule{}, fmt.Errorf("a claim is name=value, both given: %q=%q", k, v)
|
||||
}
|
||||
if _, err := path.Match(v, ""); err != nil {
|
||||
return Rule{}, fmt.Errorf("the value of %s isn't a pattern path.Match reads: %q", k, v)
|
||||
}
|
||||
}
|
||||
if r.Issuer == GitHub && !slices.ContainsFunc(githubScopes, func(c string) bool {
|
||||
v, ok := r.Claims[c]
|
||||
return ok && !strings.ContainsAny(v, `*?[\`)
|
||||
}) {
|
||||
return Rule{}, errors.New("a GitHub rule names the repository (repository=owner/name) or its owner (repository_owner=owner) without a wildcard: otherwise any repository's workflow on GitHub could get a key")
|
||||
}
|
||||
if r.TTL == 0 {
|
||||
r.TTL = int64(DefaultTTL / time.Second)
|
||||
}
|
||||
if d := r.Lifetime(); d < access.MinTTL || d > access.MaxTTL {
|
||||
return Rule{}, fmt.Errorf("a key lives from %s to %d days", access.MinTTL, int(access.MaxTTL.Hours()/24))
|
||||
}
|
||||
keys, err := access.List()
|
||||
if err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
i := slices.IndexFunc(keys, func(k access.Key) bool { return k.ID == r.Key })
|
||||
if i < 0 {
|
||||
return Rule{}, fmt.Errorf("no gateway key has the id %q (magpie gateway-key list)", r.Key)
|
||||
}
|
||||
if !keys[i].Issues || keys[i].Issuer != "" {
|
||||
return Rule{}, fmt.Errorf("the gateway key %s can't issue keys: let it with magpie gateway-key issuer %s on", keys[i].Name, r.Key)
|
||||
}
|
||||
b := make([]byte, 6)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
r.ID = hex.EncodeToString(b)
|
||||
r.Audience = strings.TrimSpace(r.Audience)
|
||||
if r.Audience == "" {
|
||||
r.Audience = "magpie-" + r.ID
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
rules, err := load()
|
||||
if err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
return r, save(append(rules, r))
|
||||
}
|
||||
|
||||
// Remove takes the rule id away.
|
||||
func Remove(id string) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
rules, err := load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i := slices.IndexFunc(rules, func(r Rule) bool { return r.ID == id })
|
||||
if i < 0 {
|
||||
return fmt.Errorf("no rule has the id %q (magpie gateway-key oidc list)", id)
|
||||
}
|
||||
return save(slices.Delete(rules, i, i+1))
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Client fetches the issuers' keys; a variable for the tests, which serve
|
||||
// them from an httptest TLS server and never reach the network.
|
||||
var Client = &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
// Now is the clock tokens are judged by.
|
||||
var Now = time.Now
|
||||
|
||||
// leeway is how far apart this computer's clock and the issuer's may be.
|
||||
const leeway = time.Minute
|
||||
|
||||
// Claims are a verified token's claims.
|
||||
type Claims map[string]any
|
||||
|
||||
// Str is claim c as text: a string as it is, a number or bool written out.
|
||||
func (c Claims) Str(name string) string {
|
||||
switch v := c[name].(type) {
|
||||
case string:
|
||||
return v
|
||||
case json.Number:
|
||||
return v.String()
|
||||
case bool:
|
||||
return strconv.FormatBool(v)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Match verifies token and finds the first rule it satisfies. A token is
|
||||
// judged only against rules that name its issuer, so an issuer no rule
|
||||
// names is never asked for keys: a token can't make magpie fetch from a
|
||||
// URL of its choosing.
|
||||
func Match(ctx context.Context, token string) (Rule, Claims, error) {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 {
|
||||
return Rule{}, nil, errors.New("the bearer token isn't a JWT")
|
||||
}
|
||||
var head struct {
|
||||
Alg string `json:"alg"`
|
||||
Kid string `json:"kid"`
|
||||
}
|
||||
if err := decodePart(parts[0], &head); err != nil {
|
||||
return Rule{}, nil, errors.New("the token's header can't be read")
|
||||
}
|
||||
if head.Alg != "RS256" {
|
||||
return Rule{}, nil, fmt.Errorf("the token is signed with %q: only RS256 is taken", clip(head.Alg))
|
||||
}
|
||||
var claims Claims
|
||||
if err := decodePart(parts[1], &claims); err != nil {
|
||||
return Rule{}, nil, errors.New("the token's claims can't be read")
|
||||
}
|
||||
iss := claims.Str("iss")
|
||||
rules, err := List()
|
||||
if err != nil {
|
||||
return Rule{}, nil, err
|
||||
}
|
||||
rules = slices.DeleteFunc(rules, func(r Rule) bool { return r.Issuer != strings.TrimRight(iss, "/") })
|
||||
if len(rules) == 0 {
|
||||
return Rule{}, nil, fmt.Errorf("no rule takes tokens from %q (magpie gateway-key oidc add)", clip(iss))
|
||||
}
|
||||
sig, err := base64.RawURLEncoding.DecodeString(parts[2])
|
||||
if err != nil {
|
||||
return Rule{}, nil, errors.New("the token's signature can't be read")
|
||||
}
|
||||
pub, err := publicKey(ctx, rules[0].Issuer, head.Kid)
|
||||
if err != nil {
|
||||
return Rule{}, nil, err
|
||||
}
|
||||
sum := sha256.Sum256([]byte(parts[0] + "." + parts[1]))
|
||||
if rsa.VerifyPKCS1v15(pub, crypto.SHA256, sum[:], sig) != nil {
|
||||
return Rule{}, nil, errors.New("the token's signature is not its issuer's")
|
||||
}
|
||||
now := Now()
|
||||
exp, ok := claimTime(claims, "exp")
|
||||
if !ok {
|
||||
return Rule{}, nil, errors.New("the token has no expiry")
|
||||
}
|
||||
if !now.Before(exp.Add(leeway)) {
|
||||
return Rule{}, nil, errors.New("the token has expired")
|
||||
}
|
||||
if nbf, ok := claimTime(claims, "nbf"); ok && now.Add(leeway).Before(nbf) {
|
||||
return Rule{}, nil, errors.New("the token isn't valid yet")
|
||||
}
|
||||
if iat, ok := claimTime(claims, "iat"); ok && now.Add(leeway).Before(iat) {
|
||||
return Rule{}, nil, errors.New("the token was issued in the future: check this computer's clock")
|
||||
}
|
||||
aud := audiences(claims["aud"])
|
||||
for _, r := range rules {
|
||||
if !slices.Contains(aud, r.Audience) || !claimsMatch(r.Claims, claims) {
|
||||
continue
|
||||
}
|
||||
if jti := claims.Str("jti"); jti != "" && !firstUse(iss+"\x00"+jti, exp.Add(leeway), now) {
|
||||
return Rule{}, nil, errors.New("this token was traded for a key already: ask the issuer for a new one")
|
||||
}
|
||||
return r, claims, nil
|
||||
}
|
||||
return Rule{}, nil, fmt.Errorf("the token matches no rule: it has aud %q and %s", strings.Join(aud, ","), described(claims, rules))
|
||||
}
|
||||
|
||||
func decodePart(s string, v any) error {
|
||||
b, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := json.NewDecoder(strings.NewReader(string(b)))
|
||||
d.UseNumber()
|
||||
return d.Decode(v)
|
||||
}
|
||||
|
||||
// clip keeps an unverified value short in a reply and the log.
|
||||
func clip(s string) string {
|
||||
if len(s) > 100 {
|
||||
return s[:100] + "…"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func claimTime(c Claims, name string) (time.Time, bool) {
|
||||
n, ok := c[name].(json.Number)
|
||||
if !ok {
|
||||
return time.Time{}, false
|
||||
}
|
||||
f, err := n.Float64()
|
||||
if err != nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return time.Unix(int64(f), 0), true
|
||||
}
|
||||
|
||||
func audiences(v any) []string {
|
||||
switch a := v.(type) {
|
||||
case string:
|
||||
return []string{a}
|
||||
case []any:
|
||||
var out []string
|
||||
for _, x := range a {
|
||||
if s, ok := x.(string); ok {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func claimsMatch(want map[string]string, c Claims) bool {
|
||||
for k, pattern := range want {
|
||||
if _, ok := c[k]; !ok {
|
||||
return false
|
||||
}
|
||||
if ok, _ := path.Match(pattern, c.Str(k)); !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// described names the token's values of the claims the rules ask about,
|
||||
// so whoever wrote the workflow sees which one is off.
|
||||
func described(c Claims, rules []Rule) string {
|
||||
seen := map[string]bool{}
|
||||
var names []string
|
||||
for _, r := range rules {
|
||||
for k := range r.Claims {
|
||||
if !seen[k] {
|
||||
seen[k] = true
|
||||
names = append(names, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
parts := make([]string, len(names))
|
||||
for i, k := range names {
|
||||
parts[i] = k + "=" + strconv.Quote(clip(c.Str(k)))
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
// used are the token ids traded, each until its token expires.
|
||||
var used = struct {
|
||||
sync.Mutex
|
||||
m map[string]time.Time
|
||||
}{m: map[string]time.Time{}}
|
||||
|
||||
func firstUse(id string, until, now time.Time) bool {
|
||||
used.Lock()
|
||||
defer used.Unlock()
|
||||
for k, t := range used.m {
|
||||
if !now.Before(t) {
|
||||
delete(used.m, k)
|
||||
}
|
||||
}
|
||||
if _, ok := used.m[id]; ok {
|
||||
return false
|
||||
}
|
||||
used.m[id] = until
|
||||
return true
|
||||
}
|
||||
|
||||
// keySet is an issuer's signing keys as last read.
|
||||
type keySet struct {
|
||||
keys map[string]*rsa.PublicKey
|
||||
fetched time.Time // when keys were read
|
||||
tried time.Time // when they were last asked for
|
||||
loading chan struct{} // closed when a read under way ends
|
||||
}
|
||||
|
||||
var sets = struct {
|
||||
sync.Mutex
|
||||
m map[string]*keySet
|
||||
}{m: map[string]*keySet{}}
|
||||
|
||||
// Keys are read again after keysFresh, and at most once in refetchGap
|
||||
// for a key id they don't have, so tokens with made-up ids can't make
|
||||
// magpie ask the issuer on every request.
|
||||
const (
|
||||
keysFresh = time.Hour
|
||||
refetchGap = 10 * time.Second
|
||||
)
|
||||
|
||||
// publicKey is the issuer's key kid. Keys that can't be read again keep
|
||||
// serving as last read; with none read, nothing is let in.
|
||||
func publicKey(ctx context.Context, iss, kid string) (*rsa.PublicKey, error) {
|
||||
for {
|
||||
sets.Lock()
|
||||
ks := sets.m[iss]
|
||||
if ks == nil {
|
||||
ks = &keySet{}
|
||||
sets.m[iss] = ks
|
||||
}
|
||||
now := Now()
|
||||
k, have := ks.keys[kid]
|
||||
stale := ks.fetched.IsZero() || now.Sub(ks.fetched) > keysFresh || !have
|
||||
if !stale || (!ks.tried.IsZero() && now.Sub(ks.tried) < refetchGap && ks.loading == nil) {
|
||||
sets.Unlock()
|
||||
if have {
|
||||
return k, nil
|
||||
}
|
||||
return nil, fmt.Errorf("the token's key %q isn't one %s signs with", clip(kid), iss)
|
||||
}
|
||||
if wait := ks.loading; wait != nil {
|
||||
sets.Unlock()
|
||||
select {
|
||||
case <-wait:
|
||||
continue
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
done := make(chan struct{})
|
||||
ks.loading, ks.tried = done, now
|
||||
sets.Unlock()
|
||||
keys, err := fetchKeys(ctx, iss)
|
||||
sets.Lock()
|
||||
if err == nil {
|
||||
ks.keys, ks.fetched = keys, Now()
|
||||
}
|
||||
ks.loading = nil
|
||||
close(done)
|
||||
k, have = ks.keys[kid]
|
||||
sets.Unlock()
|
||||
if have {
|
||||
return k, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s's signing keys can't be read: %v", iss, err)
|
||||
}
|
||||
return nil, fmt.Errorf("the token's key %q isn't one %s signs with", clip(kid), iss)
|
||||
}
|
||||
}
|
||||
|
||||
func getJSON(ctx context.Context, u string, v any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := Client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%s answered %s", u, resp.Status)
|
||||
}
|
||||
return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(v)
|
||||
}
|
||||
|
||||
// fetchKeys reads the issuer's RSA keys from its discovery document's
|
||||
// jwks_uri, which is https too.
|
||||
func fetchKeys(ctx context.Context, iss string) (map[string]*rsa.PublicKey, error) {
|
||||
var conf struct {
|
||||
Issuer string `json:"issuer"`
|
||||
JWKSURI string `json:"jwks_uri"`
|
||||
}
|
||||
if err := getJSON(ctx, iss+"/.well-known/openid-configuration", &conf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimRight(conf.Issuer, "/") != iss {
|
||||
return nil, fmt.Errorf("its discovery document names the issuer %q", clip(conf.Issuer))
|
||||
}
|
||||
if u, err := url.Parse(conf.JWKSURI); err != nil || u.Scheme != "https" {
|
||||
return nil, fmt.Errorf("its jwks_uri isn't https: %q", clip(conf.JWKSURI))
|
||||
}
|
||||
var set struct {
|
||||
Keys []struct {
|
||||
Kty string `json:"kty"`
|
||||
Kid string `json:"kid"`
|
||||
Use string `json:"use"`
|
||||
N string `json:"n"`
|
||||
E string `json:"e"`
|
||||
} `json:"keys"`
|
||||
}
|
||||
if err := getJSON(ctx, conf.JWKSURI, &set); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keys := map[string]*rsa.PublicKey{}
|
||||
for _, k := range set.Keys {
|
||||
if k.Kty != "RSA" || (k.Use != "" && k.Use != "sig") {
|
||||
continue
|
||||
}
|
||||
n, err1 := base64.RawURLEncoding.DecodeString(k.N)
|
||||
e, err2 := base64.RawURLEncoding.DecodeString(k.E)
|
||||
if err1 != nil || err2 != nil || len(e) == 0 || len(e) > 4 {
|
||||
continue
|
||||
}
|
||||
pub := &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())}
|
||||
if pub.N.BitLen() < 2048 || pub.E < 3 {
|
||||
continue
|
||||
}
|
||||
keys[k.Kid] = pub
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return nil, errors.New("it lists no RSA signing key")
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
@@ -78,6 +78,7 @@
|
||||
<a href="#models">使えるもの</a>
|
||||
<a href="#quotas">クォータと使用量</a>
|
||||
<a href="#keys">短期キー</a>
|
||||
<a href="#oidc">GitHub Actions のキー</a>
|
||||
<a href="#api">統計 API</a>
|
||||
<a href="#trouble">うまくいかないとき</a>
|
||||
</aside>
|
||||
@@ -156,6 +157,35 @@ magpie gateway-key list <span class="c"># until 10-31 14:00、expi
|
||||
</div>
|
||||
<p>期限切れのキーは、どの API でも理由付きの <code>401</code>(“the gateway key "sandbox-1" expired at …: ask for a new one”)で断られます。このコンピューターからでも同じです。1 時間後に削除されます。</p>
|
||||
|
||||
<h2 id="oidc"><a class="anchor" href="#oidc">GitHub Actions のキー</a></h2>
|
||||
<p>GitHub Actions のジョブは、リポジトリの secrets にゲートウェイキーを置かなくても短期キーを受け取れます。GitHub が渡す OIDC トークンと交換します。リポジトリ(必要ならブランチ、environment、任意の claim。完全一致か <code>*</code> 付き)、発行に使うゲートウェイキー、有効期間を指定するルールを書きます:</p>
|
||||
<div class="code">
|
||||
<span class="lang">Shell</span>
|
||||
<button class="copy" data-copy="ex-oidc-cli">コピー</button>
|
||||
<pre id="ex-oidc-cli">magpie gateway-key issuer <id> on
|
||||
magpie gateway-key oidc add --key <id> --repo owner/app --ref refs/heads/main --ttl 1h
|
||||
<span class="c"># ルール id と audience(magpie-<ルール id>)を表示</span>
|
||||
magpie gateway-key oidc list
|
||||
magpie gateway-key oidc remove <rule id></pre>
|
||||
</div>
|
||||
<p>ワークフローでは、ルールの audience 付きトークンを GitHub に求め、<code>/v1/magpie/keys/oidc</code> に POST します:</p>
|
||||
<div class="code">
|
||||
<span class="lang">YAML</span>
|
||||
<button class="copy" data-copy="ex-oidc">コピー</button>
|
||||
<pre id="ex-oidc">permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Get a magpie key
|
||||
run: |
|
||||
TOKEN=$(curl -s -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
|
||||
"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=magpie-<rule id>" | jq -r .value)
|
||||
KEY=$(curl -s -X POST https://<your magpie>/v1/magpie/keys/oidc \
|
||||
-H "Authorization: Bearer $TOKEN" -d '{"ttl":"30m"}' | jq -r .key)
|
||||
echo "::add-mask::$KEY"
|
||||
echo "MAGPIE_KEY=$KEY" >> "$GITHUB_ENV"</pre>
|
||||
</div>
|
||||
<p>キーはルールのゲートウェイキーの下で発行され、他の発行済みキーと同じくそのキーに縛られ、ルールの期間より長くは有効になりません。名前はリポジトリ、ブランチ、実行番号です。別のリポジトリやブランチのトークン、期限切れ、交換済みのトークンには理由付きの <code>401</code> が返ります。他のコンピューターから使えるのは magpie を共有している間だけで、断られたトークンは認証失敗の回数に数えられます。ルールがなければ何も交換されません。</p>
|
||||
|
||||
<h2 id="api"><a class="anchor" href="#api">統計 API</a></h2>
|
||||
<p>使用量ページの内容は JSON でも、このコンピューターに、また magpie を共有している間はゲートウェイキー付きのリクエストに提供されます。予算、モデル、アカウントで制限されたキーには、自分のリクエストと上限だけが返ります。</p>
|
||||
<ul>
|
||||
|
||||
@@ -78,6 +78,7 @@
|
||||
<a href="#models">What you get</a>
|
||||
<a href="#quotas">Quotas and usage</a>
|
||||
<a href="#keys">Short-lived keys</a>
|
||||
<a href="#oidc">Keys for GitHub Actions</a>
|
||||
<a href="#api">Stats API</a>
|
||||
<a href="#trouble">When it doesn’t work</a>
|
||||
</aside>
|
||||
@@ -156,6 +157,35 @@ magpie gateway-key list <span class="c"># until 10-31 14:00, expir
|
||||
</div>
|
||||
<p>An expired key is refused with <code>401</code> and why (“the gateway key "sandbox-1" expired at …: ask for a new one”) on every API, from this computer too. It is removed an hour later.</p>
|
||||
|
||||
<h2 id="oidc"><a class="anchor" href="#oidc">Keys for GitHub Actions</a></h2>
|
||||
<p>A GitHub Actions job can get a short-lived key without a gateway key in the repository’s secrets: it trades the OIDC token GitHub gives it. Write a rule naming the repository (and, if you like, the branch, environment or any other claim, exact or with <code>*</code>), the gateway key its keys are issued under, and how long they live:</p>
|
||||
<div class="code">
|
||||
<span class="lang">Shell</span>
|
||||
<button class="copy" data-copy="ex-oidc-cli">Copy</button>
|
||||
<pre id="ex-oidc-cli">magpie gateway-key issuer <id> on
|
||||
magpie gateway-key oidc add --key <id> --repo owner/app --ref refs/heads/main --ttl 1h
|
||||
<span class="c"># prints the rule id and its audience, magpie-<rule id></span>
|
||||
magpie gateway-key oidc list
|
||||
magpie gateway-key oidc remove <rule id></pre>
|
||||
</div>
|
||||
<p>In the workflow, ask GitHub for a token with the rule’s audience and POST it to <code>/v1/magpie/keys/oidc</code>:</p>
|
||||
<div class="code">
|
||||
<span class="lang">YAML</span>
|
||||
<button class="copy" data-copy="ex-oidc">Copy</button>
|
||||
<pre id="ex-oidc">permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Get a magpie key
|
||||
run: |
|
||||
TOKEN=$(curl -s -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
|
||||
"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=magpie-<rule id>" | jq -r .value)
|
||||
KEY=$(curl -s -X POST https://<your magpie>/v1/magpie/keys/oidc \
|
||||
-H "Authorization: Bearer $TOKEN" -d '{"ttl":"30m"}' | jq -r .key)
|
||||
echo "::add-mask::$KEY"
|
||||
echo "MAGPIE_KEY=$KEY" >> "$GITHUB_ENV"</pre>
|
||||
</div>
|
||||
<p>The key is issued under the rule’s gateway key and held to it like any other issued key, lives no longer than the rule says, and is named after the repository, branch and run. A token from another repository or branch, an expired one, or one already traded gets <code>401</code> and why. The route answers another computer only while magpie is shared, and refused tokens count against the failed sign-ins it allows. Without a rule nothing is traded.</p>
|
||||
|
||||
<h2 id="api"><a class="anchor" href="#api">Stats API</a></h2>
|
||||
<p>What the Usage page shows is also served as JSON, to this computer and, while magpie is shared, to a request with a gateway key. A key held to a budget, models or accounts is told only its own calls and limit.</p>
|
||||
<ul>
|
||||
|
||||
@@ -78,6 +78,7 @@
|
||||
<a href="#models">能用到什么</a>
|
||||
<a href="#quotas">额度与用量</a>
|
||||
<a href="#keys">短期密钥</a>
|
||||
<a href="#oidc">GitHub Actions 的密钥</a>
|
||||
<a href="#api">统计 API</a>
|
||||
<a href="#trouble">出问题时</a>
|
||||
</aside>
|
||||
@@ -156,6 +157,35 @@ magpie gateway-key list <span class="c"># until 10-31 14:00、expi
|
||||
</div>
|
||||
<p>过期的密钥在每个 API 上都返回 <code>401</code> 并说明原因(“the gateway key "sandbox-1" expired at …: ask for a new one”),本机请求也一样。一小时后它会被删掉。</p>
|
||||
|
||||
<h2 id="oidc"><a class="anchor" href="#oidc">GitHub Actions 的密钥</a></h2>
|
||||
<p>GitHub Actions 的任务不用在仓库 secrets 里放网关密钥,也能拿到短期密钥:用 GitHub 给它的 OIDC token 来换。写一条规则,指定仓库(还可以指定分支、environment 或任意 claim,精确值或带 <code>*</code>)、签发所用的网关密钥和有效期:</p>
|
||||
<div class="code">
|
||||
<span class="lang">Shell</span>
|
||||
<button class="copy" data-copy="ex-oidc-cli">复制</button>
|
||||
<pre id="ex-oidc-cli">magpie gateway-key issuer <id> on
|
||||
magpie gateway-key oidc add --key <id> --repo owner/app --ref refs/heads/main --ttl 1h
|
||||
<span class="c"># 输出规则 id 和它的 audience:magpie-<规则 id></span>
|
||||
magpie gateway-key oidc list
|
||||
magpie gateway-key oidc remove <rule id></pre>
|
||||
</div>
|
||||
<p>在 workflow 里向 GitHub 要一个带规则 audience 的 token,POST 到 <code>/v1/magpie/keys/oidc</code>:</p>
|
||||
<div class="code">
|
||||
<span class="lang">YAML</span>
|
||||
<button class="copy" data-copy="ex-oidc">复制</button>
|
||||
<pre id="ex-oidc">permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Get a magpie key
|
||||
run: |
|
||||
TOKEN=$(curl -s -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
|
||||
"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=magpie-<rule id>" | jq -r .value)
|
||||
KEY=$(curl -s -X POST https://<your magpie>/v1/magpie/keys/oidc \
|
||||
-H "Authorization: Bearer $TOKEN" -d '{"ttl":"30m"}' | jq -r .key)
|
||||
echo "::add-mask::$KEY"
|
||||
echo "MAGPIE_KEY=$KEY" >> "$GITHUB_ENV"</pre>
|
||||
</div>
|
||||
<p>换到的密钥由规则里的网关密钥签发,和其他签发的密钥一样受它约束,有效期不超过规则所写,名字是仓库、分支和运行编号。其他仓库或分支的 token、过期的 token、已经换过的 token 会收到 <code>401</code> 和原因。只有 magpie 共享时其他电脑才能调用这个接口,被拒的 token 计入失败认证次数。没有规则就什么都换不到。</p>
|
||||
|
||||
<h2 id="api"><a class="anchor" href="#api">统计 API</a></h2>
|
||||
<p>用量页上的内容也以 JSON 提供给本机;共享 magpie 时,也提供给带网关密钥的请求。受预算、模型或账号限制的密钥只能看到自己的请求和限额。</p>
|
||||
<ul>
|
||||
|
||||
Reference in New Issue
Block a user