304 lines
9.1 KiB
Go
304 lines
9.1 KiB
Go
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 "<nil>"
|
||
|
|
}
|
||
|
|
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
|
||
|
|
}
|