3 Commits
Author SHA1 Message Date
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
terminarandClaude Opus 5.5 a3e8f9bb3b yaiam: web sign-in (Web) and admin API reads (Admin)
Web signs the users of a web application in with the code flow and
PKCE: state, nonce and verifier in a short-lived __Host- cookie, the ID
token checked per OIDC Core 3.1.3.7, profile, groups and roles from
UserInfo, and the RP-initiated logout URL. Admin reads users, groups
and group members from yaiam's admin API with a client credentials
token. Toolchain go1.27.4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:54:53 +01:00
10 changed files with 1343 additions and 24 deletions

No files matched your search

+11 -4
View File
@@ -45,11 +45,18 @@ Tests use `httptest` servers only -- never a live Atlassian site.
## yaiam
`yaiam` signs a CLI in at yaiam over standards only (device flow,
refresh, revocation, UserInfo). It holds no secret and verifies no
token signature -- no crypto here; servers check tokens with yaiam's
`pkg/httpauth`. Never log a token or put one into an error, never follow
refresh, revocation, UserInfo), and a web application's users (`Web`:
code flow with PKCE, state and nonce in a short browser cookie). It
verifies no token signature -- no crypto here: a web sign-in's ID token
comes straight from the token endpoint over TLS (OpenID Connect Core
3.1.3.7) and its claims are checked (iss, aud/azp, exp, iat, nonce);
never take an ID token from anywhere else, and never let `Callback`
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`).
+45 -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) |
| `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) |
Standard library only, no third-party dependencies.
@@ -144,6 +144,50 @@ c.Logout(ctx, store) // revokes at the provider, forgets them
The user's guide is yaiam's `docs/manual/yetano-programme.md`; an
example program is yaiam's `examples/device-login`.
### Web applications
A web application signs its users in with `Web` (authorization code
flow with PKCE, a confidential or a public client):
```go
web := &yaiam.Web{
Client: yaiam.Client{Issuer: "https://login.example.org/t/default", ClientID: id},
ClientSecret: secret,
RedirectURL: "https://app.example.org/callback",
}
web.SignIn(ctx, w, r, "/after") // GET /login: redirect to yaiam
u, err := web.Callback(ctx, w, r) // GET /callback: u.Subject, u.Groups, u.Roles, u.ACR ...
out, _ := web.LogoutURL(ctx, u.IDToken)
```
- `SignIn` keeps a fresh state, nonce and PKCE verifier in a ten-minute
cookie of the browser (HttpOnly, SameSite=Lax, `__Host-` and Secure
on https); `Callback` checks the state against it and removes it.
The return path is a local path only.
- The ID token comes straight from the token endpoint over TLS, so its
signature is not checked (OpenID Connect Core 3.1.3.7) -- no crypto
here: iss, aud (and azp), exp, iat and the nonce are. Profile, groups
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
until a minute before it runs out; a refused one is fetched once more).
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`.
## Versioning
A release is a plain semver git tag (`v0.1.0`, ...) on this repository;
+13 -4
View File
@@ -7,10 +7,19 @@
## Open
- [ ] **yaiam: web sign-in.** A helper for web UIs (authorization code
+ PKCE, session handling) once yasta's web UI binds to yaiam -- it
needs ID-token checks, so either a dependency (zitadel/oidc, go-jose)
or it stays in the program; decide with yasta.
- [x] **yaiam: web sign-in** (owner decision 2026-11-17): `Web`, stdlib
only -- the ID token checked by its claims as it comes from the token
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.
- [ ] **yamcp search on Cloud.** yamcp's `jira_search_issues` still
uses `SearchPage` (classic `POST /rest/api/3/search`), which Atlassian
+2
View File
@@ -1,3 +1,5 @@
module yetano.dev/yetano/yetano-clients
go 1.25.0
toolchain go1.27.4
+201
View File
@@ -0,0 +1,201 @@
package yaiam
// Reading a tenant's users and groups from yaiam's admin API, as a
// service: a confidential service client of yaiam (its service account
// holds yaiam.user.read and yaiam.group.read; the client's tokens have
// the admin API as their audience) gets a token with the client
// credentials grant and asks /api/v1/tenants/<tenant>/... with it. For
// an application that wants to know users before they sign in, or the
// members of a group; whoever signs in brings their own groups
// (SignedIn).
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
// maxList bounds an answer of the admin API: its lists come whole (no
// paging) -- some 100 000 users.
const maxList = 64 << 20
// Admin reads from yaiam's admin API. Its fields must not change once it
// is in use; use it by pointer; it is safe for concurrent use.
type Admin struct {
// Client holds the issuer (the tenant's, whose token endpoint gives
// the token), the service client's ID and the HTTP client.
Client
// ClientSecret is the service client's secret.
ClientSecret string
// API is the admin API, e.g. "https://admin.example.org/api/v1"
// (yaiam-web; https, or http on a loopback host).
API string
// Tenant is the tenant's slug; its token works only there.
Tenant string
tokMu sync.Mutex
tok *Token
}
// Member is a user of the tenant as the admin API lists them.
type Member struct {
ID string `json:"id"`
Ref string `json:"ref"` // the name, or "home/name" for a member from another tenant
Username string `json:"username"`
DisplayName string `json:"display_name"`
State string `json:"user_state"`
Home bool `json:"home"`
}
// Group is a group of the tenant.
type Group struct {
ID string `json:"id"`
Name string `json:"name"`
Protected bool `json:"protected"`
}
// User is one user in full.
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
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.
func (a *Admin) Users(ctx context.Context) ([]Member, error) {
var out struct {
Items []Member `json:"items"`
}
return out.Items, a.get(ctx, "users", &out)
}
// User returns the user named name.
func (a *Admin) User(ctx context.Context, name string) (*User, error) {
var u User
if err := a.get(ctx, "users/"+url.PathEscape(name), &u); err != nil {
return nil, err
}
return &u, nil
}
// Groups lists the tenant's groups.
func (a *Admin) Groups(ctx context.Context) ([]Group, error) {
var out struct {
Items []Group `json:"items"`
}
return out.Items, a.get(ctx, "groups", &out)
}
// GroupMembers lists the direct members of the group name.
func (a *Admin) GroupMembers(ctx context.Context, name string) ([]Member, error) {
var out struct {
Items []Member `json:"items"`
}
return out.Items, a.get(ctx, "groups/"+url.PathEscape(name)+"/members", &out)
}
// token is a service token from the client credentials grant, kept until
// a minute before it runs out.
func (a *Admin) token(ctx context.Context) (string, error) {
a.tokMu.Lock()
defer a.tokMu.Unlock()
if a.tok != nil && time.Until(a.tok.Expiry) > leeway {
return a.tok.AccessToken, nil
}
m, err := a.discover(ctx)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, m.TokenEndpoint, strings.NewReader(url.Values{"grant_type": {"client_credentials"}}.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(a.ClientID), url.QueryEscape(a.ClientSecret))
status, body, err := a.do(req)
if err != nil {
return "", fmt.Errorf("yaiam: token: %w", err)
}
if status != http.StatusOK {
return "", oauthError("token", status, body)
}
var out struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
}
if err := json.Unmarshal(body, &out); err != nil {
return "", fmt.Errorf("yaiam: token: %w", err)
}
if out.AccessToken == "" || !strings.EqualFold(out.TokenType, "Bearer") || out.ExpiresIn <= 0 {
return "", errors.New("yaiam: token: no bearer token with a lifetime in the answer")
}
a.tok = &Token{Issuer: a.Issuer, ClientID: a.ClientID, AccessToken: out.AccessToken,
Expiry: time.Now().Add(time.Duration(out.ExpiresIn) * time.Second)}
return out.AccessToken, nil
}
// 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, a.AllowInsecure); err != nil {
return err
}
if a.Tenant == "" || strings.ContainsAny(a.Tenant, "/?#") {
return errors.New("yaiam: admin API: no tenant")
}
target := strings.TrimSuffix(a.API, "/") + "/tenants/" + url.PathEscape(a.Tenant) + "/" + path
for attempt := 0; ; attempt++ {
tok, err := a.token(ctx)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+tok)
req.Header.Set("Accept", "application/json")
status, body, err := a.doMax(req, maxList)
if err != nil {
return fmt.Errorf("yaiam: admin API: %w", err)
}
if status == http.StatusUnauthorized && attempt == 0 {
a.tokMu.Lock()
a.tok = nil
a.tokMu.Unlock()
continue
}
if status != http.StatusOK {
var p struct {
Title string `json:"title"`
Detail string `json:"detail"`
}
json.Unmarshal(body, &p)
desc := p.Detail
if desc == "" {
desc = p.Title
}
return &Error{Endpoint: "admin API", Status: status, Description: desc}
}
if err := json.Unmarshal(body, out); err != nil {
return fmt.Errorf("yaiam: admin API: %w", err)
}
return nil
}
}
+137
View File
@@ -0,0 +1,137 @@
package yaiam
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
// adminFake is the token endpoint and the admin API: a service token for
// the client credentials of "svc"/"s3cret", lists for it.
type adminFake struct {
ts *httptest.Server
mu sync.Mutex
tokens int
reject int // answer this many API calls with 401
lastPath string
}
func newAdminFake(t *testing.T) *adminFake {
f := &adminFake{}
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": f.ts.URL + "/t/default", "token_endpoint": f.ts.URL + "/token"})
})
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
if u, p, ok := r.BasicAuth(); !ok || u != "svc" || p != "s3cret" || r.PostForm.Get("grant_type") != "client_credentials" {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"error":"invalid_client"}`)
return
}
f.mu.Lock()
f.tokens++
n := f.tokens
f.mu.Unlock()
fmt.Fprintf(w, `{"access_token":"svc-%d","token_type":"Bearer","expires_in":300}`, n)
})
mux.HandleFunc("GET /api/v1/tenants/default/", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
f.lastPath = r.URL.Path
reject := f.reject > 0
if reject {
f.reject--
}
f.mu.Unlock()
if reject || !strings.HasPrefix(r.Header.Get("Authorization"), "Bearer svc-") {
w.WriteHeader(http.StatusUnauthorized)
return
}
switch strings.TrimPrefix(r.URL.Path, "/api/v1/tenants/default/") {
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","attributes":{"department":"IT"}}`)
case "groups":
fmt.Fprint(w, `{"items":[{"id":"g-1","name":"staff","protected":false}]}`)
case "groups/staff/members":
fmt.Fprint(w, `{"items":[{"id":"u-1","ref":"alice","username":"alice"}]}`)
default:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, `{"title":"Not Found","detail":"no such thing"}`)
}
})
f.ts = httptest.NewServer(mux)
t.Cleanup(f.ts.Close)
return f
}
func (f *adminFake) admin() *Admin {
return &Admin{Client: Client{Issuer: f.ts.URL + "/t/default", ClientID: "svc"}, ClientSecret: "s3cret", API: f.ts.URL + "/api/v1", Tenant: "default"}
}
// TestAdmin: the lists and a user, with one service token for all;
// a refused token is fetched again once; an error answer says what.
func TestAdmin(t *testing.T) {
f := newAdminFake(t)
a := f.admin()
ctx := context.Background()
users, err := a.Users(ctx)
if err != nil || len(users) != 1 || users[0].Username != "alice" || users[0].State != "active" || !users[0].Home {
t.Fatalf("users %+v, %v", users, err)
}
u, err := a.User(ctx, "alice")
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)
if err != nil || len(groups) != 1 || groups[0].Name != "staff" {
t.Errorf("groups %+v, %v", groups, err)
}
members, err := a.GroupMembers(ctx, "staff")
if err != nil || len(members) != 1 || members[0].ID != "u-1" {
t.Errorf("members %+v, %v", members, err)
}
if f.tokens != 1 {
t.Errorf("%d tokens for four calls", f.tokens)
}
f.reject = 1
if _, err := a.Groups(ctx); err != nil || f.tokens != 2 {
t.Errorf("after a refused token: %v, %d tokens", err, f.tokens)
}
f.reject = 2
var e *Error
if _, err := a.Groups(ctx); !errors.As(err, &e) || e.Status != http.StatusUnauthorized {
t.Errorf("refused twice: %v", err)
}
if _, err := a.User(ctx, "bob"); !errors.As(err, &e) || e.Status != http.StatusNotFound || e.Description != "no such thing" {
t.Errorf("not found: %v", err)
}
wrong := f.admin()
wrong.ClientSecret = "nope"
if _, err := wrong.Users(ctx); !errors.As(err, &e) || e.Code != "invalid_client" {
t.Errorf("wrong secret: %v", err)
}
insecure := f.admin()
insecure.API = "http://admin.example.org/api/v1"
if _, err := insecure.Users(ctx); err == nil || !strings.Contains(err.Error(), "not https") {
t.Errorf("an http API off loopback: %v", err)
}
noTenant := f.admin()
noTenant.Tenant = ""
if _, err := noTenant.Users(ctx); err == nil || !strings.Contains(err.Error(), "no tenant") {
t.Errorf("no tenant: %v", err)
}
noTenant.Tenant = "a/b"
if _, err := noTenant.Users(ctx); err == nil || !strings.Contains(err.Error(), "no tenant") {
t.Errorf("a tenant with a slash: %v", err)
}
}
+5 -2
View File
@@ -36,6 +36,9 @@ func (c *Client) StartDevice(ctx context.Context) (*DeviceAuth, error) {
if err != nil {
return nil, err
}
if m.DeviceAuthorizationEndpoint == "" {
return nil, errors.New("yaiam: the provider offers no device sign-in")
}
var out struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
@@ -52,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
}
}
+486
View File
@@ -0,0 +1,486 @@
package yaiam
// Signing the users of a web application in (authorization code flow
// with PKCE, OpenID Connect Core 3.1). SignIn sends the browser to the
// provider with a fresh state, nonce and code verifier, kept in a short
// cookie of this browser; Callback checks the state against the cookie,
// trades the code for tokens and checks the ID token.
//
// The ID token comes straight from the token endpoint over TLS, so its
// signature is not checked here: OpenID Connect Core 3.1.3.7 lets a
// client rely on the TLS server check instead -- no crypto in this
// package. Its claims are: iss the issuer, aud this client (azp too when
// there are several), not expired, the nonce of this sign-in. The
// profile, groups and roles come from UserInfo, which must name the same
// subject.
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strings"
"time"
)
// WebScopes are asked for when Web.Scopes is nil: who the user is, their
// 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
// clockSkew is the leeway for an ID token's exp and iat.
const clockSkew = time.Minute
// Errors of a sign-in.
var (
// ErrSignInState: the callback does not belong to a sign-in this
// browser started (no cookie, another state, too late). Start again.
ErrSignInState = errors.New("yaiam: the sign-in does not belong to this browser or took too long")
// ErrSignInRefused: the provider answered the callback with an error
// (the user cancelled, may not use the application, ...); see the
// wrapped *Error for its code.
ErrSignInRefused = errors.New("yaiam: the provider refused the sign-in")
)
// Web signs the users of a web application in at one issuer as one
// client. Its fields must not change once it is in use; use it by
// pointer; it is safe for concurrent use.
type Web struct {
// Client holds the issuer, the client ID, the scopes (nil:
// WebScopes) and the HTTP client. Its Scopes and token store are not
// used.
Client
// ClientSecret authenticates a confidential client at the token
// endpoint (client_secret_basic); "" for a public client.
ClientSecret string
// RedirectURL is this application's callback, registered at the
// client, e.g. "https://app.example.org/callback".
RedirectURL string
// 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
// replaces the first, whose callback then is ErrSignInState.
CookieName string
}
// SignedIn is who signed in, with the tokens.
type SignedIn struct {
// Subject is the user's ID at yaiam: it stays the same when the user
// is renamed -- the key to keep an application's own data under.
Subject string
// Username, Name and Email (EmailVerified: confirmed) with the
// scopes profile and email.
Username, Name, Email string
EmailVerified bool
// 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
AMR []string
AuthTime time.Time
// IDToken is for LogoutURL; Token for the APIs (it holds no refresh
// token unless the scopes asked for offline_access).
IDToken string
Token *Token
// ReturnTo is the path SignIn was given.
ReturnTo string
}
// String keeps the tokens out of anything printed or logged.
func (s *SignedIn) String() string {
if s == nil {
return "<nil>"
}
return fmt.Sprintf("yaiam.SignedIn{Subject: %q, Username: %q, Groups: %q, ACR: %q, tokens redacted}", s.Subject, s.Username, s.Groups, s.ACR)
}
// GoString is String, for %#v.
func (s *SignedIn) GoString() string { return s.String() }
// signInCookie is what the cookie of a running sign-in holds.
type signInCookie struct {
State string `json:"s"`
Nonce string `json:"n"`
Verifier string `json:"v"`
ReturnTo string `json:"r"`
Expires int64 `json:"e"`
}
func (w *Web) secure() bool { return strings.HasPrefix(w.RedirectURL, "https://") }
func (w *Web) cookieName() string {
name := w.CookieName
if name == "" {
name = "yaiam_signin"
}
// On https always __Host-: no other host can plant it.
if w.secure() && !strings.HasPrefix(name, "__Host-") {
return "__Host-" + name
}
return name
}
func (w *Web) scope() string {
if w.Scopes == nil {
return strings.Join(WebScopes, " ")
}
return strings.Join(w.Scopes, " ")
}
// check refuses a Web that cannot sign anyone in safely.
func (w *Web) check() error {
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, w.AllowInsecure); err != nil {
return err
}
}
scopes := WebScopes
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")
}
return nil
}
// SignIn starts a sign-in: it remembers a fresh state, nonce and PKCE
// verifier in a cookie of this browser (HttpOnly, SameSite=Lax, Secure on
// https, ten minutes) and redirects the browser to the provider.
// returnTo is the path of this application to go to afterwards
// (Callback returns it); anything but a local path becomes "/".
func (w *Web) SignIn(ctx context.Context, rw http.ResponseWriter, r *http.Request, returnTo string) error {
if err := w.check(); err != nil {
return err
}
m, err := w.discover(ctx)
if err != nil {
return err
}
if m.AuthorizationEndpoint == "" {
return errors.New("yaiam: the provider names no authorization endpoint")
}
c := signInCookie{State: random(), Nonce: random(), Verifier: random() + random(), ReturnTo: localPath(returnTo),
Expires: time.Now().Add(signInLifetime).Unix()}
raw, err := json.Marshal(c)
if err != nil {
return err
}
http.SetCookie(rw, &http.Cookie{Name: w.cookieName(), Value: base64.RawURLEncoding.EncodeToString(raw), Path: "/",
MaxAge: int(signInLifetime.Seconds()), HttpOnly: true, Secure: w.secure(), SameSite: http.SameSiteLaxMode})
challenge := sha256.Sum256([]byte(c.Verifier))
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 := w.browser(m.AuthorizationEndpoint)
if strings.Contains(target, "?") {
target += "&" + q.Encode()
} else {
target += "?" + q.Encode()
}
http.Redirect(rw, r, target, http.StatusFound)
return nil
}
// localPath is p when it is a path of this application, else "/": no
// redirect to another site after the sign-in. A browser drops tabs and
// line breaks from a URL and reads a backslash as a slash, so none of
// them, no control character, and no "//" at the start.
func localPath(p string) string {
if !strings.HasPrefix(p, "/") || strings.HasPrefix(p, "//") ||
strings.ContainsFunc(p, func(r rune) bool { return r < 0x20 || r == 0x7f || r == '\\' }) {
return "/"
}
return p
}
// random is 32 random bytes, base64url.
func random() string {
b := make([]byte, 32)
rand.Read(b) // never fails (crypto/rand)
return base64.RawURLEncoding.EncodeToString(b)
}
// Callback finishes the sign-in the request r (the provider's redirect
// to RedirectURL) belongs to: the state must be the one of this
// browser's cookie (which it removes), the code is traded for tokens with
// the verifier, the ID token checked, UserInfo asked. A refusal of the
// provider is ErrSignInRefused, a callback of another or an old sign-in
// ErrSignInState.
func (w *Web) Callback(ctx context.Context, rw http.ResponseWriter, r *http.Request) (*SignedIn, error) {
if err := w.check(); err != nil {
return nil, err
}
m, err := w.discover(ctx)
if err != nil {
return nil, err
}
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(),
SameSite: http.SameSiteLaxMode})
if cerr != nil {
return nil, ErrSignInState
}
raw, err := base64.RawURLEncoding.DecodeString(cookie.Value)
if err != nil || json.Unmarshal(raw, &c) != nil || c.State == "" || time.Now().Unix() > c.Expires {
return nil, ErrSignInState
}
q := r.URL.Query()
if subtle.ConstantTimeCompare([]byte(q.Get("state")), []byte(c.State)) != 1 {
return nil, ErrSignInState
}
// RFC 9207: an iss parameter must name this 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 != "" {
return nil, fmt.Errorf("%w: %w", ErrSignInRefused, &Error{Endpoint: "authorization", Status: http.StatusFound, Code: code,
Description: q.Get("error_description")})
}
code := q.Get("code")
if code == "" {
return nil, errors.New("yaiam: the callback has no code")
}
tok, idToken, err := w.exchange(ctx, m, code, c.Verifier)
if err != nil {
return nil, err
}
claims, err := w.checkIDToken(idToken, c.Nonce)
if err != nil {
return nil, err
}
out := &SignedIn{Subject: claims.Subject, ACR: claims.ACR, AMR: claims.AMR, IDToken: idToken, Token: tok,
ReturnTo: localPath(c.ReturnTo)} // the cookie is the browser's: check again
if claims.AuthTime > 0 {
out.AuthTime = time.Unix(claims.AuthTime, 0)
}
if m.UserinfoEndpoint != "" {
u, err := w.userInfo(ctx, m, tok)
if err != nil {
return nil, err
}
if u.Subject != claims.Subject {
return nil, errors.New("yaiam: UserInfo names another user than the ID token")
}
// 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
}
// exchange trades code for tokens at the token endpoint.
func (w *Web) exchange(ctx context.Context, m *metadata, code, verifier string) (*Token, string, error) {
form := url.Values{"grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {w.RedirectURL},
"code_verifier": {verifier}}
if w.ClientSecret == "" {
form.Set("client_id", w.ClientID)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, m.TokenEndpoint, strings.NewReader(form.Encode()))
if err != nil {
return nil, "", 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)) // RFC 6749 2.3.1
}
status, body, err := w.do(req)
if err != nil {
return nil, "", fmt.Errorf("yaiam: token: %w", err)
}
if status != http.StatusOK {
return nil, "", oauthError("token", status, body)
}
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"`
IDToken string `json:"id_token"`
}
if err := json.Unmarshal(body, &out); err != nil {
return nil, "", fmt.Errorf("yaiam: token: %w", err)
}
// No ID token: checkIDToken refuses it.
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")
}
return &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}, out.IDToken, nil
}
// idClaims are the ID token's claims a sign-in looks at.
type idClaims struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
Audience json.RawMessage `json:"aud"`
AZP string `json:"azp"`
Expiry int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
Nonce string `json:"nonce"`
ACR string `json:"acr"`
AMR []string `json:"amr"`
AuthTime int64 `json:"auth_time"`
}
// checkIDToken reads the claims of idToken, which came from the token
// endpoint over TLS (OpenID Connect Core 3.1.3.7: no signature check),
// and checks them: issuer, audience, expiry, issue time, nonce.
func (w *Web) checkIDToken(idToken, nonce string) (*idClaims, error) {
parts := strings.Split(idToken, ".")
if len(parts) != 3 {
return nil, errors.New("yaiam: the ID token is not a JWT")
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, errors.New("yaiam: the ID token's claims are not base64url")
}
var c idClaims
if err := json.Unmarshal(raw, &c); err != nil {
return nil, fmt.Errorf("yaiam: the ID token's claims: %w", err)
}
var aud []string
if err := json.Unmarshal(c.Audience, &aud); err != nil {
var one string
if json.Unmarshal(c.Audience, &one) != nil {
return nil, errors.New("yaiam: the ID token has no audience")
}
aud = []string{one}
}
now := time.Now()
switch {
case c.Issuer != w.Issuer:
return nil, fmt.Errorf("yaiam: the ID token is from issuer %q, not %q", c.Issuer, w.Issuer)
case !slices.Contains(aud, w.ClientID):
return nil, errors.New("yaiam: the ID token is not for this client")
case len(aud) > 1 && c.AZP != w.ClientID:
return nil, errors.New("yaiam: the ID token was issued to another client (azp)")
case c.Subject == "":
return nil, errors.New("yaiam: the ID token names no subject")
case c.Expiry == 0 || now.After(time.Unix(c.Expiry, 0).Add(clockSkew)):
return nil, errors.New("yaiam: the ID token has expired")
case c.IssuedAt == 0 || time.Unix(c.IssuedAt, 0).After(now.Add(clockSkew)):
return nil, errors.New("yaiam: the ID token is issued in the future")
case subtle.ConstantTimeCompare([]byte(c.Nonce), []byte(nonce)) != 1:
return nil, errors.New("yaiam: the ID token is not for this sign-in (nonce)")
}
return &c, nil
}
// webUserInfo is UserInfo's answer with what a web sign-in also takes.
type webUserInfo struct {
UserInfo
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) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.UserinfoEndpoint, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+t.AccessToken)
req.Header.Set("Accept", "application/json")
status, body, err := w.do(req)
if err != nil {
return nil, fmt.Errorf("yaiam: userinfo: %w", err)
}
if status != http.StatusOK {
return nil, &Error{Endpoint: "userinfo", Status: status}
}
var u webUserInfo
if err := json.Unmarshal(body, &u); err != nil {
return nil, fmt.Errorf("yaiam: userinfo: %w", err)
}
return &u, nil
}
// LogoutURL is where to send the browser to sign out at the provider too
// (RP-initiated logout): with the ID token of the sign-in as hint and,
// when set, PostLogoutRedirectURL. "" when the provider offers none --
// then the application ends only its own session.
func (w *Web) LogoutURL(ctx context.Context, idToken string) (string, error) {
m, err := w.discover(ctx)
if err != nil {
return "", err
}
if m.EndSessionEndpoint == "" {
return "", nil
}
q := url.Values{"client_id": {w.ClientID}}
if idToken != "" {
q.Set("id_token_hint", idToken)
}
if w.PostLogoutRedirectURL != "" {
q.Set("post_logout_redirect_uri", w.PostLogoutRedirectURL)
}
sep := "?"
if strings.Contains(m.EndSessionEndpoint, "?") {
sep = "&"
}
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()
}
+413
View File
@@ -0,0 +1,413 @@
package yaiam
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
)
// op is a fake OpenID provider for a web sign-in: it hands out the code
// "the-code", answers the token endpoint with an ID token made by
// idClaims (unsigned: nothing here checks a signature) and UserInfo with
// userBody.
type op struct {
t *testing.T
ts *httptest.Server
issuer string
mu sync.Mutex
forms []url.Values
auths []string // Authorization headers of the token requests
claims func(nonce string) map[string]any
userBody string
nonce string // the nonce of the last authorization request
// noIDToken: the token answer has none
noIDToken bool
}
func newOP(t *testing.T) *op {
o := &op{t: t}
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": o.issuer, "authorization_endpoint": o.ts.URL + "/authorize",
"token_endpoint": o.ts.URL + "/token", "userinfo_endpoint": o.ts.URL + "/userinfo", "end_session_endpoint": o.ts.URL + "/logout"})
})
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
o.mu.Lock()
o.forms = append(o.forms, r.PostForm)
o.auths = append(o.auths, r.Header.Get("Authorization"))
claims := o.claims(o.nonce)
noID := o.noIDToken
o.mu.Unlock()
if r.PostForm.Get("code") != "the-code" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `{"error":"invalid_grant"}`)
return
}
out := map[string]any{"access_token": "at-1", "token_type": "Bearer", "expires_in": 300,
"id_token": jwt(claims), "scope": "openid profile"}
if noID {
delete(out, "id_token")
}
json.NewEncoder(w).Encode(out)
})
mux.HandleFunc("GET /userinfo", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer at-1" {
w.WriteHeader(http.StatusUnauthorized)
return
}
fmt.Fprint(w, o.userBody)
})
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"],"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(),
"nonce": nonce, "acr": "mfa", "amr": []string{"pwd", "otp"}, "auth_time": now.Unix()}
}
return o
}
// jwt is an unsigned JWT with claims.
func jwt(claims map[string]any) string {
raw, _ := json.Marshal(claims)
return base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256"}`)) + "." + base64.RawURLEncoding.EncodeToString(raw) + ".c2ln"
}
func (o *op) web() *Web {
return &Web{Client: Client{Issuer: o.issuer, ClientID: "web"}, ClientSecret: "s3cret",
RedirectURL: "http://localhost:8097/callback", PostLogoutRedirectURL: "http://localhost:8097/"}
}
// start runs SignIn and returns the authorization request's parameters
// and the sign-in cookie.
func (o *op) start(t *testing.T, w *Web, returnTo string) (url.Values, *http.Cookie) {
t.Helper()
rec := httptest.NewRecorder()
if err := w.SignIn(context.Background(), rec, httptest.NewRequest(http.MethodGet, "/login", nil), returnTo); err != nil {
t.Fatal(err)
}
if rec.Code != http.StatusFound {
t.Fatalf("status %d", rec.Code)
}
loc, _ := url.Parse(rec.Header().Get("Location"))
if loc.Scheme+"://"+loc.Host+loc.Path != o.ts.URL+"/authorize" {
t.Fatalf("redirect to %s", loc)
}
cs := rec.Result().Cookies()
if len(cs) != 1 {
t.Fatalf("cookies %v", cs)
}
q := loc.Query()
o.mu.Lock()
o.nonce = q.Get("nonce")
o.mu.Unlock()
return q, cs[0]
}
// callback runs Callback for the redirect back with query and cookie.
func callback(w *Web, query string, cookie *http.Cookie) (*SignedIn, *httptest.ResponseRecorder, error) {
req := httptest.NewRequest(http.MethodGet, "/callback?"+query, nil)
if cookie != nil {
req.AddCookie(cookie)
}
rec := httptest.NewRecorder()
s, err := w.Callback(context.Background(), rec, req)
return s, rec, err
}
// TestWebSignIn: SignIn sends the browser to the provider with state,
// nonce and an S256 challenge, remembered in a short cookie; Callback
// trades the code with the verifier (client_secret_basic), checks the ID
// token and takes the profile, groups and roles from UserInfo.
func TestWebSignIn(t *testing.T) {
o := newOP(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 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 {
t.Errorf("cookie %+v", cookie)
}
s, rec, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}, "iss": {o.issuer}}.Encode(), cookie)
if err != nil {
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.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)
}
if c := rec.Result().Cookies(); len(c) != 1 || c[0].MaxAge >= 0 {
t.Errorf("the cookie was not removed: %v", c)
}
form := o.forms[0]
sum := sha256.Sum256([]byte(form.Get("code_verifier")))
if base64.RawURLEncoding.EncodeToString(sum[:]) != q.Get("code_challenge") || form.Get("redirect_uri") != w.RedirectURL ||
form.Get("grant_type") != "authorization_code" || form.Has("client_secret") || form.Has("client_id") {
t.Errorf("token request %v", form)
}
if u, p, ok := (&http.Request{Header: http.Header{"Authorization": {o.auths[0]}}}).BasicAuth(); !ok || u != "web" || p != "s3cret" {
t.Errorf("client authentication %q", o.auths[0])
}
for _, leak := range []string{"at-1", s.IDToken} {
if strings.Contains(fmt.Sprint(s), leak) || strings.Contains(fmt.Sprintf("%#v", s), leak) {
t.Error("a token in what fmt prints")
}
}
// A public client: the client ID in the form, no Authorization.
pub := o.web()
pub.ClientSecret = ""
q, cookie = o.start(t, pub, "")
if s, _, err := callback(pub, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), cookie); err != nil || s.ReturnTo != "/" {
t.Fatalf("public: %+v, %v", s, err)
}
if last := o.forms[len(o.forms)-1]; last.Get("client_id") != "web" || o.auths[len(o.auths)-1] != "" {
t.Errorf("public token request %v %q", last, o.auths[len(o.auths)-1])
}
// https: a __Host- cookie, Secure -- a name of one's own too.
sec := o.web()
sec.RedirectURL = "https://app.example.org/callback"
if _, c := o.start(t, sec, "/"); c.Name != "__Host-yaiam_signin" || !c.Secure {
t.Errorf("https cookie %+v", c)
}
sec.CookieName = "mine"
if _, c := o.start(t, sec, "/"); c.Name != "__Host-mine" {
t.Errorf("https cookie of its own name %+v", c)
}
// A planted cookie's return path is checked again.
q, cookie = o.start(t, w, "/")
raw, _ := base64.RawURLEncoding.DecodeString(cookie.Value)
var v signInCookie
json.Unmarshal(raw, &v)
v.ReturnTo = "//evil.example"
raw, _ = json.Marshal(v)
cookie.Value = base64.RawURLEncoding.EncodeToString(raw)
if s, _, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), cookie); err != nil || s.ReturnTo != "/" {
t.Errorf("planted return path: %+v, %v", s, err)
}
}
// TestWebCallbackRefuses: a callback without this browser's cookie, with
// another state, after the cookie's time, from another issuer, with an
// error of the provider, or whose ID token or UserInfo does not fit,
// signs nobody in.
func TestWebCallbackRefuses(t *testing.T) {
o := newOP(t)
w := o.web()
good := o.claims
try := func(name string, mod func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie), want error, claims func(string) map[string]any) {
t.Helper()
o.claims = good
if claims != nil {
o.claims = claims
}
q, c := o.start(t, w, "/")
cb := url.Values{"code": {"the-code"}, "state": {q.Get("state")}}
if mod != nil {
cb, c = mod(cb, c)
}
s, _, err := callback(w, cb.Encode(), c)
if err == nil || s != nil || want != nil && !errors.Is(err, want) {
t.Errorf("%s: %+v, %v", name, s, err)
}
}
try("no cookie", func(q url.Values, _ *http.Cookie) (url.Values, *http.Cookie) { return q, nil }, ErrSignInState, nil)
try("another state", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Set("state", "x"); return q, c }, ErrSignInState, nil)
try("junk cookie", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { c.Value = "!!"; return q, c }, ErrSignInState, nil)
try("expired", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) {
raw, _ := base64.RawURLEncoding.DecodeString(c.Value)
var v signInCookie
json.Unmarshal(raw, &v)
v.Expires = time.Now().Add(-time.Second).Unix()
raw, _ = json.Marshal(v)
c.Value = base64.RawURLEncoding.EncodeToString(raw)
return q, c
}, ErrSignInState, nil)
try("other issuer", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) {
q.Set("iss", "https://evil.example")
return q, c
}, nil, nil)
try("provider error", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) {
q.Del("code")
q.Set("error", "access_denied")
return q, c
}, ErrSignInRefused, nil)
try("no code", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Del("code"); return q, c }, nil, nil)
try("bad code", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Set("code", "x"); return q, c }, nil, nil)
with := func(k string, v any) func(string) map[string]any {
return func(n string) map[string]any { c := good(n); c[k] = v; return c }
}
try("issuer", nil, nil, with("iss", "https://evil.example"))
try("audience", nil, nil, with("aud", "other"))
try("several audiences, other azp", nil, nil, with("aud", []string{"web", "other"}))
o.userBody = `{"sub":""}`
try("no subject", nil, nil, with("sub", ""))
o.userBody = `{"sub":"u-1"}`
o.noIDToken = true
try("no ID token", nil, nil, nil)
o.noIDToken = false
try("expired token", nil, nil, with("exp", time.Now().Add(-2*time.Minute).Unix()))
try("issued in the future", nil, nil, with("iat", time.Now().Add(2*time.Minute).Unix()))
try("other nonce", nil, nil, with("nonce", "x"))
o.userBody = `{"sub":"u-2","preferred_username":"mallory"}`
try("UserInfo of another user", nil, nil, nil)
// Several audiences with azp this client: fine.
o.userBody = `{"sub":"u-1"}`
o.claims = func(n string) map[string]any {
c := good(n)
c["aud"] = []string{"web", "api"}
c["azp"] = "web"
return c
}
q, c := o.start(t, w, "/")
if _, _, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), c); err != nil {
t.Errorf("azp: %v", err)
}
}
// TestWebConfig: an http redirect URL off loopback, or no openid, is
// refused; a return path elsewhere becomes "/"; the logout URL carries
// the hint and the post-logout redirect.
func TestWebConfig(t *testing.T) {
o := newOP(t)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/login", nil)
bad := o.web()
bad.RedirectURL = "http://app.example.org/callback"
if err := bad.SignIn(context.Background(), rec, req, "/"); err == nil {
t.Error("http redirect URL taken")
}
noOpenID := o.web()
noOpenID.Scopes = []string{"profile"}
if err := noOpenID.SignIn(context.Background(), rec, req, "/"); err == nil {
t.Error("no openid taken")
}
for in, want := range map[string]string{"/a?b=c": "/a?b=c", "//evil.example": "/", "https://evil.example": "/", "/\\evil": "/",
"": "/", "a": "/", "/x\r\nSet-Cookie: y": "/", "/\t/evil.example": "/", "/\t\\evil": "/", "/a\x7f": "/", "/a\\b": "/"} {
if got := localPath(in); got != want {
t.Errorf("localPath(%q) = %q", in, got)
}
}
u, err := o.web().LogoutURL(context.Background(), "the-id-token")
if err != nil {
t.Fatal(err)
}
lu, _ := url.Parse(u)
if !strings.HasPrefix(u, o.ts.URL+"/logout?") || lu.Query().Get("id_token_hint") != "the-id-token" ||
lu.Query().Get("post_logout_redirect_uri") != "http://localhost:8097/" || lu.Query().Get("client_id") != "web" {
t.Errorf("logout URL %s", u)
}
}
// TestDeviceNeedsItsEndpoint: a provider without a device authorization
// endpoint serves a web sign-in, but StartDevice says it has none.
func TestDeviceNeedsItsEndpoint(t *testing.T) {
o := newOP(t)
c := &Client{Issuer: o.issuer, ClientID: "cli"}
if _, err := c.StartDevice(context.Background()); err == nil || !strings.Contains(err.Error(), "no device sign-in") {
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")
}
}
+30 -13
View File
@@ -88,8 +88,16 @@ type Client struct {
// again once the access token runs out.
Scopes []string
// HTTPClient sends the requests; nil means one with a 30 s timeout.
// Redirects are never followed, whichever client it is.
// Redirects are never followed, whichever client it is. It must check
// 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
@@ -103,6 +111,8 @@ type metadata struct {
DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`
RevocationEndpoint string `json:"revocation_endpoint"`
UserinfoEndpoint string `json:"userinfo_endpoint"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
EndSessionEndpoint string `json:"end_session_endpoint"`
}
// httpClient is HTTPClient (or the default) without redirects: an answer
@@ -132,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 == "" {
@@ -157,14 +167,16 @@ 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)
}
for name, u := range map[string]string{"token_endpoint": m.TokenEndpoint, "device_authorization_endpoint": m.DeviceAuthorizationEndpoint} {
if err := checkURL(name, u); err != nil {
return nil, err
}
if err := checkURL("token_endpoint", m.TokenEndpoint, c.AllowInsecure); err != nil {
return nil, err
}
for name, u := range map[string]string{"revocation_endpoint": m.RevocationEndpoint, "userinfo_endpoint": m.UserinfoEndpoint} {
// The others only where a flow needs them (device: StartDevice; web:
// Web.SignIn); those that are named must be https.
for name, u := range map[string]string{"revocation_endpoint": m.RevocationEndpoint, "userinfo_endpoint": m.UserinfoEndpoint,
"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
}
}
@@ -176,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)
@@ -185,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)
@@ -201,16 +213,21 @@ func isLoopback(host string) bool {
// do sends req and reads at most maxBody of the answer.
func (c *Client) do(req *http.Request) (int, []byte, error) {
return c.doMax(req, maxBody)
}
// doMax is do with another limit.
func (c *Client) doMax(req *http.Request, limit int64) (int, []byte, error) {
resp, err := c.httpClient().Do(req)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))
body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
if err != nil {
return 0, nil, err
}
if len(body) > maxBody {
if int64(len(body)) > limit {
return 0, nil, errors.New("answer too large")
}
return resp.StatusCode, body, nil