Files
yetano-clients/yaiam/yaiam.go
T
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

278 lines
8.8 KiB
Go

// 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 <name> --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. 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
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"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
EndSessionEndpoint string `json:"end_session_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)
}
if err := checkURL("token_endpoint", m.TokenEndpoint); err != nil {
return nil, err
}
// 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 {
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) {
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, limit+1))
if err != nil {
return 0, nil, err
}
if int64(len(body)) > limit {
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, " ")
}