Skip to content

Commit 0877906

Browse files
authored
Add ate-idp-server to serve the discovery document and key set for actor JWTs (agent-substrate#2099)
Part of agent-substrate#1756. - Adds `cmd/ate-idp-server`, which serves `/.well-known/openid-configuration` and `/openid/v1/jwks` over HTTPS with a servicedns credential bundle, so relying parties can verify actor JWTs. - Reads the actor JWT authority pool from `--actor-id-jwt-pool` with `localjwtauthority.RefreshingPool`, the reader ate-api-server signs with, and builds each document from it per request. - Builds both documents at startup and exits if it can't. After that, a request whose document can't be built gets a 500 rather than an empty or stale set. - Requires `--issuer` rather than deriving a default, so it can't disagree with ateapi, and accepts only `https://<host>`, so the routes are fixed. The check is the new `actoridjwt.ValidateIssuer`; the discovery document moves out of `internal/oidcdiscovery` into the server, its only user. - Makes the EC case in `localjwtauthority.JWKS` explicit: P-256 with fixed 32-byte coordinates and an error for any other curve, rather than reading the coordinate size off the encoded point. - Records in `docs/metrics/substrate.yaml` that it emits no metrics. For reviewers: the pool holds the signing keys, so ate-idp-server will mount the same Secret ate-api-server does, in place of the controller and ConfigMap in agent-substrate#2134. ate-api-server and ate-setup still accept an issuer with a path until the installer deploys ate-idp-server. It serves `/healthz` but no `/readyz`. Nothing deploys it yet. Testing: unit tests for routing, the host-only issuer check, the discovery document, startup failures, key changes, 500s on a broken set, the P-256 encoding, and required flags, plus a local run over TLS against a generated pool. E2E can't cover it until it's deployed. - [ ] Tests pass - [ ] Appropriate changes to documentation are included in the PR
1 parent 3a2ca62 commit 0877906

11 files changed

Lines changed: 628 additions & 187 deletions

File tree

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
// Copyright 2026 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
// Package server serves the actor JWT issuer's OpenID discovery document and
16+
// JWK set.
17+
package server
18+
19+
import (
20+
"encoding/json"
21+
"fmt"
22+
"log/slog"
23+
"net/http"
24+
"slices"
25+
26+
"go.ate.dev/substrate/internal/actoridjwt"
27+
"go.ate.dev/substrate/internal/localjwtauthority"
28+
)
29+
30+
// KeySource supplies the verification keys to publish.
31+
// *localjwtauthority.RefreshingPool is one.
32+
type KeySource interface {
33+
VerificationKeys() ([]*localjwtauthority.VerificationKey, error)
34+
}
35+
36+
// Server serves the discovery document at /.well-known/openid-configuration
37+
// and the JWK set at /openid/v1/jwks, plus /healthz. It builds both documents
38+
// from its KeySource on every request and answers 500 when that fails.
39+
type Server struct {
40+
issuer string
41+
keys KeySource
42+
}
43+
44+
// New returns a Server that publishes keys for issuer, which must be
45+
// https://<host>. It fails if the keys cannot be published.
46+
func New(issuer string, keys KeySource) (*Server, error) {
47+
if err := actoridjwt.ValidateIssuer(issuer); err != nil {
48+
return nil, err
49+
}
50+
s := &Server{issuer: issuer, keys: keys}
51+
if _, _, err := s.build(); err != nil {
52+
return nil, fmt.Errorf("cannot publish the keys: %w", err)
53+
}
54+
return s, nil
55+
}
56+
57+
// Register adds the server's routes to mux.
58+
func (s *Server) Register(mux *http.ServeMux) {
59+
mux.HandleFunc("GET /.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
60+
discovery, _, err := s.build()
61+
serveDocument(w, r, discovery, err)
62+
})
63+
mux.HandleFunc("GET /openid/v1/jwks", func(w http.ResponseWriter, r *http.Request) {
64+
_, jwks, err := s.build()
65+
serveDocument(w, r, jwks, err)
66+
})
67+
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
68+
w.WriteHeader(http.StatusOK)
69+
})
70+
}
71+
72+
type discoveryDocument struct {
73+
Issuer string `json:"issuer"`
74+
JWKSURI string `json:"jwks_uri"`
75+
ResponseTypesSupported []string `json:"response_types_supported"`
76+
SubjectTypesSupported []string `json:"subject_types_supported"`
77+
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
78+
ClaimsSupported []string `json:"claims_supported"`
79+
}
80+
81+
func (s *Server) build() (discovery, jwks []byte, err error) {
82+
verificationKeys, err := s.keys.VerificationKeys()
83+
if err != nil {
84+
return nil, nil, fmt.Errorf("reading verification keys: %w", err)
85+
}
86+
if jwks, err = localjwtauthority.JWKS(verificationKeys); err != nil {
87+
return nil, nil, err
88+
}
89+
algorithms := make([]string, 0, len(verificationKeys))
90+
for _, vk := range verificationKeys {
91+
algorithms = append(algorithms, vk.Algorithm)
92+
}
93+
slices.Sort(algorithms)
94+
discovery, err = json.Marshal(discoveryDocument{
95+
Issuer: s.issuer,
96+
JWKSURI: s.issuer + "/openid/v1/jwks",
97+
ResponseTypesSupported: []string{"id_token"},
98+
SubjectTypesSupported: []string{"public"},
99+
IDTokenSigningAlgValuesSupported: slices.Compact(algorithms),
100+
ClaimsSupported: []string{"iss", "sub", "aud", "exp", "nbf", "iat", "jti", "actor.ate.dev", "worker-for-actor.ate.dev"},
101+
})
102+
if err != nil {
103+
return nil, nil, err
104+
}
105+
return discovery, jwks, nil
106+
}
107+
108+
func serveDocument(w http.ResponseWriter, r *http.Request, doc []byte, err error) {
109+
if err != nil {
110+
slog.ErrorContext(r.Context(), "Cannot publish the actor JWT keys", slog.Any("err", err))
111+
http.Error(w, "cannot publish the key set", http.StatusInternalServerError)
112+
return
113+
}
114+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
115+
_, _ = w.Write(doc)
116+
}
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
// Copyright 2026 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package server
16+
17+
import (
18+
"encoding/json"
19+
"net/http"
20+
"net/http/httptest"
21+
"os"
22+
"path/filepath"
23+
"sync"
24+
"testing"
25+
26+
"github.com/google/go-cmp/cmp"
27+
28+
"go.ate.dev/substrate/internal/localjwtauthority"
29+
)
30+
31+
// fakeKeys is a KeySource whose keys and error a test can change.
32+
type fakeKeys struct {
33+
mu sync.Mutex
34+
keys []*localjwtauthority.VerificationKey
35+
err error
36+
}
37+
38+
func (f *fakeKeys) VerificationKeys() ([]*localjwtauthority.VerificationKey, error) {
39+
f.mu.Lock()
40+
defer f.mu.Unlock()
41+
return f.keys, f.err
42+
}
43+
44+
func (f *fakeKeys) set(keys []*localjwtauthority.VerificationKey, err error) {
45+
f.mu.Lock()
46+
defer f.mu.Unlock()
47+
f.keys, f.err = keys, err
48+
}
49+
50+
// verificationKeys generates one key per algorithm.
51+
func verificationKeys(t *testing.T, algorithms ...string) []*localjwtauthority.VerificationKey {
52+
t.Helper()
53+
pool := &localjwtauthority.ConcretePool{}
54+
for _, alg := range algorithms {
55+
authority, err := localjwtauthority.GenerateAuthority(alg, "")
56+
if err != nil {
57+
t.Fatal(err)
58+
}
59+
pool.Authorities = append(pool.Authorities, authority)
60+
}
61+
keys, err := pool.VerificationKeys()
62+
if err != nil {
63+
t.Fatal(err)
64+
}
65+
return keys
66+
}
67+
68+
func keySet(t *testing.T, keys []*localjwtauthority.VerificationKey) string {
69+
t.Helper()
70+
jwks, err := localjwtauthority.JWKS(keys)
71+
if err != nil {
72+
t.Fatal(err)
73+
}
74+
return string(jwks)
75+
}
76+
77+
func newServer(t *testing.T, issuer string, keys KeySource) http.Handler {
78+
t.Helper()
79+
s, err := New(issuer, keys)
80+
if err != nil {
81+
t.Fatal(err)
82+
}
83+
mux := http.NewServeMux()
84+
s.Register(mux)
85+
return mux
86+
}
87+
88+
func get(h http.Handler, method, target string) *httptest.ResponseRecorder {
89+
w := httptest.NewRecorder()
90+
h.ServeHTTP(w, httptest.NewRequest(method, target, nil))
91+
return w
92+
}
93+
94+
func TestServesDocuments(t *testing.T) {
95+
keys := verificationKeys(t, "ES256")
96+
s := newServer(t, "https://idp.ate-system.svc", &fakeKeys{keys: keys})
97+
tests := []struct {
98+
target string
99+
want string
100+
}{
101+
{
102+
target: "/.well-known/openid-configuration",
103+
want: `{"issuer":"https://idp.ate-system.svc",` +
104+
`"jwks_uri":"https://idp.ate-system.svc/openid/v1/jwks",` +
105+
`"response_types_supported":["id_token"],` +
106+
`"subject_types_supported":["public"],` +
107+
`"id_token_signing_alg_values_supported":["ES256"],` +
108+
`"claims_supported":["iss","sub","aud","exp","nbf","iat","jti","actor.ate.dev","worker-for-actor.ate.dev"]}`,
109+
},
110+
{target: "/openid/v1/jwks", want: keySet(t, keys)},
111+
}
112+
for _, tt := range tests {
113+
w := get(s, http.MethodGet, tt.target)
114+
if w.Code != http.StatusOK {
115+
t.Fatalf("GET %s = %d, want 200", tt.target, w.Code)
116+
}
117+
if diff := cmp.Diff(tt.want, w.Body.String()); diff != "" {
118+
t.Errorf("GET %s body (-want +got):\n%s", tt.target, diff)
119+
}
120+
if got := w.Header().Get("Content-Type"); got != "application/json; charset=utf-8" {
121+
t.Errorf("GET %s: Content-Type = %q, want application/json; charset=utf-8", tt.target, got)
122+
}
123+
}
124+
}
125+
126+
func TestNewFails(t *testing.T) {
127+
keys := verificationKeys(t, "ES256")
128+
tests := map[string]struct {
129+
issuer string
130+
keys KeySource
131+
}{
132+
"issuer not https": {issuer: "http://idp.ate-system.svc", keys: &fakeKeys{keys: keys}},
133+
"issuer with path": {issuer: "https://idp.example.com/prod", keys: &fakeKeys{keys: keys}},
134+
"keys unreadable": {issuer: "https://idp.ate-system.svc", keys: &fakeKeys{err: os.ErrNotExist}},
135+
"no keys": {issuer: "https://idp.ate-system.svc", keys: &fakeKeys{}},
136+
}
137+
for name, tt := range tests {
138+
if _, err := New(tt.issuer, tt.keys); err == nil {
139+
t.Errorf("%s: New returned nil error", name)
140+
}
141+
}
142+
}
143+
144+
func TestFollowsKeyChanges(t *testing.T) {
145+
first := verificationKeys(t, "ES256")
146+
keys := &fakeKeys{keys: first}
147+
s := newServer(t, "https://idp.ate-system.svc", keys)
148+
if got, want := get(s, http.MethodGet, "/openid/v1/jwks").Body.String(), keySet(t, first); got != want {
149+
t.Fatalf("served key set = %q, want %q", got, want)
150+
}
151+
152+
rotated := append(verificationKeys(t, "RS256"), first...)
153+
keys.set(rotated, nil)
154+
if got, want := get(s, http.MethodGet, "/openid/v1/jwks").Body.String(), keySet(t, rotated); got != want {
155+
t.Errorf("after rotation: served key set = %q, want %q", got, want)
156+
}
157+
158+
for name, change := range map[string]func(){
159+
"read error": func() { keys.set(nil, os.ErrNotExist) },
160+
"empty pool": func() { keys.set(nil, nil) },
161+
} {
162+
change()
163+
for _, target := range []string{"/.well-known/openid-configuration", "/openid/v1/jwks"} {
164+
if got := get(s, http.MethodGet, target).Code; got != http.StatusInternalServerError {
165+
t.Errorf("after %s: GET %s = %d, want 500", name, target, got)
166+
}
167+
}
168+
}
169+
}
170+
171+
func TestDiscoveryAdvertisesPoolAlgorithms(t *testing.T) {
172+
s := newServer(t, "https://idp.ate-system.svc", &fakeKeys{keys: verificationKeys(t, "RS256", "ES256", "ES256")})
173+
var doc struct {
174+
Algorithms []string `json:"id_token_signing_alg_values_supported"`
175+
}
176+
if err := json.Unmarshal(get(s, http.MethodGet, "/.well-known/openid-configuration").Body.Bytes(), &doc); err != nil {
177+
t.Fatal(err)
178+
}
179+
if diff := cmp.Diff([]string{"ES256", "RS256"}, doc.Algorithms); diff != "" {
180+
t.Errorf("algorithms (-want +got):\n%s", diff)
181+
}
182+
}
183+
184+
func TestMethodsAndUnknownPaths(t *testing.T) {
185+
s := newServer(t, "https://idp.ate-system.svc", &fakeKeys{keys: verificationKeys(t, "ES256")})
186+
187+
if got := get(s, http.MethodGet, "/healthz").Code; got != http.StatusOK {
188+
t.Errorf("GET /healthz = %d, want 200", got)
189+
}
190+
191+
if got := get(s, http.MethodHead, "/openid/v1/jwks").Code; got != http.StatusOK {
192+
t.Errorf("HEAD = %d, want 200", got)
193+
}
194+
195+
w := get(s, http.MethodPost, "/openid/v1/jwks")
196+
if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" {
197+
t.Errorf("POST = %d, Allow %q; want 405, Allow GET, HEAD", w.Code, w.Header().Get("Allow"))
198+
}
199+
200+
if got := get(s, http.MethodGet, "/openid/v1/other").Code; got != http.StatusNotFound {
201+
t.Errorf("GET unknown path = %d, want 404", got)
202+
}
203+
}
204+
205+
func TestPublishesRefreshingPool(t *testing.T) {
206+
wire, keyID, err := localjwtauthority.GeneratePool("ES256", "")
207+
if err != nil {
208+
t.Fatal(err)
209+
}
210+
file := filepath.Join(t.TempDir(), "pool.json")
211+
if err := os.WriteFile(file, wire, 0o600); err != nil {
212+
t.Fatal(err)
213+
}
214+
pool, err := localjwtauthority.NewRefreshingPool(file)
215+
if err != nil {
216+
t.Fatal(err)
217+
}
218+
s := newServer(t, "https://idp.ate-system.svc", pool)
219+
220+
var set struct {
221+
Keys []map[string]string `json:"keys"`
222+
}
223+
if err := json.Unmarshal(get(s, http.MethodGet, "/openid/v1/jwks").Body.Bytes(), &set); err != nil {
224+
t.Fatal(err)
225+
}
226+
if len(set.Keys) != 1 {
227+
t.Fatalf("served %d keys, want 1", len(set.Keys))
228+
}
229+
if k := set.Keys[0]; k["kid"] != keyID || k["alg"] != "ES256" || k["d"] != "" {
230+
t.Errorf("served key %v; want kid %q, alg ES256, and no private key", k, keyID)
231+
}
232+
}

0 commit comments

Comments
 (0)