5 Commits
Author SHA1 Message Date
terminarandClaude Opus 5.5 c2a5e3928a feat(yaiam): refresh and revoke a web sign-in's tokens
Web.Refresh trades the refresh token from an offline_access sign-in for
the next access token, authenticating a confidential client with its
secret (Client.Refresh only sends client_id). Web.Revoke ends the refresh
and access token at sign-out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 00:03:17 +01:00
terminarandClaude Opus 5.5 560a1ead8a feat(yaiam): token exchange for a user's token at another service (RFC 8693)
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>
2026-11-21 19:27:57 +01:00
terminarandClaude Opus 5.5 76543b23a0 fix(yaiam): check the sign-in cookie and state before discovery
A callback that belongs to no sign-in of this browser is now
ErrSignInState without contacting the provider (before, an unreachable
provider turned it into a discovery error).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:35:15 +01:00
terminarandClaude Opus 5.5 376ae3c970 feat(yaiam): web sign-in at any OIDC provider behind another name
Web.PublicIssuer sends the browser to the provider's endpoints on a
public origin while the server keeps Issuer (container networks); the
callback's iss may name either. Client.AllowInsecure accepts plain http
off loopback for test installations on a closed network. email_verified
counts only as the JSON boolean true; a string no longer fails the
sign-in. First consumer: yaemp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:32:32 +01:00
terminarandClaude Opus 5.5 538a6c8ae6 yaiam: user attributes in SignedIn and User (ADR-0044)
Web asks for the scope attributes; SignedIn.Attributes carries the
attributes yaiam released to the application (from UserInfo), and
Admin's User carries a user's attributes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:16:32 +01:00
13 changed files with 672 additions and 30 deletions

No files matched your search

