Exchanger trades a user's access token, as a confidential client with its secret in a Basic header, for one at another yaiam client (yaiam ADR-0045): Exchange(ctx, subject, audience, scopes...) and Revoke for the end of an agent's job. Only access tokens are asked for and taken. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
151 lines
5.3 KiB
Go
151 lines
5.3 KiB
Go
package yaiam
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
// exchangeServer is a fake provider's token exchange: it answers with
|
|
// answer (or the OAuth error code refuse) and records what it got.
|
|
type exchangeServer struct {
|
|
ts *httptest.Server
|
|
issuer string
|
|
mu sync.Mutex
|
|
forms []url.Values
|
|
basic []string
|
|
refuse string
|
|
answer map[string]any
|
|
revoked []url.Values
|
|
}
|
|
|
|
func newExchangeServer(t *testing.T) *exchangeServer {
|
|
s := &exchangeServer{answer: map[string]any{"access_token": "exchanged", "token_type": "Bearer", "expires_in": 300,
|
|
"issued_token_type": tokenTypeAccess, "scope": "openid"}}
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /t/default/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
|
json.NewEncoder(w).Encode(map[string]string{"issuer": s.issuer, "token_endpoint": s.ts.URL + "/token",
|
|
"revocation_endpoint": s.ts.URL + "/revoke"})
|
|
})
|
|
record := func(r *http.Request) url.Values {
|
|
r.ParseForm()
|
|
id, secret, _ := r.BasicAuth()
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.basic = append(s.basic, id+":"+secret)
|
|
return r.PostForm
|
|
}
|
|
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
|
|
form := record(r)
|
|
s.mu.Lock()
|
|
s.forms = append(s.forms, form)
|
|
refuse, answer := s.refuse, s.answer
|
|
s.mu.Unlock()
|
|
if refuse != "" {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
fmt.Fprintf(w, `{"error":%q}`, refuse)
|
|
return
|
|
}
|
|
json.NewEncoder(w).Encode(answer)
|
|
})
|
|
mux.HandleFunc("POST /revoke", func(w http.ResponseWriter, r *http.Request) {
|
|
form := record(r)
|
|
s.mu.Lock()
|
|
s.revoked = append(s.revoked, form)
|
|
s.mu.Unlock()
|
|
})
|
|
s.ts = httptest.NewServer(mux)
|
|
t.Cleanup(s.ts.Close)
|
|
s.issuer = s.ts.URL + "/t/default"
|
|
return s
|
|
}
|
|
|
|
// TestExchange: the request RFC 8693 asks for, with the client's secret
|
|
// in a Basic header and the user's token only in the body; the answer
|
|
// becomes a Token without a refresh token; Revoke ends only it.
|
|
func TestExchange(t *testing.T) {
|
|
s := newExchangeServer(t)
|
|
e := &Exchanger{Client: Client{Issuer: s.issuer, ClientID: "yaais"}, ClientSecret: "s3cret:/&"}
|
|
tok, err := e.Exchange(context.Background(), "users-token", "yakpo", "openid", "profile")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if tok.AccessToken != "exchanged" || tok.RefreshToken != "" || tok.ClientID != "yaais" || tok.Scope != "openid" || tok.Expiry.IsZero() {
|
|
t.Errorf("token = %#v", tok)
|
|
}
|
|
f := s.forms[0]
|
|
for k, want := range map[string]string{"grant_type": grantTokenExchange, "subject_token": "users-token",
|
|
"subject_token_type": tokenTypeAccess, "requested_token_type": tokenTypeAccess, "audience": "yakpo", "scope": "openid profile"} {
|
|
if f.Get(k) != want {
|
|
t.Errorf("%s = %q, want %q", k, f.Get(k), want)
|
|
}
|
|
}
|
|
if f.Has("client_secret") || s.basic[0] != "yaais:"+url.QueryEscape("s3cret:/&") {
|
|
t.Errorf("client authentication: form %v, basic %q", f, s.basic[0])
|
|
}
|
|
if strings.Contains(fmt.Sprint(tok), "exchanged") {
|
|
t.Error("the token prints its access token")
|
|
}
|
|
|
|
if _, err := e.Exchange(context.Background(), "users-token", "yakpo"); err != nil || s.forms[1].Has("scope") {
|
|
t.Errorf("no scopes: %v, %v", err, s.forms[1])
|
|
}
|
|
if err := e.Revoke(context.Background(), tok); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if r := s.revoked[0]; r.Get("token") != "exchanged" || r.Get("token_type_hint") != "access_token" || s.basic[len(s.basic)-1] == ":" {
|
|
t.Errorf("revoked %v", r)
|
|
}
|
|
}
|
|
|
|
// TestExchangeRefused: an OAuth error comes back as *Error with its
|
|
// code; an answer that is not an access token, no secret or no audience
|
|
// are errors before or after the request.
|
|
func TestExchangeRefused(t *testing.T) {
|
|
s := newExchangeServer(t)
|
|
e := &Exchanger{Client: Client{Issuer: s.issuer, ClientID: "yaais"}, ClientSecret: "secret"}
|
|
s.refuse = "invalid_target"
|
|
var oe *Error
|
|
if _, err := e.Exchange(context.Background(), "t", "yakpo"); !errors.As(err, &oe) || oe.Code != "invalid_target" {
|
|
t.Errorf("refused: %v", err)
|
|
}
|
|
s.refuse = ""
|
|
for name, mod := range map[string]func(map[string]any){
|
|
"an ID token": func(a map[string]any) { a["issued_token_type"] = "urn:ietf:params:oauth:token-type:id_token" },
|
|
"no type": func(a map[string]any) { delete(a, "issued_token_type") },
|
|
"no lifetime": func(a map[string]any) { delete(a, "expires_in") },
|
|
"not bearer": func(a map[string]any) { a["token_type"] = "N_A" },
|
|
"no access token": func(a map[string]any) { delete(a, "access_token") },
|
|
} {
|
|
s.answer = map[string]any{"access_token": "x", "token_type": "Bearer", "expires_in": 300, "issued_token_type": tokenTypeAccess}
|
|
mod(s.answer)
|
|
if _, err := e.Exchange(context.Background(), "t", "yakpo"); err == nil {
|
|
t.Errorf("%s: accepted", name)
|
|
}
|
|
}
|
|
n := len(s.forms)
|
|
if _, err := e.Exchange(context.Background(), "t", ""); err == nil {
|
|
t.Error("no audience")
|
|
}
|
|
if _, err := e.Exchange(context.Background(), "", "yakpo"); err == nil {
|
|
t.Error("no subject token")
|
|
}
|
|
noSecret := &Exchanger{Client: Client{Issuer: s.issuer, ClientID: "yaais"}}
|
|
if _, err := noSecret.Exchange(context.Background(), "t", "yakpo"); err == nil {
|
|
t.Error("no secret")
|
|
}
|
|
if len(s.forms) != n {
|
|
t.Errorf("%d requests sent for refused calls", len(s.forms)-n)
|
|
}
|
|
if err := e.Revoke(context.Background(), nil); err != nil {
|
|
t.Errorf("revoking nothing: %v", err)
|
|
}
|
|
}
|