diff --git a/AGENTS.md b/AGENTS.md index d9a7b46..8659352 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`). diff --git a/README.md b/README.md index eaf3bbf..2ca9abd 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,15 @@ 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. `Admin` reads a tenant's users, groups and group members from yaiam's admin API with a service client's token (client credentials, cached diff --git a/TODO.md b/TODO.md index 400072f..252a3c9 100644 --- a/TODO.md +++ b/TODO.md @@ -12,6 +12,11 @@ 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. - [ ] **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. diff --git a/yaiam/admin.go b/yaiam/admin.go index 0c96df7..df63883 100644 --- a/yaiam/admin.go +++ b/yaiam/admin.go @@ -153,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, "/?#") { diff --git a/yaiam/device.go b/yaiam/device.go index 2de3115..93074c7 100644 --- a/yaiam/device.go +++ b/yaiam/device.go @@ -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 } } diff --git a/yaiam/web.go b/yaiam/web.go index ad5dc0d..5159706 100644 --- a/yaiam/web.go +++ b/yaiam/web.go @@ -71,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 @@ -149,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 } } @@ -161,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") } @@ -195,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 { @@ -254,7 +271,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 != "" { @@ -286,7 +303,11 @@ 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 @@ -395,7 +416,7 @@ 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"` @@ -445,5 +466,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() } diff --git a/yaiam/web_test.go b/yaiam/web_test.go index 7d5a687..48d3d0c 100644 --- a/yaiam/web_test.go +++ b/yaiam/web_test.go @@ -327,3 +327,87 @@ 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") + } +} diff --git a/yaiam/yaiam.go b/yaiam/yaiam.go index e7f0442..0d79c0d 100644 --- a/yaiam/yaiam.go +++ b/yaiam/yaiam.go @@ -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)