diff --git a/AGENTS.md b/AGENTS.md index 835addc..c3a1838 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,8 +42,22 @@ Tests use `httptest` servers only -- never a live Atlassian site. - Comments explain why, not what. Every exported identifier has a doc comment. +## 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 +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 +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`). + ## Consumers -`yareco`, `yabaratla`, `yamcp` (all in the yetano meta-repository). A +`yareco`, `yabaratla`, `yamcp` (Atlassian); `yaiam` (its example and +end-to-end test), next `yasta` (`yaiam`). All in the yetano +meta-repository. A breaking API change needs a new minor version and the consumers bumped in the same wave. diff --git a/README.md b/README.md index d88a95d..655975f 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,13 @@ 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) | Standard library only, no third-party dependencies. +`yaiam` signs a command-line program in at yaiam (device flow) and keeps +its tokens; see below. + ## Usage ```go @@ -107,6 +111,39 @@ make # fmt + vet + test (-race) + vulncheck make test ``` +## yaiam + +A command-line program signs its user in at yaiam -- or any OpenID +Connect provider with the device flow -- and keeps the tokens: + +```go +c := &yaiam.Client{Issuer: "https://login.example.org/t/default", ClientID: id} +store := yaiam.FileStore{Path: filepath.Join(stateDir, "token.json")} +c.Login(ctx, store, func(d *yaiam.DeviceAuth) error { + fmt.Printf("Open %s and enter %s\n", d.VerificationURI, d.UserCode) + return nil +}) +err := c.Authorize(ctx, store, req) // Bearer header; refreshes when needed +c.Logout(ctx, store) // revokes at the provider, forgets them +``` + +- Only standards: discovery, device authorization, token endpoint + (device code, refresh token), revocation (RFC 7009), UserInfo. A + public client, no secret. +- `FileStore` keeps the tokens in a 0600 file and refuses one others + may read. A stored token is used only for its own issuer and client; + a refused refresh token removes it (`ErrLoginRequired`). +- Every endpoint must be https (http only on a loopback host), the + discovery document must name exactly the issuer, redirects are never + followed, answers are capped at 1 MiB. Tokens appear in no error, and + `fmt` prints a `Token` without them. +- Checking tokens on the server side is not here: yaiam's + `pkg/httpauth` (JWT against the issuer's keys, optional + introspection). + +The user's guide is yaiam's `docs/manual/yetano-programme.md`; an +example program is yaiam's `examples/device-login`. + ## Versioning A release is a plain semver git tag (`v0.1.0`, ...) on this repository; diff --git a/TODO.md b/TODO.md index bdb12b3..f4f5acf 100644 --- a/TODO.md +++ b/TODO.md @@ -7,6 +7,11 @@ ## 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. + - [ ] **yamcp search on Cloud.** yamcp's `jira_search_issues` still uses `SearchPage` (classic `POST /rest/api/3/search`), which Atlassian has deprecated on Cloud in favour of `/search/jql` (`Search`). Moving diff --git a/yaiam/device.go b/yaiam/device.go new file mode 100644 index 0000000..a6eeb6c --- /dev/null +++ b/yaiam/device.go @@ -0,0 +1,142 @@ +package yaiam + +import ( + "context" + "errors" + "fmt" + "net/url" + "time" +) + +// grantDeviceCode is the device flow's grant type (RFC 8628 section 3.4). +const grantDeviceCode = "urn:ietf:params:oauth:grant-type:device_code" + +// DeviceAuth is a started device sign-in: show the user VerificationURI +// and UserCode (or VerificationURIComplete, which carries the code), then +// call WaitDevice. +type DeviceAuth struct { + // UserCode is what the user enters, e.g. "BCDF-GHJK". + UserCode string + // VerificationURI is the page to enter it on. + VerificationURI string + // VerificationURIComplete is the same page with the code filled in + // (empty if the provider gives none). Fine for a link or a QR code. + VerificationURIComplete string + // Expiry is when the code runs out. + Expiry time.Time + // Interval is how long to wait between two polls. + Interval time.Duration + + deviceCode string +} + +// StartDevice asks for a device sign-in. +func (c *Client) StartDevice(ctx context.Context) (*DeviceAuth, error) { + m, err := c.discover(ctx) + if err != nil { + return nil, err + } + var out struct { + DeviceCode string `json:"device_code"` + UserCode string `json:"user_code"` + VerificationURI string `json:"verification_uri"` + VerificationURIComplete string `json:"verification_uri_complete"` + ExpiresIn int64 `json:"expires_in"` + Interval int64 `json:"interval"` + } + if err := c.post(ctx, "device_authorization", m.DeviceAuthorizationEndpoint, + url.Values{"client_id": {c.ClientID}, "scope": {c.scope()}}, &out); err != nil { + return nil, err + } + if out.DeviceCode == "" || out.UserCode == "" || out.ExpiresIn <= 0 { + 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 { + return nil, err + } + if out.VerificationURIComplete != "" { + if err := checkURL("verification_uri_complete", out.VerificationURIComplete); err != nil { + return nil, err + } + } + interval := time.Duration(out.Interval) * time.Second + if interval <= 0 { + interval = 5 * time.Second // RFC 8628 section 3.2 + } + return &DeviceAuth{ + UserCode: out.UserCode, + VerificationURI: out.VerificationURI, + VerificationURIComplete: out.VerificationURIComplete, + Expiry: time.Now().Add(time.Duration(out.ExpiresIn) * time.Second), + Interval: interval, + deviceCode: out.DeviceCode, + }, nil +} + +// sleep waits d or until ctx ends (a variable so tests need not wait). +var sleep = func(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } +} + +// WaitDevice polls until the user has confirmed d in the browser and +// returns the tokens; ErrDenied if the user declined, ErrExpired if the +// code ran out first. It keeps to the provider's interval and slows down +// when asked to; cancelling ctx stops it. +func (c *Client) WaitDevice(ctx context.Context, d *DeviceAuth) (*Token, error) { + m, err := c.discover(ctx) + if err != nil { + return nil, err + } + interval := d.Interval + for { + if !time.Now().Add(interval).Before(d.Expiry) { + return nil, ErrExpired + } + if err := sleep(ctx, interval); err != nil { + return nil, err + } + t, err := c.tokenRequest(ctx, m, url.Values{"grant_type": {grantDeviceCode}, "device_code": {d.deviceCode}, "client_id": {c.ClientID}}) + switch { + case err == nil: + return t, nil + case isCode(err, "authorization_pending"): + case isCode(err, "slow_down"): + interval += 5 * time.Second // RFC 8628 section 3.5 + case isCode(err, "access_denied"): + return nil, ErrDenied + case isCode(err, "expired_token"): + return nil, ErrExpired + default: + return nil, err + } + } +} + +// Login signs in with the device flow and stores the tokens: show is +// called with the code to show the user (an error from it ends the +// sign-in). +func (c *Client) Login(ctx context.Context, store Store, show func(*DeviceAuth) error) (*Token, error) { + d, err := c.StartDevice(ctx) + if err != nil { + return nil, err + } + if err := show(d); err != nil { + return nil, err + } + t, err := c.WaitDevice(ctx, d) + if err != nil { + return nil, err + } + if err := store.Save(t); err != nil { + return nil, fmt.Errorf("yaiam: keep the tokens: %w", err) + } + return t, nil +} diff --git a/yaiam/token.go b/yaiam/token.go new file mode 100644 index 0000000..d9e51bf --- /dev/null +++ b/yaiam/token.go @@ -0,0 +1,304 @@ +package yaiam + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "time" +) + +// leeway is how long before its expiry an access token is refreshed, so +// it does not run out on its way to the API. +const leeway = time.Minute + +// Token is what a sign-in gives: an access token for the APIs, a refresh +// token for the next one (only with the scope offline_access), and for +// which issuer and client they are. fmt prints it without the tokens. +type Token struct { + Issuer string `json:"issuer"` + ClientID string `json:"client_id"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token,omitempty"` + Expiry time.Time `json:"expiry"` + Scope string `json:"scope,omitempty"` +} + +// String keeps the tokens out of anything printed or logged. +func (t *Token) String() string { + if t == nil { + return "" + } + return fmt.Sprintf("yaiam.Token{Issuer: %q, ClientID: %q, Expiry: %s, Scope: %q, tokens redacted}", + t.Issuer, t.ClientID, t.Expiry.Format(time.RFC3339), t.Scope) +} + +// GoString is String, for %#v. +func (t *Token) GoString() string { return t.String() } + +// tokenRequest posts form to the token endpoint and reads the tokens. +func (c *Client) tokenRequest(ctx context.Context, m *metadata, form url.Values) (*Token, error) { + 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"` + } + if err := c.post(ctx, "token", m.TokenEndpoint, form, &out); 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") + } + return &Token{ + Issuer: c.Issuer, + ClientID: c.ClientID, + AccessToken: out.AccessToken, + RefreshToken: out.RefreshToken, + Expiry: time.Now().Add(time.Duration(out.ExpiresIn) * time.Second), + Scope: out.Scope, + }, nil +} + +// Refresh gets a new access token with t's refresh token. The answer's +// refresh token replaces t's (yaiam hands out a new one each time); keep +// the result, not t. A refused refresh token is ErrLoginRequired. +func (c *Client) Refresh(ctx context.Context, t *Token) (*Token, error) { + if t.RefreshToken == "" { + return nil, ErrLoginRequired + } + m, err := c.discover(ctx) + if err != nil { + return nil, err + } + nt, err := c.tokenRequest(ctx, m, url.Values{"grant_type": {"refresh_token"}, "refresh_token": {t.RefreshToken}, "client_id": {c.ClientID}}) + if isCode(err, "invalid_grant") { + return nil, fmt.Errorf("%w (%w)", ErrLoginRequired, err) + } + if err != nil { + return nil, err + } + if nt.RefreshToken == "" { + nt.RefreshToken = t.RefreshToken + } + return nt, nil +} + +// Token returns a usable access token from store: the stored one, or a +// refreshed one (then stored) when it runs out within a minute. +// ErrLoginRequired when there is none, it belongs to another issuer or +// client, or it cannot be refreshed; a refused refresh token is removed +// from store. Only one process should refresh from one store at a time: +// yaiam takes a refresh token used twice as stolen. +func (c *Client) Token(ctx context.Context, store Store) (*Token, error) { + t, err := store.Load() + if err != nil { + return nil, err + } + if t == nil || t.Issuer != c.Issuer || t.ClientID != c.ClientID || t.AccessToken == "" { + return nil, ErrLoginRequired + } + if time.Until(t.Expiry) > leeway { + return t, nil + } + nt, err := c.Refresh(ctx, t) + if errors.Is(err, ErrLoginRequired) { + if derr := store.Delete(); derr != nil { + return nil, derr + } + return nil, err + } + if err != nil { + return nil, err + } + if err := store.Save(nt); err != nil { + return nil, fmt.Errorf("yaiam: keep the tokens: %w", err) + } + return nt, nil +} + +// Authorize sets req's Authorization header to the access token from +// store (Token). Send req with a client that does not pass the header on +// to other hosts -- net/http's own drops it on a redirect elsewhere. +func (c *Client) Authorize(ctx context.Context, store Store, req *http.Request) error { + t, err := c.Token(ctx, store) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+t.AccessToken) + return nil +} + +// Logout revokes the stored tokens at the provider (the refresh token +// first, which ends the access tokens it made too) and removes them from +// store. The stored tokens are removed even when the provider cannot be +// reached; that error is returned. +func (c *Client) Logout(ctx context.Context, store Store) error { + t, err := store.Load() + if err != nil || t == nil { + return err + } + var revokeErr error + if t.Issuer == c.Issuer && t.ClientID == c.ClientID { + revokeErr = c.revoke(ctx, t) + } + if err := store.Delete(); err != nil { + return err + } + return revokeErr +} + +// revoke revokes t's refresh token and access token (RFC 7009). +func (c *Client) revoke(ctx context.Context, t *Token) error { + m, err := c.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 := c.post(ctx, "revocation", m.RevocationEndpoint, + url.Values{"token": {tok.value}, "token_type_hint": {tok.hint}, "client_id": {c.ClientID}}, nil); err != nil { + return err + } + } + return nil +} + +// UserInfo is who signed in, from the provider's UserInfo endpoint. +type UserInfo struct { + // Subject is the user's ID (yaiam: stays the same on a rename). + Subject string `json:"sub"` + // Username is the user's name, with the scope profile. + Username string `json:"preferred_username"` + // Name is the display name, with the scope profile. + Name string `json:"name"` + // Email is the address, with the scope email. + Email string `json:"email"` +} + +// UserInfo asks the provider who t's user is. +func (c *Client) UserInfo(ctx context.Context, t *Token) (*UserInfo, error) { + m, err := c.discover(ctx) + if err != nil { + return nil, err + } + if m.UserinfoEndpoint == "" { + return nil, errors.New("yaiam: the provider offers no UserInfo") + } + 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 := c.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 UserInfo + if err := json.Unmarshal(body, &u); err != nil { + return nil, fmt.Errorf("yaiam: userinfo: %w", err) + } + if u.Subject == "" { + return nil, errors.New("yaiam: userinfo: no sub in the answer") + } + return &u, nil +} + +// Store keeps a program's tokens between runs. +type Store interface { + // Load returns the stored tokens, nil (and no error) if there are none. + Load() (*Token, error) + // Save replaces the stored tokens. + Save(*Token) error + // Delete removes them; no error if there are none. + Delete() error +} + +// FileStore keeps the tokens as JSON in a file only its owner may read +// (0600, in a directory created 0700), e.g. in the program's state +// directory from core/paths. Load refuses a file others may read: the +// refresh token is as good as a sign-in. (On Windows, where the mode +// bits mean nothing, the file's place in the user's profile protects it.) +type FileStore struct { + Path string +} + +// Load reads the file; nil if there is none. +func (s FileStore) Load() (*Token, error) { + f, err := os.Open(s.Path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + defer f.Close() + if runtime.GOOS != "windows" { + info, err := f.Stat() + if err != nil { + return nil, err + } + if info.Mode().Perm()&0o077 != 0 { + return nil, fmt.Errorf("yaiam: token file %s is accessible to others (mode %s): chmod 600 it", s.Path, info.Mode().Perm()) + } + } + var t Token + if err := json.NewDecoder(f).Decode(&t); err != nil { + return nil, fmt.Errorf("yaiam: token file %s: %w", s.Path, err) + } + return &t, nil +} + +// Save writes the file through a temporary one next to it, so a crash +// leaves the old tokens or the new ones, never half of them. +func (s FileStore) Save(t *Token) error { + dir := filepath.Dir(s.Path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + data, err := json.Marshal(t) + if err != nil { + return err + } + f, err := os.CreateTemp(dir, filepath.Base(s.Path)+".*") // mode 0600 + if err != nil { + return err + } + defer os.Remove(f.Name()) // after the rename: nothing left to remove + if _, err := f.Write(data); err != nil { + f.Close() + return err + } + if err := f.Sync(); err != nil { + f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(f.Name(), s.Path) +} + +// Delete removes the file. +func (s FileStore) Delete() error { + if err := os.Remove(s.Path); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil +} diff --git a/yaiam/yaiam.go b/yaiam/yaiam.go new file mode 100644 index 0000000..84275a0 --- /dev/null +++ b/yaiam/yaiam.go @@ -0,0 +1,266 @@ +// Package yaiam signs a command-line program in at yaiam -- or any +// OpenID Connect provider with the device authorization grant (RFC 8628) +// -- and keeps its tokens: the user confirms a short code in a browser, +// the program gets an access and a refresh token, stores them in a file +// only its owner may read and refreshes the access token when it runs +// out. Server-side checking of the tokens is not here: a Go service uses +// yaiam's pkg/httpauth (or any JWT library, or introspection). +// +// Only standards, no yaiam-specific endpoint: discovery, the device +// authorization endpoint, the token endpoint (device code and refresh +// token grants), revocation (RFC 7009) and UserInfo. The client is a +// public client (no secret) that yaiam allows the device flow +// ("yaiam-ctl client add --public --device-flow"). +// +// Tokens never appear in an error or in what fmt prints for a Token. +// Every endpoint must be https; plain http only on a loopback host, for +// a local test installation. +package yaiam + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +// DefaultScopes are asked for when Client.Scopes is nil: an OpenID +// Connect sign-in with the user's name, and a refresh token. +var DefaultScopes = []string{"openid", "profile", "offline_access"} + +// maxBody is the most read of any answer. +const maxBody = 1 << 20 + +var ( + // ErrLoginRequired means there is no usable token: none stored, one + // for another issuer or client, or the refresh token was refused + // (expired, revoked, the user locked). Sign in again (Login). + ErrLoginRequired = errors.New("yaiam: sign-in required") + // ErrDenied means the user declined the sign-in in the browser. + ErrDenied = errors.New("yaiam: the sign-in was denied") + // ErrExpired means the code ran out before the user confirmed it. + ErrExpired = errors.New("yaiam: the code expired before the sign-in was confirmed") +) + +// Error is an OAuth error answer (RFC 6749 section 5.2) or another +// answer an endpoint should not have given. +type Error struct { + // Endpoint names what answered: "discovery", "device_authorization", + // "token", "revocation", "userinfo". + Endpoint string + // Status is the HTTP status. + Status int + // Code is the OAuth error code ("invalid_grant", ...), empty if the + // answer had none. + Code string + // Description is the server's error_description, if any. + Description string +} + +func (e *Error) Error() string { + s := fmt.Sprintf("yaiam: %s: HTTP %d", e.Endpoint, e.Status) + if e.Code != "" { + s += ": " + e.Code + } + if e.Description != "" { + s += ": " + e.Description + } + return s +} + +// Client talks to one issuer as one public client. Its fields must not +// change once it is in use; it is safe for concurrent use. +type Client struct { + // Issuer is the issuer URL exactly as the provider names it, e.g. + // "https://login.example.org/t/default" (yaiam: one per tenant). + Issuer string + // ClientID is the public client's ID. + ClientID string + // Scopes are asked for at sign-in; nil means DefaultScopes. Without + // "offline_access" there is no refresh token: the program signs in + // 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. + HTTPClient *http.Client + + mu sync.Mutex + meta *metadata + hc *http.Client +} + +// metadata is what Client uses of the provider's discovery document. +type metadata struct { + Issuer string `json:"issuer"` + TokenEndpoint string `json:"token_endpoint"` + DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"` + RevocationEndpoint string `json:"revocation_endpoint"` + UserinfoEndpoint string `json:"userinfo_endpoint"` +} + +// httpClient is HTTPClient (or the default) without redirects: an answer +// that sends us elsewhere is an error, so a token or code never follows +// it. +func (c *Client) httpClient() *http.Client { + c.mu.Lock() + defer c.mu.Unlock() + if c.hc == nil { + hc := http.Client{Timeout: 30 * time.Second} + if c.HTTPClient != nil { + hc = *c.HTTPClient + } + hc.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + c.hc = &hc + } + return c.hc +} + +// discover fetches the discovery document once and checks it: the issuer +// it names is exactly Issuer, and every endpoint is https (or http on a +// loopback host). +func (c *Client) discover(ctx context.Context) (*metadata, error) { + c.mu.Lock() + m := c.meta + c.mu.Unlock() + if m != nil { + return m, nil + } + if err := checkURL("issuer", c.Issuer); err != nil { + return nil, err + } + if c.ClientID == "" { + return nil, errors.New("yaiam: no client ID") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(c.Issuer, "/")+"/.well-known/openid-configuration", nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + status, body, err := c.do(req) + if err != nil { + return nil, fmt.Errorf("yaiam: discovery: %w", err) + } + if status != http.StatusOK { + return nil, &Error{Endpoint: "discovery", Status: status} + } + m = new(metadata) + if err := json.Unmarshal(body, m); err != nil { + return nil, fmt.Errorf("yaiam: discovery: %w", err) + } + 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 + } + } + for name, u := range map[string]string{"revocation_endpoint": m.RevocationEndpoint, "userinfo_endpoint": m.UserinfoEndpoint} { + if u != "" { + if err := checkURL(name, u); err != nil { + return nil, err + } + } + } + c.mu.Lock() + c.meta = m + c.mu.Unlock() + return m, nil +} + +// checkURL refuses anything but an absolute https URL, or http on a +// loopback host. +func checkURL(name, s string) error { + u, err := url.Parse(s) + if err != nil || u.Host == "" { + return fmt.Errorf("yaiam: %s %q is not an absolute URL", name, s) + } + switch { + case u.Scheme == "https": + return nil + case u.Scheme == "http" && isLoopback(u.Hostname()): + return nil + } + return fmt.Errorf("yaiam: %s %q is not https", name, s) +} + +func isLoopback(host string) bool { + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +// do sends req and reads at most maxBody of the answer. +func (c *Client) do(req *http.Request) (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)) + if err != nil { + return 0, nil, err + } + if len(body) > maxBody { + return 0, nil, errors.New("answer too large") + } + return resp.StatusCode, body, nil +} + +// post sends form to endpoint. A 200 answer is decoded into out; any +// other is returned as *Error. +func (c *Client) post(ctx context.Context, name, endpoint string, form url.Values, out any) error { + 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") + status, body, err := c.do(req) + if err != nil { + return fmt.Errorf("yaiam: %s: %w", name, err) + } + if status != http.StatusOK { + return oauthError(name, status, body) + } + if out == nil { + return nil + } + if err := json.Unmarshal(body, out); err != nil { + return fmt.Errorf("yaiam: %s: %w", name, err) + } + return nil +} + +// oauthError reads an OAuth error answer; a body that is not one leaves +// Code empty. +func oauthError(name string, status int, body []byte) *Error { + var e struct { + Code string `json:"error"` + Description string `json:"error_description"` + } + json.Unmarshal(body, &e) + return &Error{Endpoint: name, Status: status, Code: e.Code, Description: e.Description} +} + +// isCode tells whether err is an OAuth error with this code. +func isCode(err error, code string) bool { + var e *Error + return errors.As(err, &e) && e.Code == code +} + +func (c *Client) scope() string { + if c.Scopes == nil { + return strings.Join(DefaultScopes, " ") + } + return strings.Join(c.Scopes, " ") +} diff --git a/yaiam/yaiam_test.go b/yaiam/yaiam_test.go new file mode 100644 index 0000000..6aadaed --- /dev/null +++ b/yaiam/yaiam_test.go @@ -0,0 +1,476 @@ +package yaiam + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +// provider is a fake OpenID provider: polls answers the queued token +// endpoint answers to device code polls, in order; refresh the answer to +// a refresh. +type provider struct { + t *testing.T + ts *httptest.Server + issuer string + + mu sync.Mutex + polls []string // error codes, "" for the tokens + refresh string // error code, "" for new tokens + revoked []string + forms []map[string]string + userinfo string // the bearer token UserInfo accepts + userBody string // what UserInfo answers, default a user + verifURI string + noComplete bool // no verification_uri_complete + noRefresh bool // a refresh answer without a new refresh token +} + +func newProvider(t *testing.T) *provider { + p := &provider{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": p.issuer, + "token_endpoint": p.ts.URL + "/token", + "device_authorization_endpoint": p.ts.URL + "/device_authorization", + "revocation_endpoint": p.ts.URL + "/revoke", + "userinfo_endpoint": p.ts.URL + "/userinfo", + }) + }) + mux.HandleFunc("POST /device_authorization", func(w http.ResponseWriter, r *http.Request) { + p.record(r) + verif := p.verifURI + if verif == "" { + verif = p.ts.URL + "/device" + } + out := map[string]any{"device_code": "the-device-code", "user_code": "BCDF-GHJK", + "verification_uri": verif, "verification_uri_complete": verif + "?user_code=BCDF-GHJK", "expires_in": 600, "interval": 2} + if p.noComplete { + delete(out, "verification_uri_complete") + } + json.NewEncoder(w).Encode(out) + }) + mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) { + form := p.record(r) + p.mu.Lock() + defer p.mu.Unlock() + code := p.refresh + if form["grant_type"] == grantDeviceCode { + if len(p.polls) == 0 { + t.Error("polled too often") + code = "invalid_request" + } else { + code, p.polls = p.polls[0], p.polls[1:] + } + } + if code != "" { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, `{"error":%q,"error_description":"said the server"}`, code) + return + } + n := len(p.forms) + out := map[string]any{"access_token": fmt.Sprintf("access-%d", n), "token_type": "Bearer", + "expires_in": 600, "refresh_token": fmt.Sprintf("refresh-%d", n), "scope": "openid offline_access"} + if p.noRefresh && form["grant_type"] == "refresh_token" { + delete(out, "refresh_token") + } + json.NewEncoder(w).Encode(out) + }) + mux.HandleFunc("POST /revoke", func(w http.ResponseWriter, r *http.Request) { + form := p.record(r) + p.mu.Lock() + p.revoked = append(p.revoked, form["token_type_hint"]+":"+form["token"]) + p.mu.Unlock() + }) + mux.HandleFunc("GET /userinfo", func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer "+p.userinfo { + w.WriteHeader(http.StatusUnauthorized) + return + } + if p.userBody != "" { + fmt.Fprint(w, p.userBody) + return + } + fmt.Fprint(w, `{"sub":"u-1","preferred_username":"alice","name":"Alice"}`) + }) + p.ts = httptest.NewServer(mux) + t.Cleanup(p.ts.Close) + p.issuer = p.ts.URL + "/t/default" + return p +} + +// record keeps a request's form. +func (p *provider) record(r *http.Request) map[string]string { + r.ParseForm() + form := map[string]string{} + for k := range r.PostForm { + form[k] = r.PostForm.Get(k) + } + p.mu.Lock() + p.forms = append(p.forms, form) + p.mu.Unlock() + return form +} + +func (p *provider) client() *Client { + return &Client{Issuer: p.issuer, ClientID: "cli"} +} + +// noSleep replaces the poll wait for a test and records the waits. +func noSleep(t *testing.T) *[]time.Duration { + var waits []time.Duration + old := sleep + sleep = func(ctx context.Context, d time.Duration) error { + waits = append(waits, d) + return ctx.Err() + } + t.Cleanup(func() { sleep = old }) + return &waits +} + +func store(t *testing.T) FileStore { + return FileStore{Path: filepath.Join(t.TempDir(), "state", "token.json")} +} + +func TestLogin(t *testing.T) { + p := newProvider(t) + waits := noSleep(t) + p.polls = []string{"authorization_pending", "slow_down", "authorization_pending", ""} + s := store(t) + c := p.client() + var shown *DeviceAuth + tok, err := c.Login(context.Background(), s, func(d *DeviceAuth) error { shown = d; return nil }) + if err != nil { + t.Fatal(err) + } + if shown.UserCode != "BCDF-GHJK" || shown.VerificationURI != p.ts.URL+"/device" || + shown.VerificationURIComplete != p.ts.URL+"/device?user_code=BCDF-GHJK" || shown.Interval != 2*time.Second { + t.Errorf("shown %+v", shown) + } + // The provider's interval, 5 s more after slow_down. + if fmt.Sprint(*waits) != "[2s 2s 7s 7s]" { + t.Errorf("waits = %v", *waits) + } + if tok.Issuer != p.issuer || tok.ClientID != "cli" || tok.AccessToken == "" || tok.RefreshToken == "" || time.Until(tok.Expiry) < 9*time.Minute { + t.Errorf("token = %+v", tok) + } + start, poll := p.forms[0], p.forms[1] + if start["client_id"] != "cli" || start["scope"] != "openid profile offline_access" { + t.Errorf("device authorization form %v", start) + } + if poll["grant_type"] != grantDeviceCode || poll["device_code"] != "the-device-code" || poll["client_id"] != "cli" { + t.Errorf("poll form %v", poll) + } + got, err := s.Load() + if err != nil || got.AccessToken != tok.AccessToken || got.RefreshToken != tok.RefreshToken { + t.Fatalf("stored %v, %v", got, err) + } + if runtime.GOOS != "windows" { + info, _ := os.Stat(s.Path) + dir, _ := os.Stat(filepath.Dir(s.Path)) + if info.Mode().Perm() != 0o600 || dir.Mode().Perm() != 0o700 { + t.Errorf("modes %v, %v", info.Mode(), dir.Mode()) + } + } + // What a show error does: no polling. + p.forms = nil + if _, err := c.Login(context.Background(), s, func(*DeviceAuth) error { return errors.New("no terminal") }); err == nil || len(p.forms) != 1 { + t.Errorf("show error: %v, %d requests", err, len(p.forms)) + } +} + +func TestWaitDeviceEnds(t *testing.T) { + for _, tc := range []struct { + code string + want error + }{ + {"access_denied", ErrDenied}, + {"expired_token", ErrExpired}, + {"invalid_client", nil}, + } { + t.Run(tc.code, func(t *testing.T) { + p := newProvider(t) + noSleep(t) + p.polls = []string{"authorization_pending", tc.code} + c := p.client() + d, err := c.StartDevice(context.Background()) + if err != nil { + t.Fatal(err) + } + _, err = c.WaitDevice(context.Background(), d) + if tc.want != nil && !errors.Is(err, tc.want) { + t.Errorf("err = %v, want %v", err, tc.want) + } + if tc.want == nil && !isCode(err, tc.code) { + t.Errorf("err = %v, want the OAuth error %s", err, tc.code) + } + }) + } + // The code runs out here before the provider says so. + p := newProvider(t) + noSleep(t) + c := p.client() + d, _ := c.StartDevice(context.Background()) + d.Expiry = time.Now().Add(time.Second) + if _, err := c.WaitDevice(context.Background(), d); !errors.Is(err, ErrExpired) || len(p.forms) != 1 { + t.Errorf("err = %v after %d requests", err, len(p.forms)) + } + // Cancelling ends the wait. + ctx, cancel := context.WithCancel(context.Background()) + cancel() + d, _ = c.StartDevice(context.Background()) + if _, err := c.WaitDevice(ctx, d); !errors.Is(err, context.Canceled) { + t.Errorf("cancelled: %v", err) + } +} + +func TestToken(t *testing.T) { + p := newProvider(t) + c := p.client() + ctx := context.Background() + s := store(t) + if _, err := c.Token(ctx, s); !errors.Is(err, ErrLoginRequired) { + t.Errorf("no file: %v", err) + } + + fresh := &Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r0", Expiry: time.Now().Add(5 * time.Minute)} + s.Save(fresh) + if got, err := c.Token(ctx, s); err != nil || got.AccessToken != "a0" || len(p.forms) != 0 { + t.Errorf("fresh token: %v, %v, %d requests", got, err, len(p.forms)) + } + req, _ := http.NewRequest(http.MethodGet, "https://api.example.org/", nil) + if err := c.Authorize(ctx, s, req); err != nil || req.Header.Get("Authorization") != "Bearer a0" { + t.Errorf("Authorize: %v, %q", err, req.Header.Get("Authorization")) + } + + // Another issuer's or client's token is not sent here. + for _, other := range []*Token{ + {Issuer: "https://elsewhere.example.org", ClientID: "cli", AccessToken: "a0", Expiry: fresh.Expiry}, + {Issuer: p.issuer, ClientID: "other", AccessToken: "a0", Expiry: fresh.Expiry}, + } { + s.Save(other) + if _, err := c.Token(ctx, s); !errors.Is(err, ErrLoginRequired) { + t.Errorf("token of %s/%s: %v", other.Issuer, other.ClientID, err) + } + } + + // Running out within a minute: refreshed and stored. + s.Save(&Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r0", Expiry: time.Now().Add(30 * time.Second)}) + got, err := c.Token(ctx, s) + if err != nil || got.AccessToken == "a0" || got.RefreshToken == "r0" { + t.Fatalf("refresh: %v, %v", got, err) + } + if f := p.forms[0]; f["grant_type"] != "refresh_token" || f["refresh_token"] != "r0" || f["client_id"] != "cli" { + t.Errorf("refresh form %v", f) + } + if stored, _ := s.Load(); stored.AccessToken != got.AccessToken || stored.RefreshToken != got.RefreshToken { + t.Errorf("stored %v", stored) + } + + // An answer without a new refresh token keeps the old one. + p.noRefresh = true + s.Save(&Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r0", Expiry: time.Now()}) + if got, err := c.Token(ctx, s); err != nil || got.RefreshToken != "r0" { + t.Errorf("refresh without a new refresh token: %v, %v", got, err) + } + p.noRefresh = false + + // No refresh token: sign in again. + s.Save(&Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", Expiry: time.Now()}) + if _, err := c.Token(ctx, s); !errors.Is(err, ErrLoginRequired) { + t.Errorf("without refresh token: %v", err) + } + + // A refused refresh token: sign in again, and the file is gone. + p.refresh = "invalid_grant" + s.Save(&Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r-secret", Expiry: time.Now()}) + _, err = c.Token(ctx, s) + if !errors.Is(err, ErrLoginRequired) || !isCode(err, "invalid_grant") || strings.Contains(err.Error(), "r-secret") { + t.Errorf("refused refresh: %v", err) + } + if _, err := os.Stat(s.Path); !os.IsNotExist(err) { + t.Errorf("token file kept: %v", err) + } + + // Any other failure keeps the file. + p.refresh = "temporarily_unavailable" + s.Save(&Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r0", Expiry: time.Now()}) + if _, err := c.Token(ctx, s); err == nil || errors.Is(err, ErrLoginRequired) { + t.Errorf("server trouble: %v", err) + } + if t2, _ := s.Load(); t2 == nil { + t.Error("token file removed on server trouble") + } +} + +func TestLogoutAndUserInfo(t *testing.T) { + p := newProvider(t) + c := p.client() + ctx := context.Background() + s := store(t) + tok := &Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r0", Expiry: time.Now().Add(time.Hour)} + s.Save(tok) + + p.userinfo = "a0" + u, err := c.UserInfo(ctx, tok) + if err != nil || u.Subject != "u-1" || u.Username != "alice" || u.Name != "Alice" { + t.Errorf("userinfo %+v, %v", u, err) + } + p.userBody = `{"preferred_username":"alice"}` + if _, err := c.UserInfo(ctx, tok); err == nil { + t.Error("userinfo without sub accepted") + } + p.userBody = "" + p.userinfo = "other" + if _, err := c.UserInfo(ctx, tok); err == nil { + t.Error("userinfo with a refused token") + } + + if err := c.Logout(ctx, s); err != nil { + t.Fatal(err) + } + if fmt.Sprint(p.revoked) != "[refresh_token:r0 access_token:a0]" || p.forms[0]["client_id"] != "cli" { + t.Errorf("revoked %v", p.revoked) + } + if t2, _ := s.Load(); t2 != nil { + t.Error("tokens kept after logout") + } + if err := c.Logout(ctx, s); err != nil { + t.Errorf("logout without tokens: %v", err) + } + + // The provider cannot be reached: the tokens go anyway. + s.Save(tok) + p.ts.Close() + gone := &Client{Issuer: p.issuer, ClientID: "cli"} + if err := gone.Logout(ctx, s); err == nil { + t.Error("no error without the provider") + } + if t2, _ := s.Load(); t2 != nil { + t.Error("tokens kept when the provider is gone") + } +} + +func TestDiscoveryChecks(t *testing.T) { + ctx := context.Background() + p := newProvider(t) + noSleep(t) + + // The discovery document must name exactly this issuer. + wrong := &Client{Issuer: p.issuer + "/", ClientID: "cli"} + if _, err := wrong.StartDevice(ctx); err == nil || !strings.Contains(err.Error(), "names the issuer") { + t.Errorf("other issuer: %v", err) + } + for _, issuer := range []string{"http://login.example.org/t/default", "ftp://localhost/x", "/t/default", ""} { + c := &Client{Issuer: issuer, ClientID: "cli"} + if _, err := c.StartDevice(ctx); err == nil { + t.Errorf("issuer %q accepted", issuer) + } + } + if _, err := (&Client{Issuer: p.issuer}).StartDevice(ctx); err == nil { + t.Error("no client ID accepted") + } + + // A verification page that is not https is not shown. + p.verifURI = "http://phish.example.org/device" + for _, noComplete := range []bool{false, true} { + p.noComplete = noComplete + if _, err := p.client().StartDevice(ctx); err == nil { + t.Errorf("http verification_uri accepted (without complete: %v)", noComplete) + } + } +} + +// TestEndpointsNotHTTPS: endpoints of the discovery document must be https. +func TestEndpointsNotHTTPS(t *testing.T) { + var ts *httptest.Server + ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(map[string]string{"issuer": ts.URL, "token_endpoint": "http://login.example.org/token", + "device_authorization_endpoint": ts.URL + "/device_authorization"}) + })) + defer ts.Close() + if _, err := (&Client{Issuer: ts.URL, ClientID: "cli"}).StartDevice(context.Background()); err == nil || !strings.Contains(err.Error(), "token_endpoint") { + t.Errorf("http token endpoint: %v", err) + } +} + +// TestNoRedirects: a token request is never sent on to where an answer +// points. +func TestNoRedirects(t *testing.T) { + var hit bool + elsewhere := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hit = true })) + defer elsewhere.Close() + var ts *httptest.Server + ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/token" { + http.Redirect(w, r, elsewhere.URL+"/token", http.StatusTemporaryRedirect) + return + } + json.NewEncoder(w).Encode(map[string]string{"issuer": ts.URL, "token_endpoint": ts.URL + "/token", + "device_authorization_endpoint": ts.URL + "/device_authorization"}) + })) + defer ts.Close() + c := &Client{Issuer: ts.URL, ClientID: "cli", HTTPClient: &http.Client{}} + _, err := c.Refresh(context.Background(), &Token{RefreshToken: "r-secret"}) + if err == nil || hit || strings.Contains(err.Error(), "r-secret") { + t.Errorf("redirect: err %v, followed %v", err, hit) + } +} + +func TestAnswerTooLarge(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"issuer":"`)) + w.Write([]byte(strings.Repeat("x", maxBody))) + })) + defer ts.Close() + if _, err := (&Client{Issuer: ts.URL, ClientID: "cli"}).StartDevice(context.Background()); err == nil || !strings.Contains(err.Error(), "too large") { + t.Errorf("large answer: %v", err) + } +} + +func TestTokenPrintsNoSecrets(t *testing.T) { + tok := &Token{Issuer: "https://login.example.org", ClientID: "cli", AccessToken: "secret-access", RefreshToken: "secret-refresh"} + for _, format := range []string{"%v", "%+v", "%#v", "%s"} { + if out := fmt.Sprintf(format, tok); strings.Contains(out, "secret") { + t.Errorf("%s prints %s", format, out) + } + } +} + +func TestFileStore(t *testing.T) { + s := store(t) + if tok, err := s.Load(); tok != nil || err != nil { + t.Errorf("no file: %v, %v", tok, err) + } + if err := s.Delete(); err != nil { + t.Errorf("delete without file: %v", err) + } + s.Save(&Token{AccessToken: "a"}) + if runtime.GOOS != "windows" { + os.Chmod(s.Path, 0o644) + if _, err := s.Load(); err == nil || !strings.Contains(err.Error(), "accessible to others") { + t.Errorf("0644 file: %v", err) + } + os.Chmod(s.Path, 0o600) + } + os.WriteFile(s.Path, []byte("{"), 0o600) + if _, err := s.Load(); err == nil { + t.Error("broken file accepted") + } + // Nothing but the file is left behind. + s.Save(&Token{AccessToken: "b"}) + if entries, _ := os.ReadDir(filepath.Dir(s.Path)); len(entries) != 1 { + t.Errorf("left behind: %v", entries) + } +}