+2 -1
View File
@@ -55,7 +55,8 @@ return without the state check. Client secrets (`Web`, `Admin`) go only
in the Authorization header to the token endpoint. Servers check tokens
with yaiam's `pkg/httpauth`. Never log a token or put one into an error, never follow
a redirect with one, never accept an endpoint that is not https (http
only on loopback), and never send a stored token to another issuer or
only on loopback, or anywhere with the explicit `AllowInsecure` of a test
installation), and never send a stored token to another issuer or
client than the one it came from. Tests use a fake provider
(`httptest`); the end-to-end test against a real yaiam-authd is in
yaiam (`internal/oidcprovider/devicelogin_test.go`).
+41 -1
View File
@@ -14,7 +14,7 @@ Today it holds the Atlassian clients that `yareco`, `yabaratla` and
| `atlassian/jira` | Jira REST API client (Cloud v3 and Server/Data Center v2) |
| `atlassian/confluence` | small Confluence REST API client (classic content API) |
| `atlassian/internal/transport` | the HTTP machinery both share; not importable from outside |
| `yaiam` | sign a command-line program in at yaiam (device flow, RFC 8628) and keep its tokens (YAIAM-710, 2026-11-09); sign a web application's users in (code flow with PKCE) and read users and groups from yaiam's admin API (2026-11-17) |
| `yaiam` | sign a command-line program in at yaiam (device flow, RFC 8628) and keep its tokens (YAIAM-710, 2026-11-09); sign a web application's users in (code flow with PKCE) and read users and groups from yaiam's admin API (2026-11-17); trade a user's token for one at another service, for an agent (token exchange, RFC 8693, 2026-11-21); refresh and revoke a web sign-in's tokens (2026-11-28) |
Standard library only, no third-party dependencies.
@@ -170,6 +170,20 @@ out, _ := web.LogoutURL(ctx, u.IDToken)
and roles come from UserInfo, which must name the same subject.
- The application keeps its own session and its own data under
`Subject` -- it stays when the user is renamed.
- Any OpenID Connect provider works, not only yaiam: set `Scopes` to
what it offers (e.g. `openid email profile`; the default asks for
yaiam's groups, roles and attributes). `EmailVerified` is true only
for the JSON boolean `true` (some providers send the string).
- `PublicIssuer`: when the application reaches the provider under
another name than the browser does (a container network), the browser
is sent to the endpoints on the public origin; the server keeps
`Issuer`. `AllowInsecure` (on `Client`) accepts plain http off
loopback, for a test installation on a closed network only.
- With `offline_access` in `Scopes` the sign-in's `Token` has a refresh
token: `web.Refresh(ctx, tok)` gets the next access token (client
secret in a Basic header for a confidential client; keep the result,
its refresh token replaces the old one; a refused one is
`ErrLoginRequired`), and `web.Revoke(ctx, tok)` ends both at sign-out.
`Admin` reads a tenant's users, groups and group members from yaiam's
admin API with a service client's token (client credentials, cached
@@ -179,6 +193,32 @@ An example web application is yaiam's `examples/webapp`; an end-to-end
test against a real yaiam-authd is yaiam's
`internal/oidcprovider/weblogin_test.go`.
### Acting for a user: token exchange
A confidential client that holds a user's access token -- an
application, a gateway, an agent runner like yaais -- trades it for one
at another client of yaiam, on behalf of the same user (RFC 8693, yaiam
ADR-0045). The target has to allow it (`yaiam-ctl client exchange-from
<target> <this client>`):
```go
x := &yaiam.Exchanger{
Client: yaiam.Client{Issuer: "https://login.example.org/t/default", ClientID: yaaisID},
ClientSecret: secret, // its token endpoint auth method is basic
}
agent, err := x.Exchange(ctx, usersAccessToken, yakpoClientID) // optional: fewer scopes
// ... the agent calls yakpo with agent.AccessToken ...
x.Revoke(ctx, agent) // at the end of its job: only this token ends
```
The new token names the user (`sub`), this client (`client_id`,
`act.sub`) and the target alone (`aud`). It has no refresh token and
ends no later than the user's token; when that one ends (revoked, the
consent withdrawn), so does the exchanged one. Give an agent the
exchanged token, never the user's. The user's token may be one issued to
this client or one another client got for it as its audience (an MCP
client calling a gateway).
## Versioning
A release is a plain semver git tag (`v0.1.0`, ...) on this repository;
+6
View File
@@ -12,6 +12,12 @@
endpoint over TLS (OpenID Connect Core 3.1.3.7), profile and groups
from UserInfo; `Admin` for the admin API. The application keeps its
own session. yaiam's `examples/webapp` uses it; yasta and yaais can.
- [x] **yaiam: any OpenID Connect provider for a web sign-in**
(2026-11-20, first consumer yaemp, replacing go-oidc/oauth2):
`Web.PublicIssuer` (the browser reaches the provider under another
origin), `Client.AllowInsecure` (http off loopback, test installations
only), `email_verified` true only as JSON boolean; `Callback` checks
the cookie and state before it contacts the provider (v0.5.1).
- [ ] **yaiam: web refresh.** `Web` has no refresh for a confidential
client (Client.Refresh sends no secret); add when an application keeps
access tokens beyond the sign-in.
+4 -1
View File
@@ -70,6 +70,9 @@ type User struct {
Locale string `json:"locale"`
TimeZone string `json:"time_zone"`
State string `json:"state"`
// Attributes are the user's attributes by name (department,
// cost_center, ...); none with a yaiam before them.
Attributes map[string]string `json:"attributes"`
}
// Users lists the tenant's users.
@@ -150,7 +153,7 @@ func (a *Admin) token(ctx context.Context) (string, error) {
// get asks the API for path below the tenant and decodes the answer.
// A refused token is fetched again once.
func (a *Admin) get(ctx context.Context, path string, out any) error {
if err := checkURL("admin API", a.API); err != nil {
if err := checkURL("admin API", a.API, a.AllowInsecure); err != nil {
return err
}
if a.Tenant == "" || strings.ContainsAny(a.Tenant, "/?#") {
+2 -2
View File
@@ -57,7 +57,7 @@ func newAdminFake(t *testing.T) *adminFake {
case "users":
fmt.Fprint(w, `{"items":[{"id":"u-1","ref":"alice","username":"alice","display_name":"Alice","user_state":"active","home":true}]}`)
case "users/alice":
fmt.Fprint(w, `{"id":"u-1","username":"alice","display_name":"Alice","email":"alice@example.org","email_verified":true,"state":"active"}`)
fmt.Fprint(w, `{"id":"u-1","username":"alice","display_name":"Alice","email":"alice@example.org","email_verified":true,"state":"active","attributes":{"department":"IT"}}`)
case "groups":
fmt.Fprint(w, `{"items":[{"id":"g-1","name":"staff","protected":false}]}`)
case "groups/staff/members":
@@ -88,7 +88,7 @@ func TestAdmin(t *testing.T) {
t.Fatalf("users %+v, %v", users, err)
}
u, err := a.User(ctx, "alice")
if err != nil || u.Email != "alice@example.org" || !u.EmailVerified {
if err != nil || u.Email != "alice@example.org" || !u.EmailVerified || u.Attributes["department"] != "IT" {
t.Errorf("user %+v, %v", u, err)
}
groups, err := a.Groups(ctx)
+2 -2
View File
@@ -55,11 +55,11 @@ func (c *Client) StartDevice(ctx context.Context) (*DeviceAuth, error) {
return nil, errors.New("yaiam: device_authorization: incomplete answer")
}
// The user opens these pages: only ones of the provider's kind.
if err := checkURL("verification_uri", out.VerificationURI); err != nil {
if err := checkURL("verification_uri", out.VerificationURI, c.AllowInsecure); err != nil {
return nil, err
}
if out.VerificationURIComplete != "" {
if err := checkURL("verification_uri_complete", out.VerificationURIComplete); err != nil {
if err := checkURL("verification_uri_complete", out.VerificationURIComplete, c.AllowInsecure); err != nil {
return nil, err
}
}
+110
View File
@@ -0,0 +1,110 @@
package yaiam
// Token exchange (RFC 8693; yaiam ADR-0045): a confidential client --
// an application, a gateway, an agent runner -- that holds a user's
// access token trades it for one at another client of yaiam, on behalf
// of the same user. The target has to allow it ("yaiam-ctl client
// exchange-from <target> <this client>"). The new token names the user
// (sub), this client (client_id, act.sub) and the target alone (aud); it
// has no refresh token and ends no later than the token it came from.
// For an agent: hand it the exchanged token, never the user's, and
// revoke it when its job ends (Revoke).
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
)
const (
grantTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"
tokenTypeAccess = "urn:ietf:params:oauth:token-type:access_token"
)
// Exchanger trades users' access tokens as one confidential client. Its
// fields must not change once it is in use; use it by pointer; it is
// safe for concurrent use.
type Exchanger struct {
// Client holds the issuer (the tenant's), this client's ID and the
// HTTP client. Its Scopes are not used.
Client
// ClientSecret is this client's secret, sent in an HTTP Basic header
// (its token endpoint auth method has to be basic).
ClientSecret string
}
// Exchange trades the user's access token subject -- issued to this
// client, or to another one for this client as its audience -- for an
// access token at the client audience (the target's client ID). scopes
// narrow it; none means every scope the token can carry there. A refused
// exchange is an *Error: invalid_target when the target does not take
// this client's tokens or the user may not use it, invalid_request for a
// subject token yaiam does not exchange, invalid_scope for a scope it
// cannot carry.
func (e *Exchanger) Exchange(ctx context.Context, subject, audience string, scopes ...string) (*Token, error) {
if subject == "" || audience == "" {
return nil, errors.New("yaiam: token exchange: a subject token and an audience are needed")
}
m, err := e.discover(ctx)
if err != nil {
return nil, err
}
form := url.Values{"grant_type": {grantTokenExchange}, "subject_token": {subject},
"subject_token_type": {tokenTypeAccess}, "requested_token_type": {tokenTypeAccess}, "audience": {audience}}
if len(scopes) > 0 {
form.Set("scope", strings.Join(scopes, " "))
}
var out struct {
AccessToken string `json:"access_token"`
IssuedTokenType string `json:"issued_token_type"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}
if err := e.postBasic(ctx, "token", m.TokenEndpoint, form, &out); err != nil {
return nil, err
}
if out.AccessToken == "" || out.IssuedTokenType != tokenTypeAccess || !strings.EqualFold(out.TokenType, "Bearer") || out.ExpiresIn <= 0 {
return nil, errors.New("yaiam: token exchange: no bearer access token with a lifetime in the answer")
}
return &Token{Issuer: e.Issuer, ClientID: e.ClientID, AccessToken: out.AccessToken,
Expiry: time.Now().Add(time.Duration(out.ExpiresIn) * time.Second), Scope: out.Scope}, nil
}
// Revoke ends an exchanged token t (RFC 7009) -- an agent's at the end of
// its job. Only that token ends; the user's token it came from stays.
func (e *Exchanger) Revoke(ctx context.Context, t *Token) error {
if t == nil || t.AccessToken == "" {
return nil
}
m, err := e.discover(ctx)
if err != nil {
return err
}
if m.RevocationEndpoint == "" {
return errors.New("yaiam: the provider offers no revocation")
}
return e.postBasic(ctx, "revocation", m.RevocationEndpoint,
url.Values{"token": {t.AccessToken}, "token_type_hint": {"access_token"}}, nil)
}
// postBasic is post with this client's ID and secret in a Basic header
// (RFC 6749 §2.3.1: both form-encoded first).
func (e *Exchanger) postBasic(ctx context.Context, name, endpoint string, form url.Values, out any) error {
if e.ClientSecret == "" {
return fmt.Errorf("yaiam: %s: no client secret", name)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(url.QueryEscape(e.ClientID), url.QueryEscape(e.ClientSecret))
return e.send(name, req, out)
}
+150
View File
@@ -0,0 +1,150 @@
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)
}
}
+60 -14
View File
@@ -31,9 +31,11 @@ import (
)
// WebScopes are asked for when Web.Scopes is nil: who the user is, their
// address, and their groups and roles at yaiam (the client must be
// allowed "groups" and "roles").
var WebScopes = []string{"openid", "profile", "email", "groups", "roles"}
// address, their groups and roles at yaiam (the client must be allowed
// "groups" and "roles") and the user attributes released to the client
// (yaiam allows "attributes" once some are). A scope the client is not
// allowed is left out, not refused.
var WebScopes = []string{"openid", "profile", "email", "groups", "roles", "attributes"}
// signInLifetime is how long a started sign-in may take.
const signInLifetime = 10 * time.Minute
@@ -69,6 +71,14 @@ type Web struct {
// PostLogoutRedirectURL is where the provider sends the browser
// after a sign-out (registered at the client); "" for none.
PostLogoutRedirectURL string
// PublicIssuer is the issuer URL as the browser reaches it, when this
// application reaches the provider under another name (a container
// network: Issuer "http://oidc:8080/default", PublicIssuer
// "http://localhost:8180/default"): the same path on another origin.
// The endpoints the browser is sent to (authorization, end session)
// that are on Issuer's origin go to PublicIssuer's instead, and the
// callback's iss may name either. "" means Issuer.
PublicIssuer string
// CookieName names the short cookie of a running sign-in; "" means
// "yaiam_signin". On https it always gets the prefix "__Host-". One
// sign-in per browser at a time: a second one started in another tab
@@ -88,6 +98,9 @@ type SignedIn struct {
// Groups and Roles with the scopes groups and roles: the names of the
// user's groups (subgroups' members included) and roles in the tenant.
Groups, Roles []string
// Attributes with the scope attributes: the user's attributes yaiam
// releases to the client (department, cost_center, ...), by name.
Attributes map[string]string
// ACR is how strongly the user signed in ("pwd", "mfa", "phr"), AMR
// with what; AuthTime when.
ACR string
@@ -144,11 +157,11 @@ func (w *Web) scope() string {
// check refuses a Web that cannot sign anyone in safely.
func (w *Web) check() error {
if err := checkURL("redirect URL", w.RedirectURL); err != nil {
if err := checkURL("redirect URL", w.RedirectURL, w.AllowInsecure); err != nil {
return err
}
if w.PostLogoutRedirectURL != "" {
if err := checkURL("post-logout redirect URL", w.PostLogoutRedirectURL); err != nil {
if err := checkURL("post-logout redirect URL", w.PostLogoutRedirectURL, w.AllowInsecure); err != nil {
return err
}
}
@@ -156,6 +169,15 @@ func (w *Web) check() error {
if w.Scopes != nil {
scopes = w.Scopes
}
if w.PublicIssuer != "" {
if err := checkURL("public issuer", w.PublicIssuer, w.AllowInsecure); err != nil {
return err
}
pub, _ := url.Parse(w.PublicIssuer)
if iss, err := url.Parse(w.Issuer); err != nil || iss.Path != pub.Path {
return errors.New("yaiam: the public issuer must have the issuer's path")
}
}
if !slices.Contains(scopes, "openid") {
return errors.New("yaiam: a sign-in needs the scope openid")
}
@@ -190,7 +212,7 @@ func (w *Web) SignIn(ctx context.Context, rw http.ResponseWriter, r *http.Reques
q := url.Values{"response_type": {"code"}, "client_id": {w.ClientID}, "redirect_uri": {w.RedirectURL},
"scope": {w.scope()}, "state": {c.State}, "nonce": {c.Nonce},
"code_challenge": {base64.RawURLEncoding.EncodeToString(challenge[:])}, "code_challenge_method": {"S256"}}
target := m.AuthorizationEndpoint
target := w.browser(m.AuthorizationEndpoint)
if strings.Contains(target, "?") {
target += "&" + q.Encode()
} else {
@@ -229,10 +251,8 @@ func (w *Web) Callback(ctx context.Context, rw http.ResponseWriter, r *http.Requ
if err := w.check(); err != nil {
return nil, err
}
m, err := w.discover(ctx)
if err != nil {
return nil, err
}
// The browser's cookie and the state first: a callback of no sign-in
// of this browser never reaches the provider.
var c signInCookie
cookie, cerr := r.Cookie(w.cookieName())
http.SetCookie(rw, &http.Cookie{Name: w.cookieName(), Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: w.secure(),
@@ -249,7 +269,7 @@ func (w *Web) Callback(ctx context.Context, rw http.ResponseWriter, r *http.Requ
return nil, ErrSignInState
}
// RFC 9207: an iss parameter must name this issuer.
if iss := q.Get("iss"); iss != "" && iss != w.Issuer {
if iss := q.Get("iss"); iss != "" && iss != w.Issuer && (w.PublicIssuer == "" || iss != w.PublicIssuer) {
return nil, fmt.Errorf("yaiam: the callback comes from issuer %q, not %q", iss, w.Issuer)
}
if code := q.Get("error"); code != "" {
@@ -260,6 +280,10 @@ func (w *Web) Callback(ctx context.Context, rw http.ResponseWriter, r *http.Requ
if code == "" {
return nil, errors.New("yaiam: the callback has no code")
}
m, err := w.discover(ctx)
if err != nil {
return nil, err
}
tok, idToken, err := w.exchange(ctx, m, code, c.Verifier)
if err != nil {
return nil, err
@@ -281,7 +305,12 @@ func (w *Web) Callback(ctx context.Context, rw http.ResponseWriter, r *http.Requ
if u.Subject != claims.Subject {
return nil, errors.New("yaiam: UserInfo names another user than the ID token")
}
out.Username, out.Name, out.Email, out.EmailVerified, out.Groups, out.Roles = u.Username, u.Name, u.Email, u.EmailVerified, u.Groups, u.Roles
// Only the JSON boolean true confirms the address: some providers
// send the string "true", which a sign-in must not take for it
// (nor fail on).
out.Username, out.Name, out.Email, out.Groups, out.Roles = u.Username, u.Name, u.Email, u.Groups, u.Roles
out.EmailVerified = string(u.EmailVerified) == "true"
out.Attributes = u.Attributes
}
return out, nil
}
@@ -389,9 +418,10 @@ func (w *Web) checkIDToken(idToken, nonce string) (*idClaims, error) {
// webUserInfo is UserInfo's answer with what a web sign-in also takes.
type webUserInfo struct {
UserInfo
EmailVerified bool `json:"email_verified"`
EmailVerified json.RawMessage `json:"email_verified"`
Groups []string `json:"groups"`
Roles []string `json:"roles"`
Attributes map[string]string `json:"attributes"`
}
func (w *Web) userInfo(ctx context.Context, m *metadata, t *Token) (*webUserInfo, error) {
@@ -438,5 +468,21 @@ func (w *Web) LogoutURL(ctx context.Context, idToken string) (string, error) {
if strings.Contains(m.EndSessionEndpoint, "?") {
sep = "&"
}
return m.EndSessionEndpoint + sep + q.Encode(), nil
return w.browser(m.EndSessionEndpoint) + sep + q.Encode(), nil
}
// browser is endpoint as the browser reaches it: on PublicIssuer's
// origin when it is on Issuer's.
func (w *Web) browser(endpoint string) string {
if w.PublicIssuer == "" {
return endpoint
}
e, err := url.Parse(endpoint)
iss, err2 := url.Parse(w.Issuer)
pub, err3 := url.Parse(w.PublicIssuer)
if err != nil || err2 != nil || err3 != nil || e.Scheme != iss.Scheme || e.Host != iss.Host {
return endpoint
}
e.Scheme, e.Host = pub.Scheme, pub.Host
return e.String()
}
+94
View File
@@ -0,0 +1,94 @@
package yaiam
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
)
// Refresh gets a new access token for a signed-in user with t's refresh
// token (there is one only when the scopes asked for offline_access).
// Unlike Client.Refresh it authenticates a confidential client with its
// secret. The answer's refresh token replaces t's; keep the result, not
// t. A refused refresh token is ErrLoginRequired.
func (w *Web) Refresh(ctx context.Context, t *Token) (*Token, error) {
if t == nil || t.RefreshToken == "" {
return nil, ErrLoginRequired
}
m, err := w.discover(ctx)
if err != nil {
return nil, err
}
var out struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}
err = w.postClient(ctx, "token", m.TokenEndpoint, url.Values{"grant_type": {"refresh_token"}, "refresh_token": {t.RefreshToken}}, &out)
if isCode(err, "invalid_grant") {
return nil, fmt.Errorf("%w (%w)", ErrLoginRequired, err)
}
if err != nil {
return nil, err
}
if out.AccessToken == "" || !strings.EqualFold(out.TokenType, "Bearer") || out.ExpiresIn <= 0 {
return nil, errors.New("yaiam: token: no bearer token with a lifetime in the answer")
}
nt := &Token{Issuer: w.Issuer, ClientID: w.ClientID, AccessToken: out.AccessToken, RefreshToken: out.RefreshToken,
Expiry: time.Now().Add(time.Duration(out.ExpiresIn) * time.Second), Scope: out.Scope}
if nt.RefreshToken == "" {
nt.RefreshToken = t.RefreshToken
}
return nt, nil
}
// Revoke ends a signed-in user's tokens at the provider (RFC 7009): the
// refresh token first, which ends the access tokens it made too, then
// the access token. For a sign-out; the browser's session at the
// provider ends only through LogoutURL.
func (w *Web) Revoke(ctx context.Context, t *Token) error {
if t == nil || (t.RefreshToken == "" && t.AccessToken == "") {
return nil
}
m, err := w.discover(ctx)
if err != nil {
return err
}
if m.RevocationEndpoint == "" {
return errors.New("yaiam: the provider offers no revocation")
}
for _, tok := range []struct{ value, hint string }{{t.RefreshToken, "refresh_token"}, {t.AccessToken, "access_token"}} {
if tok.value == "" {
continue
}
if err := w.postClient(ctx, "revocation", m.RevocationEndpoint, url.Values{"token": {tok.value}, "token_type_hint": {tok.hint}}, nil); err != nil {
return err
}
}
return nil
}
// postClient posts form as this client: a confidential one with its ID
// and secret in a Basic header (RFC 6749 §2.3.1), a public one with
// client_id in the form.
func (w *Web) postClient(ctx context.Context, name, endpoint string, form url.Values, out any) error {
if w.ClientSecret == "" {
form.Set("client_id", w.ClientID)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
if w.ClientSecret != "" {
req.SetBasicAuth(url.QueryEscape(w.ClientID), url.QueryEscape(w.ClientSecret))
}
return w.send(name, req, out)
}
+85
View File
@@ -0,0 +1,85 @@
package yaiam
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"time"
)
// TestWebRefreshAndRevoke: a confidential client refreshes and revokes
// with its secret in a Basic header and no client_id in the form; a
// refused refresh token is ErrLoginRequired.
func TestWebRefreshAndRevoke(t *testing.T) {
var mu sync.Mutex
var forms []url.Values
var auths []string
var ts *httptest.Server
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": ts.URL + "/t/default", "token_endpoint": ts.URL + "/token",
"revocation_endpoint": ts.URL + "/revoke"})
})
record := func(r *http.Request) {
r.ParseForm()
mu.Lock()
forms = append(forms, r.PostForm)
auths = append(auths, r.Header.Get("Authorization"))
mu.Unlock()
}
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
record(r)
if r.PostForm.Get("refresh_token") != "rt-1" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `{"error":"invalid_grant"}`)
return
}
fmt.Fprint(w, `{"access_token":"at-2","token_type":"Bearer","expires_in":300,"refresh_token":"rt-2","scope":"openid offline_access"}`)
})
mux.HandleFunc("POST /revoke", func(w http.ResponseWriter, r *http.Request) { record(r) })
ts = httptest.NewServer(mux)
defer ts.Close()
w := &Web{Client: Client{Issuer: ts.URL + "/t/default", ClientID: "web"}, ClientSecret: "s3cret", RedirectURL: "http://localhost/cb"}
nt, err := w.Refresh(context.Background(), &Token{AccessToken: "at-1", RefreshToken: "rt-1"})
if err != nil {
t.Fatal(err)
}
if nt.AccessToken != "at-2" || nt.RefreshToken != "rt-2" || nt.ClientID != "web" || time.Until(nt.Expiry) < 4*time.Minute {
t.Fatalf("token %+v", nt)
}
if f := forms[0]; f.Get("grant_type") != "refresh_token" || f.Has("client_id") || auths[0] != "Basic d2ViOnMzY3JldA==" {
t.Fatalf("form %v auth %q", f, auths[0])
}
if _, err := w.Refresh(context.Background(), &Token{RefreshToken: "stale"}); !errors.Is(err, ErrLoginRequired) {
t.Fatalf("stale: %v", err)
}
if _, err := w.Refresh(context.Background(), &Token{AccessToken: "at"}); !errors.Is(err, ErrLoginRequired) {
t.Fatalf("no refresh token: %v", err)
}
forms, auths = nil, nil
if err := w.Revoke(context.Background(), nt); err != nil {
t.Fatal(err)
}
if len(forms) != 2 || forms[0].Get("token") != "rt-2" || forms[0].Get("token_type_hint") != "refresh_token" ||
forms[1].Get("token") != "at-2" || auths[1] != "Basic d2ViOnMzY3JldA==" {
t.Fatalf("revoke forms %v", forms)
}
// A public client sends client_id instead.
pub := &Web{Client: Client{Issuer: ts.URL + "/t/default", ClientID: "web"}, RedirectURL: "http://localhost/cb"}
forms, auths = nil, nil
if _, err := pub.Refresh(context.Background(), &Token{RefreshToken: "rt-1"}); err != nil {
t.Fatal(err)
}
if forms[0].Get("client_id") != "web" || auths[0] != "" {
t.Fatalf("public: %v %q", forms[0], auths[0])
}
}
+98 -3
View File
@@ -71,7 +71,7 @@ func newOP(t *testing.T) *op {
o.ts = httptest.NewServer(mux)
t.Cleanup(o.ts.Close)
o.issuer = o.ts.URL + "/t/default"
o.userBody = `{"sub":"u-1","preferred_username":"alice","name":"Alice","email":"alice@example.org","email_verified":true,"groups":["staff","dev"],"roles":["editor"]}`
o.userBody = `{"sub":"u-1","preferred_username":"alice","name":"Alice","email":"alice@example.org","email_verified":true,"groups":["staff","dev"],"roles":["editor"],"attributes":{"department":"IT"}}`
o.claims = func(nonce string) map[string]any {
now := time.Now()
return map[string]any{"iss": o.issuer, "sub": "u-1", "aud": "web", "exp": now.Add(5 * time.Minute).Unix(), "iat": now.Unix(),
@@ -137,7 +137,7 @@ func TestWebSignIn(t *testing.T) {
w := o.web()
q, cookie := o.start(t, w, "/staff?x=1")
if q.Get("response_type") != "code" || q.Get("client_id") != "web" || q.Get("redirect_uri") != w.RedirectURL ||
q.Get("scope") != "openid profile email groups roles" || q.Get("code_challenge_method") != "S256" || q.Get("state") == "" || q.Get("nonce") == "" {
q.Get("scope") != "openid profile email groups roles attributes" || q.Get("code_challenge_method") != "S256" || q.Get("state") == "" || q.Get("nonce") == "" {
t.Errorf("authorization request %v", q)
}
if !cookie.HttpOnly || cookie.SameSite != http.SameSiteLaxMode || cookie.Name != "yaiam_signin" || cookie.Secure || cookie.MaxAge != 600 {
@@ -148,7 +148,7 @@ func TestWebSignIn(t *testing.T) {
t.Fatal(err)
}
if s.Subject != "u-1" || s.Username != "alice" || s.Name != "Alice" || s.Email != "alice@example.org" || !s.EmailVerified ||
strings.Join(s.Groups, ",") != "staff,dev" || strings.Join(s.Roles, ",") != "editor" || s.ACR != "mfa" || s.AuthTime.IsZero() ||
strings.Join(s.Groups, ",") != "staff,dev" || strings.Join(s.Roles, ",") != "editor" || s.Attributes["department"] != "IT" || len(s.Attributes) != 1 || s.ACR != "mfa" || s.AuthTime.IsZero() ||
s.ReturnTo != "/staff?x=1" || s.Token.AccessToken != "at-1" || s.IDToken == "" {
t.Errorf("signed in %+v", s)
}
@@ -327,3 +327,98 @@ func TestDeviceNeedsItsEndpoint(t *testing.T) {
t.Errorf("start device: %v", err)
}
}
// TestWebPublicIssuer: with PublicIssuer the browser goes to the
// provider's endpoints on the public origin, the server keeps using
// Issuer, and the callback's iss may name either; a public issuer with
// another path is refused.
func TestWebPublicIssuer(t *testing.T) {
o := newOP(t)
w := o.web()
pubOrigin := strings.Replace(o.ts.URL, "127.0.0.1", "localhost", 1)
w.PublicIssuer = pubOrigin + "/t/default"
rec := httptest.NewRecorder()
if err := w.SignIn(context.Background(), rec, httptest.NewRequest(http.MethodGet, "/login", nil), "/"); err != nil {
t.Fatal(err)
}
loc, _ := url.Parse(rec.Header().Get("Location"))
if loc.Scheme+"://"+loc.Host+loc.Path != pubOrigin+"/authorize" {
t.Fatalf("redirect to %s", loc)
}
o.mu.Lock()
o.nonce = loc.Query().Get("nonce")
o.mu.Unlock()
cookie := rec.Result().Cookies()[0]
cb := url.Values{"code": {"the-code"}, "state": {loc.Query().Get("state")}, "iss": {w.PublicIssuer}}
if s, _, err := callback(w, cb.Encode(), cookie); err != nil || s.Subject != "u-1" {
t.Fatalf("iss = public issuer: %+v, %v", s, err)
}
if u, err := w.LogoutURL(context.Background(), ""); err != nil || !strings.HasPrefix(u, pubOrigin+"/logout?") {
t.Errorf("logout URL %q, %v", u, err)
}
other := o.web()
other.PublicIssuer = pubOrigin + "/t/other"
if err := other.SignIn(context.Background(), httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/login", nil), "/"); err == nil {
t.Error("public issuer with another path taken")
}
}
// TestWebEmailVerified: only the JSON boolean true confirms the address;
// the string "true" or no claim leaves it unconfirmed without failing.
func TestWebEmailVerified(t *testing.T) {
o := newOP(t)
w := o.web()
for body, want := range map[string]bool{
`{"sub":"u-1","email":"a@example.org","email_verified":true}`: true,
`{"sub":"u-1","email":"a@example.org","email_verified":"true"}`: false,
`{"sub":"u-1","email":"a@example.org","email_verified":1}`: false,
`{"sub":"u-1","email":"a@example.org"}`: false,
} {
o.userBody = body
q, c := o.start(t, w, "/")
s, _, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), c)
if err != nil || s.EmailVerified != want || s.Email != "a@example.org" {
t.Errorf("%s: %+v, %v", body, s, err)
}
}
}
// TestAllowInsecure: plain http off loopback only with AllowInsecure.
func TestAllowInsecure(t *testing.T) {
for _, c := range []struct {
url string
insecure bool
ok bool
}{
{"http://oidc:8080/default", false, false},
{"http://oidc:8080/default", true, true},
{"http://127.0.0.1:8080/default", false, true},
{"https://login.example.org/t/default", false, true},
{"ftp://oidc/default", true, false},
{"/default", true, false},
} {
if err := checkURL("issuer", c.url, c.insecure); (err == nil) != c.ok {
t.Errorf("%s (insecure %v): %v", c.url, c.insecure, err)
}
}
w := &Web{Client: Client{Issuer: "http://oidc:8080/default", ClientID: "web", AllowInsecure: true},
RedirectURL: "http://app:8787/auth/callback"}
if err := w.check(); err != nil {
t.Errorf("insecure web: %v", err)
}
w.AllowInsecure = false
if err := w.check(); err == nil {
t.Error("http redirect URL off loopback taken without AllowInsecure")
}
}
// TestWebCallbackBeforeProvider: a callback without this browser's
// sign-in is refused before the provider is asked (here: unreachable).
func TestWebCallbackBeforeProvider(t *testing.T) {
w := &Web{Client: Client{Issuer: "http://127.0.0.1:9/t/default", ClientID: "web"}, RedirectURL: "http://localhost:8097/callback"}
for _, cookie := range []*http.Cookie{nil, {Name: "yaiam_signin", Value: "!!"}} {
if _, _, err := callback(w, "code=c&state=s", cookie); !errors.Is(err, ErrSignInState) {
t.Errorf("cookie %v: %v", cookie, err)
}
}
}
+18 -6
View File
@@ -92,6 +92,12 @@ type Client struct {
// TLS certificates: a web sign-in trusts the ID token because it
// comes from the token endpoint over TLS.
HTTPClient *http.Client
// AllowInsecure accepts plain http on any host, not only on loopback:
// for a test installation whose provider sits on a closed network
// (e.g. a compose network, "http://oidc:8080/default"). Without TLS a
// web sign-in's ID token is only as trustworthy as that network --
// never set it for a provider reached over the internet.
AllowInsecure bool
mu sync.Mutex
meta *metadata
@@ -136,7 +142,7 @@ func (c *Client) discover(ctx context.Context) (*metadata, error) {
if m != nil {
return m, nil
}
if err := checkURL("issuer", c.Issuer); err != nil {
if err := checkURL("issuer", c.Issuer, c.AllowInsecure); err != nil {
return nil, err
}
if c.ClientID == "" {
@@ -161,7 +167,7 @@ func (c *Client) discover(ctx context.Context) (*metadata, error) {
if m.Issuer != c.Issuer {
return nil, fmt.Errorf("yaiam: discovery names the issuer %q, not %q", m.Issuer, c.Issuer)
}
if err := checkURL("token_endpoint", m.TokenEndpoint); err != nil {
if err := checkURL("token_endpoint", m.TokenEndpoint, c.AllowInsecure); err != nil {
return nil, err
}
// The others only where a flow needs them (device: StartDevice; web:
@@ -170,7 +176,7 @@ func (c *Client) discover(ctx context.Context) (*metadata, error) {
"device_authorization_endpoint": m.DeviceAuthorizationEndpoint, "authorization_endpoint": m.AuthorizationEndpoint,
"end_session_endpoint": m.EndSessionEndpoint} {
if u != "" {
if err := checkURL(name, u); err != nil {
if err := checkURL(name, u, c.AllowInsecure); err != nil {
return nil, err
}
}
@@ -182,8 +188,8 @@ func (c *Client) discover(ctx context.Context) (*metadata, error) {
}
// checkURL refuses anything but an absolute https URL, or http on a
// loopback host.
func checkURL(name, s string) error {
// loopback host (any host with insecure).
func checkURL(name, s string, insecure bool) error {
u, err := url.Parse(s)
if err != nil || u.Host == "" {
return fmt.Errorf("yaiam: %s %q is not an absolute URL", name, s)
@@ -191,7 +197,7 @@ func checkURL(name, s string) error {
switch {
case u.Scheme == "https":
return nil
case u.Scheme == "http" && isLoopback(u.Hostname()):
case u.Scheme == "http" && (insecure || isLoopback(u.Hostname())):
return nil
}
return fmt.Errorf("yaiam: %s %q is not https", name, s)
@@ -236,6 +242,12 @@ func (c *Client) post(ctx context.Context, name, endpoint string, form url.Value
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
return c.send(name, req, out)
}
// send sends req. A 200 answer is decoded into out (if not nil); any
// other is returned as *Error.
func (c *Client) send(name string, req *http.Request, out any) error {
status, body, err := c.do(req)
if err != nil {
return fmt.Errorf("yaiam: %s: %w", name, err)