2 Commits
Author SHA1 Message Date
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
terminarandClaude Opus 5.5 4bff8798e5 yaiam: device-flow sign-in for Yetano programs (YAIAM-710)
A shared client for programs that sign in at yaiam (or any OIDC
provider): device flow (RFC 8628), refresh with rotation, revocation
(RFC 7009), UserInfo and a 0600 file store. Standard library only;
https only (http on loopback), exact issuer match, no redirects,
answers capped at 1 MiB, tokens never in errors or fmt output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 21:40:58 +01:00
12 changed files with 2412 additions and 1 deletions

No files matched your search

+21 -1
View File
@@ -42,8 +42,28 @@ Tests use `httptest` servers only -- never a live Atlassian site.
- Comments explain why, not what. Every exported identifier has a doc - Comments explain why, not what. Every exported identifier has a doc
comment. comment.
## yaiam
`yaiam` signs a CLI in at yaiam over standards only (device flow,
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
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 ## 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 breaking API change needs a new minor version and the consumers bumped
in the same wave. in the same wave.
+72
View File
@@ -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/jira` | Jira REST API client (Cloud v3 and Server/Data Center v2) |
| `atlassian/confluence` | small Confluence REST API client (classic content API) | | `atlassian/confluence` | small Confluence REST API client (classic content API) |
| `atlassian/internal/transport` | the HTTP machinery both share; not importable from outside | | `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); 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. 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 ## Usage
```go ```go
@@ -107,6 +111,74 @@ make # fmt + vet + test (-race) + vulncheck
make test 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`.
### 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.
`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 ## Versioning
A release is a plain semver git tag (`v0.1.0`, ...) on this repository; A release is a plain semver git tag (`v0.1.0`, ...) on this repository;
+9
View File
@@ -7,6 +7,15 @@
## Open ## Open
- [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.
- [ ] **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 - [ ] **yamcp search on Cloud.** yamcp's `jira_search_issues` still
uses `SearchPage` (classic `POST /rest/api/3/search`), which Atlassian uses `SearchPage` (classic `POST /rest/api/3/search`), which Atlassian
has deprecated on Cloud in favour of `/search/jql` (`Search`). Moving has deprecated on Cloud in favour of `/search/jql` (`Search`). Moving
+2
View File
@@ -1,3 +1,5 @@
module yetano.dev/yetano/yetano-clients module yetano.dev/yetano/yetano-clients
go 1.25.0 go 1.25.0
toolchain go1.27.4
+198
View File
@@ -0,0 +1,198 @@
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"`
}
// 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); 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"}`)
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 {
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)
}
}
+145
View File
@@ -0,0 +1,145 @@
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
}
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"`
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
}
+304
View File
@@ -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 "<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
}
+442
View File
@@ -0,0 +1,442 @@
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, and their groups and roles at yaiam (the client must be
// allowed "groups" and "roles").
var WebScopes = []string{"openid", "profile", "email", "groups", "roles"}
// 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
// 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
// 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); err != nil {
return err
}
if w.PostLogoutRedirectURL != "" {
if err := checkURL("post-logout redirect URL", w.PostLogoutRedirectURL); err != nil {
return err
}
}
scopes := WebScopes
if w.Scopes != nil {
scopes = w.Scopes
}
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 := 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 {
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")
}
out.Username, out.Name, out.Email, out.EmailVerified, out.Groups, out.Roles = u.Username, u.Name, u.Email, u.EmailVerified, u.Groups, u.Roles
}
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 bool `json:"email_verified"`
Groups []string `json:"groups"`
Roles []string `json:"roles"`
}
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 m.EndSessionEndpoint + sep + q.Encode(), nil
}
+329
View File
@@ -0,0 +1,329 @@
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"]}`
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" || 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.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)
}
}
+277
View File
@@ -0,0 +1,277 @@
// 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, " ")
}
+476
View File
@@ -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)
}
}