Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d062f559f | ||
|
|
c2a5e3928a | ||
|
|
560a1ead8a | ||
|
|
76543b23a0 | ||
|
|
376ae3c970 | ||
|
|
538a6c8ae6 | ||
|
|
a3e8f9bb3b |
No files matched your search
@@ -45,11 +45,18 @@ Tests use `httptest` servers only -- never a live Atlassian site.
|
|||||||
## yaiam
|
## yaiam
|
||||||
|
|
||||||
`yaiam` signs a CLI in at yaiam over standards only (device flow,
|
`yaiam` signs a CLI in at yaiam over standards only (device flow,
|
||||||
refresh, revocation, UserInfo). It holds no secret and verifies no
|
refresh, revocation, UserInfo), and a web application's users (`Web`:
|
||||||
token signature -- no crypto here; servers check tokens with yaiam's
|
code flow with PKCE, state and nonce in a short browser cookie). It
|
||||||
`pkg/httpauth`. Never log a token or put one into an error, never follow
|
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
|
a redirect with one, never accept an endpoint that is not https (http
|
||||||
only on loopback), and never send a stored token to another issuer or
|
only on loopback, or anywhere with the explicit `AllowInsecure` of a test
|
||||||
|
installation), and never send a stored token to another issuer or
|
||||||
client than the one it came from. Tests use a fake provider
|
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
|
(`httptest`); the end-to-end test against a real yaiam-authd is in
|
||||||
yaiam (`internal/oidcprovider/devicelogin_test.go`).
|
yaiam (`internal/oidcprovider/devicelogin_test.go`).
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ Today it holds the Atlassian clients that `yareco`, `yabaratla` and
|
|||||||
| `atlassian/jira` | Jira REST API client (Cloud v3 and Server/Data Center v2) |
|
| `atlassian/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) |
|
| `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); trade a user's token for one at another service, for an agent (token exchange, RFC 8693, 2026-11-21); refresh and revoke a web sign-in's tokens (2026-11-28); fetch an SSH certificate for a public key (ADR-0046, 2026-11-29) |
|
||||||
|
|
||||||
Standard library only, no third-party dependencies.
|
Standard library only, no third-party dependencies.
|
||||||
|
|
||||||
@@ -144,6 +144,98 @@ c.Logout(ctx, store) // revokes at the provider, forgets them
|
|||||||
The user's guide is yaiam's `docs/manual/yetano-programme.md`; an
|
The user's guide is yaiam's `docs/manual/yetano-programme.md`; an
|
||||||
example program is yaiam's `examples/device-login`.
|
example program is yaiam's `examples/device-login`.
|
||||||
|
|
||||||
|
### Web applications
|
||||||
|
|
||||||
|
A web application signs its users in with `Web` (authorization code
|
||||||
|
flow with PKCE, a confidential or a public client):
|
||||||
|
|
||||||
|
```go
|
||||||
|
web := &yaiam.Web{
|
||||||
|
Client: yaiam.Client{Issuer: "https://login.example.org/t/default", ClientID: id},
|
||||||
|
ClientSecret: secret,
|
||||||
|
RedirectURL: "https://app.example.org/callback",
|
||||||
|
}
|
||||||
|
web.SignIn(ctx, w, r, "/after") // GET /login: redirect to yaiam
|
||||||
|
u, err := web.Callback(ctx, w, r) // GET /callback: u.Subject, u.Groups, u.Roles, u.ACR ...
|
||||||
|
out, _ := web.LogoutURL(ctx, u.IDToken)
|
||||||
|
```
|
||||||
|
|
||||||
|
- `SignIn` keeps a fresh state, nonce and PKCE verifier in a ten-minute
|
||||||
|
cookie of the browser (HttpOnly, SameSite=Lax, `__Host-` and Secure
|
||||||
|
on https); `Callback` checks the state against it and removes it.
|
||||||
|
The return path is a local path only.
|
||||||
|
- The ID token comes straight from the token endpoint over TLS, so its
|
||||||
|
signature is not checked (OpenID Connect Core 3.1.3.7) -- no crypto
|
||||||
|
here: iss, aud (and azp), exp, iat and the nonce are. Profile, groups
|
||||||
|
and roles come from UserInfo, which must name the same subject.
|
||||||
|
- The application keeps its own session and its own data under
|
||||||
|
`Subject` -- it stays when the user is renamed.
|
||||||
|
- Any OpenID Connect provider works, not only yaiam: set `Scopes` to
|
||||||
|
what it offers (e.g. `openid email profile`; the default asks for
|
||||||
|
yaiam's groups, roles and attributes). `EmailVerified` is true only
|
||||||
|
for the JSON boolean `true` (some providers send the string).
|
||||||
|
- `PublicIssuer`: when the application reaches the provider under
|
||||||
|
another name than the browser does (a container network), the browser
|
||||||
|
is sent to the endpoints on the public origin; the server keeps
|
||||||
|
`Issuer`. `AllowInsecure` (on `Client`) accepts plain http off
|
||||||
|
loopback, for a test installation on a closed network only.
|
||||||
|
- With `offline_access` in `Scopes` the sign-in's `Token` has a refresh
|
||||||
|
token: `web.Refresh(ctx, tok)` gets the next access token (client
|
||||||
|
secret in a Basic header for a confidential client; keep the result,
|
||||||
|
its refresh token replaces the old one; a refused one is
|
||||||
|
`ErrLoginRequired`), and `web.Revoke(ctx, tok)` ends both at sign-out.
|
||||||
|
|
||||||
|
`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`.
|
||||||
|
|
||||||
|
### SSH certificates
|
||||||
|
|
||||||
|
A tenant of yaiam can be an SSH certificate authority (yaiam ADR-0046).
|
||||||
|
Sign the user in with the scope `ssh` (the client needs it and the
|
||||||
|
audience `yaiam.SSHAudience(issuer)` in yaiam), then trade the access
|
||||||
|
token and a public key for a short-lived OpenSSH certificate:
|
||||||
|
|
||||||
|
```go
|
||||||
|
c := &yaiam.Client{Issuer: issuer, ClientID: id, Scopes: []string{"openid", yaiam.SSHScope}}
|
||||||
|
tok, err := c.Login(ctx, store, show) // or StartDevice/WaitDevice
|
||||||
|
cert, err := c.SSHCertificate(ctx, tok, publicKeyLine)
|
||||||
|
keys, err := c.SSHCAKeys(ctx) // what servers trust
|
||||||
|
```
|
||||||
|
|
||||||
|
Only the public key is sent. yaseva (`yaseva ssh login`) is the client
|
||||||
|
that keeps the private key in its vault.
|
||||||
|
|
||||||
|
### Acting for a user: token exchange
|
||||||
|
|
||||||
|
A confidential client that holds a user's access token -- an
|
||||||
|
application, a gateway, an agent runner like yaais -- trades it for one
|
||||||
|
at another client of yaiam, on behalf of the same user (RFC 8693, yaiam
|
||||||
|
ADR-0045). The target has to allow it (`yaiam-ctl client exchange-from
|
||||||
|
<target> <this client>`):
|
||||||
|
|
||||||
|
```go
|
||||||
|
x := &yaiam.Exchanger{
|
||||||
|
Client: yaiam.Client{Issuer: "https://login.example.org/t/default", ClientID: yaaisID},
|
||||||
|
ClientSecret: secret, // its token endpoint auth method is basic
|
||||||
|
}
|
||||||
|
agent, err := x.Exchange(ctx, usersAccessToken, yakpoClientID) // optional: fewer scopes
|
||||||
|
// ... the agent calls yakpo with agent.AccessToken ...
|
||||||
|
x.Revoke(ctx, agent) // at the end of its job: only this token ends
|
||||||
|
```
|
||||||
|
|
||||||
|
The new token names the user (`sub`), this client (`client_id`,
|
||||||
|
`act.sub`) and the target alone (`aud`). It has no refresh token and
|
||||||
|
ends no later than the user's token; when that one ends (revoked, the
|
||||||
|
consent withdrawn), so does the exchanged one. Give an agent the
|
||||||
|
exchanged token, never the user's. The user's token may be one issued to
|
||||||
|
this client or one another client got for it as its audience (an MCP
|
||||||
|
client calling a gateway).
|
||||||
|
|
||||||
## 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;
|
||||||
|
|||||||
@@ -7,10 +7,20 @@
|
|||||||
|
|
||||||
## Open
|
## Open
|
||||||
|
|
||||||
- [ ] **yaiam: web sign-in.** A helper for web UIs (authorization code
|
- [x] **yaiam: web sign-in** (owner decision 2026-11-17): `Web`, stdlib
|
||||||
+ PKCE, session handling) once yasta's web UI binds to yaiam -- it
|
only -- the ID token checked by its claims as it comes from the token
|
||||||
needs ID-token checks, so either a dependency (zitadel/oidc, go-jose)
|
endpoint over TLS (OpenID Connect Core 3.1.3.7), profile and groups
|
||||||
or it stays in the program; decide with yasta.
|
from UserInfo; `Admin` for the admin API. The application keeps its
|
||||||
|
own session. yaiam's `examples/webapp` uses it; yasta and yaais can.
|
||||||
|
- [x] **yaiam: any OpenID Connect provider for a web sign-in**
|
||||||
|
(2026-11-20, first consumer yaemp, replacing go-oidc/oauth2):
|
||||||
|
`Web.PublicIssuer` (the browser reaches the provider under another
|
||||||
|
origin), `Client.AllowInsecure` (http off loopback, test installations
|
||||||
|
only), `email_verified` true only as JSON boolean; `Callback` checks
|
||||||
|
the cookie and state before it contacts the provider (v0.5.1).
|
||||||
|
- [ ] **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
|
||||||
|
|||||||
@@ -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
|
||||||
+201
@@ -0,0 +1,201 @@
|
|||||||
|
package yaiam
|
||||||
|
|
||||||
|
// Reading a tenant's users and groups from yaiam's admin API, as a
|
||||||
|
// service: a confidential service client of yaiam (its service account
|
||||||
|
// holds yaiam.user.read and yaiam.group.read; the client's tokens have
|
||||||
|
// the admin API as their audience) gets a token with the client
|
||||||
|
// credentials grant and asks /api/v1/tenants/<tenant>/... with it. For
|
||||||
|
// an application that wants to know users before they sign in, or the
|
||||||
|
// members of a group; whoever signs in brings their own groups
|
||||||
|
// (SignedIn).
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxList bounds an answer of the admin API: its lists come whole (no
|
||||||
|
// paging) -- some 100 000 users.
|
||||||
|
const maxList = 64 << 20
|
||||||
|
|
||||||
|
// Admin reads from yaiam's admin API. Its fields must not change once it
|
||||||
|
// is in use; use it by pointer; it is safe for concurrent use.
|
||||||
|
type Admin struct {
|
||||||
|
// Client holds the issuer (the tenant's, whose token endpoint gives
|
||||||
|
// the token), the service client's ID and the HTTP client.
|
||||||
|
Client
|
||||||
|
// ClientSecret is the service client's secret.
|
||||||
|
ClientSecret string
|
||||||
|
// API is the admin API, e.g. "https://admin.example.org/api/v1"
|
||||||
|
// (yaiam-web; https, or http on a loopback host).
|
||||||
|
API string
|
||||||
|
// Tenant is the tenant's slug; its token works only there.
|
||||||
|
Tenant string
|
||||||
|
|
||||||
|
tokMu sync.Mutex
|
||||||
|
tok *Token
|
||||||
|
}
|
||||||
|
|
||||||
|
// Member is a user of the tenant as the admin API lists them.
|
||||||
|
type Member struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Ref string `json:"ref"` // the name, or "home/name" for a member from another tenant
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
State string `json:"user_state"`
|
||||||
|
Home bool `json:"home"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group is a group of the tenant.
|
||||||
|
type Group struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Protected bool `json:"protected"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// User is one user in full.
|
||||||
|
type User struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
EmailVerified bool `json:"email_verified"`
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
TimeZone string `json:"time_zone"`
|
||||||
|
State string `json:"state"`
|
||||||
|
// Attributes are the user's attributes by name (department,
|
||||||
|
// cost_center, ...); none with a yaiam before them.
|
||||||
|
Attributes map[string]string `json:"attributes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Users lists the tenant's users.
|
||||||
|
func (a *Admin) Users(ctx context.Context) ([]Member, error) {
|
||||||
|
var out struct {
|
||||||
|
Items []Member `json:"items"`
|
||||||
|
}
|
||||||
|
return out.Items, a.get(ctx, "users", &out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// User returns the user named name.
|
||||||
|
func (a *Admin) User(ctx context.Context, name string) (*User, error) {
|
||||||
|
var u User
|
||||||
|
if err := a.get(ctx, "users/"+url.PathEscape(name), &u); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &u, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Groups lists the tenant's groups.
|
||||||
|
func (a *Admin) Groups(ctx context.Context) ([]Group, error) {
|
||||||
|
var out struct {
|
||||||
|
Items []Group `json:"items"`
|
||||||
|
}
|
||||||
|
return out.Items, a.get(ctx, "groups", &out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GroupMembers lists the direct members of the group name.
|
||||||
|
func (a *Admin) GroupMembers(ctx context.Context, name string) ([]Member, error) {
|
||||||
|
var out struct {
|
||||||
|
Items []Member `json:"items"`
|
||||||
|
}
|
||||||
|
return out.Items, a.get(ctx, "groups/"+url.PathEscape(name)+"/members", &out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// token is a service token from the client credentials grant, kept until
|
||||||
|
// a minute before it runs out.
|
||||||
|
func (a *Admin) token(ctx context.Context) (string, error) {
|
||||||
|
a.tokMu.Lock()
|
||||||
|
defer a.tokMu.Unlock()
|
||||||
|
if a.tok != nil && time.Until(a.tok.Expiry) > leeway {
|
||||||
|
return a.tok.AccessToken, nil
|
||||||
|
}
|
||||||
|
m, err := a.discover(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, m.TokenEndpoint, strings.NewReader(url.Values{"grant_type": {"client_credentials"}}.Encode()))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
req.SetBasicAuth(url.QueryEscape(a.ClientID), url.QueryEscape(a.ClientSecret))
|
||||||
|
status, body, err := a.do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("yaiam: token: %w", err)
|
||||||
|
}
|
||||||
|
if status != http.StatusOK {
|
||||||
|
return "", oauthError("token", status, body)
|
||||||
|
}
|
||||||
|
var out struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
ExpiresIn int64 `json:"expires_in"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &out); err != nil {
|
||||||
|
return "", fmt.Errorf("yaiam: token: %w", err)
|
||||||
|
}
|
||||||
|
if out.AccessToken == "" || !strings.EqualFold(out.TokenType, "Bearer") || out.ExpiresIn <= 0 {
|
||||||
|
return "", errors.New("yaiam: token: no bearer token with a lifetime in the answer")
|
||||||
|
}
|
||||||
|
a.tok = &Token{Issuer: a.Issuer, ClientID: a.ClientID, AccessToken: out.AccessToken,
|
||||||
|
Expiry: time.Now().Add(time.Duration(out.ExpiresIn) * time.Second)}
|
||||||
|
return out.AccessToken, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// get asks the API for path below the tenant and decodes the answer.
|
||||||
|
// A refused token is fetched again once.
|
||||||
|
func (a *Admin) get(ctx context.Context, path string, out any) error {
|
||||||
|
if err := checkURL("admin API", a.API, a.AllowInsecure); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if a.Tenant == "" || strings.ContainsAny(a.Tenant, "/?#") {
|
||||||
|
return errors.New("yaiam: admin API: no tenant")
|
||||||
|
}
|
||||||
|
target := strings.TrimSuffix(a.API, "/") + "/tenants/" + url.PathEscape(a.Tenant) + "/" + path
|
||||||
|
for attempt := 0; ; attempt++ {
|
||||||
|
tok, err := a.token(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+tok)
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
status, body, err := a.doMax(req, maxList)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("yaiam: admin API: %w", err)
|
||||||
|
}
|
||||||
|
if status == http.StatusUnauthorized && attempt == 0 {
|
||||||
|
a.tokMu.Lock()
|
||||||
|
a.tok = nil
|
||||||
|
a.tokMu.Unlock()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if status != http.StatusOK {
|
||||||
|
var p struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
Detail string `json:"detail"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(body, &p)
|
||||||
|
desc := p.Detail
|
||||||
|
if desc == "" {
|
||||||
|
desc = p.Title
|
||||||
|
}
|
||||||
|
return &Error{Endpoint: "admin API", Status: status, Description: desc}
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, out); err != nil {
|
||||||
|
return fmt.Errorf("yaiam: admin API: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package yaiam
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// adminFake is the token endpoint and the admin API: a service token for
|
||||||
|
// the client credentials of "svc"/"s3cret", lists for it.
|
||||||
|
type adminFake struct {
|
||||||
|
ts *httptest.Server
|
||||||
|
mu sync.Mutex
|
||||||
|
tokens int
|
||||||
|
reject int // answer this many API calls with 401
|
||||||
|
lastPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAdminFake(t *testing.T) *adminFake {
|
||||||
|
f := &adminFake{}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /t/default/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{"issuer": f.ts.URL + "/t/default", "token_endpoint": f.ts.URL + "/token"})
|
||||||
|
})
|
||||||
|
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.ParseForm()
|
||||||
|
if u, p, ok := r.BasicAuth(); !ok || u != "svc" || p != "s3cret" || r.PostForm.Get("grant_type") != "client_credentials" {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
fmt.Fprint(w, `{"error":"invalid_client"}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
f.mu.Lock()
|
||||||
|
f.tokens++
|
||||||
|
n := f.tokens
|
||||||
|
f.mu.Unlock()
|
||||||
|
fmt.Fprintf(w, `{"access_token":"svc-%d","token_type":"Bearer","expires_in":300}`, n)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /api/v1/tenants/default/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
f.lastPath = r.URL.Path
|
||||||
|
reject := f.reject > 0
|
||||||
|
if reject {
|
||||||
|
f.reject--
|
||||||
|
}
|
||||||
|
f.mu.Unlock()
|
||||||
|
if reject || !strings.HasPrefix(r.Header.Get("Authorization"), "Bearer svc-") {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch strings.TrimPrefix(r.URL.Path, "/api/v1/tenants/default/") {
|
||||||
|
case "users":
|
||||||
|
fmt.Fprint(w, `{"items":[{"id":"u-1","ref":"alice","username":"alice","display_name":"Alice","user_state":"active","home":true}]}`)
|
||||||
|
case "users/alice":
|
||||||
|
fmt.Fprint(w, `{"id":"u-1","username":"alice","display_name":"Alice","email":"alice@example.org","email_verified":true,"state":"active","attributes":{"department":"IT"}}`)
|
||||||
|
case "groups":
|
||||||
|
fmt.Fprint(w, `{"items":[{"id":"g-1","name":"staff","protected":false}]}`)
|
||||||
|
case "groups/staff/members":
|
||||||
|
fmt.Fprint(w, `{"items":[{"id":"u-1","ref":"alice","username":"alice"}]}`)
|
||||||
|
default:
|
||||||
|
w.Header().Set("Content-Type", "application/problem+json")
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
fmt.Fprint(w, `{"title":"Not Found","detail":"no such thing"}`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
f.ts = httptest.NewServer(mux)
|
||||||
|
t.Cleanup(f.ts.Close)
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *adminFake) admin() *Admin {
|
||||||
|
return &Admin{Client: Client{Issuer: f.ts.URL + "/t/default", ClientID: "svc"}, ClientSecret: "s3cret", API: f.ts.URL + "/api/v1", Tenant: "default"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAdmin: the lists and a user, with one service token for all;
|
||||||
|
// a refused token is fetched again once; an error answer says what.
|
||||||
|
func TestAdmin(t *testing.T) {
|
||||||
|
f := newAdminFake(t)
|
||||||
|
a := f.admin()
|
||||||
|
ctx := context.Background()
|
||||||
|
users, err := a.Users(ctx)
|
||||||
|
if err != nil || len(users) != 1 || users[0].Username != "alice" || users[0].State != "active" || !users[0].Home {
|
||||||
|
t.Fatalf("users %+v, %v", users, err)
|
||||||
|
}
|
||||||
|
u, err := a.User(ctx, "alice")
|
||||||
|
if err != nil || u.Email != "alice@example.org" || !u.EmailVerified || u.Attributes["department"] != "IT" {
|
||||||
|
t.Errorf("user %+v, %v", u, err)
|
||||||
|
}
|
||||||
|
groups, err := a.Groups(ctx)
|
||||||
|
if err != nil || len(groups) != 1 || groups[0].Name != "staff" {
|
||||||
|
t.Errorf("groups %+v, %v", groups, err)
|
||||||
|
}
|
||||||
|
members, err := a.GroupMembers(ctx, "staff")
|
||||||
|
if err != nil || len(members) != 1 || members[0].ID != "u-1" {
|
||||||
|
t.Errorf("members %+v, %v", members, err)
|
||||||
|
}
|
||||||
|
if f.tokens != 1 {
|
||||||
|
t.Errorf("%d tokens for four calls", f.tokens)
|
||||||
|
}
|
||||||
|
f.reject = 1
|
||||||
|
if _, err := a.Groups(ctx); err != nil || f.tokens != 2 {
|
||||||
|
t.Errorf("after a refused token: %v, %d tokens", err, f.tokens)
|
||||||
|
}
|
||||||
|
f.reject = 2
|
||||||
|
var e *Error
|
||||||
|
if _, err := a.Groups(ctx); !errors.As(err, &e) || e.Status != http.StatusUnauthorized {
|
||||||
|
t.Errorf("refused twice: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := a.User(ctx, "bob"); !errors.As(err, &e) || e.Status != http.StatusNotFound || e.Description != "no such thing" {
|
||||||
|
t.Errorf("not found: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
wrong := f.admin()
|
||||||
|
wrong.ClientSecret = "nope"
|
||||||
|
if _, err := wrong.Users(ctx); !errors.As(err, &e) || e.Code != "invalid_client" {
|
||||||
|
t.Errorf("wrong secret: %v", err)
|
||||||
|
}
|
||||||
|
insecure := f.admin()
|
||||||
|
insecure.API = "http://admin.example.org/api/v1"
|
||||||
|
if _, err := insecure.Users(ctx); err == nil || !strings.Contains(err.Error(), "not https") {
|
||||||
|
t.Errorf("an http API off loopback: %v", err)
|
||||||
|
}
|
||||||
|
noTenant := f.admin()
|
||||||
|
noTenant.Tenant = ""
|
||||||
|
if _, err := noTenant.Users(ctx); err == nil || !strings.Contains(err.Error(), "no tenant") {
|
||||||
|
t.Errorf("no tenant: %v", err)
|
||||||
|
}
|
||||||
|
noTenant.Tenant = "a/b"
|
||||||
|
if _, err := noTenant.Users(ctx); err == nil || !strings.Contains(err.Error(), "no tenant") {
|
||||||
|
t.Errorf("a tenant with a slash: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
-2
@@ -36,6 +36,9 @@ func (c *Client) StartDevice(ctx context.Context) (*DeviceAuth, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if m.DeviceAuthorizationEndpoint == "" {
|
||||||
|
return nil, errors.New("yaiam: the provider offers no device sign-in")
|
||||||
|
}
|
||||||
var out struct {
|
var out struct {
|
||||||
DeviceCode string `json:"device_code"`
|
DeviceCode string `json:"device_code"`
|
||||||
UserCode string `json:"user_code"`
|
UserCode string `json:"user_code"`
|
||||||
@@ -52,11 +55,11 @@ func (c *Client) StartDevice(ctx context.Context) (*DeviceAuth, error) {
|
|||||||
return nil, errors.New("yaiam: device_authorization: incomplete answer")
|
return nil, errors.New("yaiam: device_authorization: incomplete answer")
|
||||||
}
|
}
|
||||||
// The user opens these pages: only ones of the provider's kind.
|
// The user opens these pages: only ones of the provider's kind.
|
||||||
if err := checkURL("verification_uri", out.VerificationURI); err != nil {
|
if err := checkURL("verification_uri", out.VerificationURI, c.AllowInsecure); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if out.VerificationURIComplete != "" {
|
if out.VerificationURIComplete != "" {
|
||||||
if err := checkURL("verification_uri_complete", out.VerificationURIComplete); err != nil {
|
if err := checkURL("verification_uri_complete", out.VerificationURIComplete, c.AllowInsecure); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package yaiam
|
||||||
|
|
||||||
|
// Token exchange (RFC 8693; yaiam ADR-0045): a confidential client --
|
||||||
|
// an application, a gateway, an agent runner -- that holds a user's
|
||||||
|
// access token trades it for one at another client of yaiam, on behalf
|
||||||
|
// of the same user. The target has to allow it ("yaiam-ctl client
|
||||||
|
// exchange-from <target> <this client>"). The new token names the user
|
||||||
|
// (sub), this client (client_id, act.sub) and the target alone (aud); it
|
||||||
|
// has no refresh token and ends no later than the token it came from.
|
||||||
|
// For an agent: hand it the exchanged token, never the user's, and
|
||||||
|
// revoke it when its job ends (Revoke).
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
grantTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"
|
||||||
|
tokenTypeAccess = "urn:ietf:params:oauth:token-type:access_token"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exchanger trades users' access tokens as one confidential client. Its
|
||||||
|
// fields must not change once it is in use; use it by pointer; it is
|
||||||
|
// safe for concurrent use.
|
||||||
|
type Exchanger struct {
|
||||||
|
// Client holds the issuer (the tenant's), this client's ID and the
|
||||||
|
// HTTP client. Its Scopes are not used.
|
||||||
|
Client
|
||||||
|
// ClientSecret is this client's secret, sent in an HTTP Basic header
|
||||||
|
// (its token endpoint auth method has to be basic).
|
||||||
|
ClientSecret string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exchange trades the user's access token subject -- issued to this
|
||||||
|
// client, or to another one for this client as its audience -- for an
|
||||||
|
// access token at the client audience (the target's client ID). scopes
|
||||||
|
// narrow it; none means every scope the token can carry there. A refused
|
||||||
|
// exchange is an *Error: invalid_target when the target does not take
|
||||||
|
// this client's tokens or the user may not use it, invalid_request for a
|
||||||
|
// subject token yaiam does not exchange, invalid_scope for a scope it
|
||||||
|
// cannot carry.
|
||||||
|
func (e *Exchanger) Exchange(ctx context.Context, subject, audience string, scopes ...string) (*Token, error) {
|
||||||
|
if subject == "" || audience == "" {
|
||||||
|
return nil, errors.New("yaiam: token exchange: a subject token and an audience are needed")
|
||||||
|
}
|
||||||
|
m, err := e.discover(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
form := url.Values{"grant_type": {grantTokenExchange}, "subject_token": {subject},
|
||||||
|
"subject_token_type": {tokenTypeAccess}, "requested_token_type": {tokenTypeAccess}, "audience": {audience}}
|
||||||
|
if len(scopes) > 0 {
|
||||||
|
form.Set("scope", strings.Join(scopes, " "))
|
||||||
|
}
|
||||||
|
var out struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
IssuedTokenType string `json:"issued_token_type"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
ExpiresIn int64 `json:"expires_in"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
}
|
||||||
|
if err := e.postBasic(ctx, "token", m.TokenEndpoint, form, &out); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if out.AccessToken == "" || out.IssuedTokenType != tokenTypeAccess || !strings.EqualFold(out.TokenType, "Bearer") || out.ExpiresIn <= 0 {
|
||||||
|
return nil, errors.New("yaiam: token exchange: no bearer access token with a lifetime in the answer")
|
||||||
|
}
|
||||||
|
return &Token{Issuer: e.Issuer, ClientID: e.ClientID, AccessToken: out.AccessToken,
|
||||||
|
Expiry: time.Now().Add(time.Duration(out.ExpiresIn) * time.Second), Scope: out.Scope}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke ends an exchanged token t (RFC 7009) -- an agent's at the end of
|
||||||
|
// its job. Only that token ends; the user's token it came from stays.
|
||||||
|
func (e *Exchanger) Revoke(ctx context.Context, t *Token) error {
|
||||||
|
if t == nil || t.AccessToken == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m, err := e.discover(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if m.RevocationEndpoint == "" {
|
||||||
|
return errors.New("yaiam: the provider offers no revocation")
|
||||||
|
}
|
||||||
|
return e.postBasic(ctx, "revocation", m.RevocationEndpoint,
|
||||||
|
url.Values{"token": {t.AccessToken}, "token_type_hint": {"access_token"}}, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// postBasic is post with this client's ID and secret in a Basic header
|
||||||
|
// (RFC 6749 §2.3.1: both form-encoded first).
|
||||||
|
func (e *Exchanger) postBasic(ctx context.Context, name, endpoint string, form url.Values, out any) error {
|
||||||
|
if e.ClientSecret == "" {
|
||||||
|
return fmt.Errorf("yaiam: %s: no client secret", name)
|
||||||
|
}
|
||||||
|
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")
|
||||||
|
req.SetBasicAuth(url.QueryEscape(e.ClientID), url.QueryEscape(e.ClientSecret))
|
||||||
|
return e.send(name, req, out)
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
package yaiam
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// exchangeServer is a fake provider's token exchange: it answers with
|
||||||
|
// answer (or the OAuth error code refuse) and records what it got.
|
||||||
|
type exchangeServer struct {
|
||||||
|
ts *httptest.Server
|
||||||
|
issuer string
|
||||||
|
mu sync.Mutex
|
||||||
|
forms []url.Values
|
||||||
|
basic []string
|
||||||
|
refuse string
|
||||||
|
answer map[string]any
|
||||||
|
revoked []url.Values
|
||||||
|
}
|
||||||
|
|
||||||
|
func newExchangeServer(t *testing.T) *exchangeServer {
|
||||||
|
s := &exchangeServer{answer: map[string]any{"access_token": "exchanged", "token_type": "Bearer", "expires_in": 300,
|
||||||
|
"issued_token_type": tokenTypeAccess, "scope": "openid"}}
|
||||||
|
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": s.issuer, "token_endpoint": s.ts.URL + "/token",
|
||||||
|
"revocation_endpoint": s.ts.URL + "/revoke"})
|
||||||
|
})
|
||||||
|
record := func(r *http.Request) url.Values {
|
||||||
|
r.ParseForm()
|
||||||
|
id, secret, _ := r.BasicAuth()
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
s.basic = append(s.basic, id+":"+secret)
|
||||||
|
return r.PostForm
|
||||||
|
}
|
||||||
|
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
form := record(r)
|
||||||
|
s.mu.Lock()
|
||||||
|
s.forms = append(s.forms, form)
|
||||||
|
refuse, answer := s.refuse, s.answer
|
||||||
|
s.mu.Unlock()
|
||||||
|
if refuse != "" {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
fmt.Fprintf(w, `{"error":%q}`, refuse)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(answer)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("POST /revoke", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
form := record(r)
|
||||||
|
s.mu.Lock()
|
||||||
|
s.revoked = append(s.revoked, form)
|
||||||
|
s.mu.Unlock()
|
||||||
|
})
|
||||||
|
s.ts = httptest.NewServer(mux)
|
||||||
|
t.Cleanup(s.ts.Close)
|
||||||
|
s.issuer = s.ts.URL + "/t/default"
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestExchange: the request RFC 8693 asks for, with the client's secret
|
||||||
|
// in a Basic header and the user's token only in the body; the answer
|
||||||
|
// becomes a Token without a refresh token; Revoke ends only it.
|
||||||
|
func TestExchange(t *testing.T) {
|
||||||
|
s := newExchangeServer(t)
|
||||||
|
e := &Exchanger{Client: Client{Issuer: s.issuer, ClientID: "yaais"}, ClientSecret: "s3cret:/&"}
|
||||||
|
tok, err := e.Exchange(context.Background(), "users-token", "yakpo", "openid", "profile")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if tok.AccessToken != "exchanged" || tok.RefreshToken != "" || tok.ClientID != "yaais" || tok.Scope != "openid" || tok.Expiry.IsZero() {
|
||||||
|
t.Errorf("token = %#v", tok)
|
||||||
|
}
|
||||||
|
f := s.forms[0]
|
||||||
|
for k, want := range map[string]string{"grant_type": grantTokenExchange, "subject_token": "users-token",
|
||||||
|
"subject_token_type": tokenTypeAccess, "requested_token_type": tokenTypeAccess, "audience": "yakpo", "scope": "openid profile"} {
|
||||||
|
if f.Get(k) != want {
|
||||||
|
t.Errorf("%s = %q, want %q", k, f.Get(k), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if f.Has("client_secret") || s.basic[0] != "yaais:"+url.QueryEscape("s3cret:/&") {
|
||||||
|
t.Errorf("client authentication: form %v, basic %q", f, s.basic[0])
|
||||||
|
}
|
||||||
|
if strings.Contains(fmt.Sprint(tok), "exchanged") {
|
||||||
|
t.Error("the token prints its access token")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := e.Exchange(context.Background(), "users-token", "yakpo"); err != nil || s.forms[1].Has("scope") {
|
||||||
|
t.Errorf("no scopes: %v, %v", err, s.forms[1])
|
||||||
|
}
|
||||||
|
if err := e.Revoke(context.Background(), tok); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if r := s.revoked[0]; r.Get("token") != "exchanged" || r.Get("token_type_hint") != "access_token" || s.basic[len(s.basic)-1] == ":" {
|
||||||
|
t.Errorf("revoked %v", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestExchangeRefused: an OAuth error comes back as *Error with its
|
||||||
|
// code; an answer that is not an access token, no secret or no audience
|
||||||
|
// are errors before or after the request.
|
||||||
|
func TestExchangeRefused(t *testing.T) {
|
||||||
|
s := newExchangeServer(t)
|
||||||
|
e := &Exchanger{Client: Client{Issuer: s.issuer, ClientID: "yaais"}, ClientSecret: "secret"}
|
||||||
|
s.refuse = "invalid_target"
|
||||||
|
var oe *Error
|
||||||
|
if _, err := e.Exchange(context.Background(), "t", "yakpo"); !errors.As(err, &oe) || oe.Code != "invalid_target" {
|
||||||
|
t.Errorf("refused: %v", err)
|
||||||
|
}
|
||||||
|
s.refuse = ""
|
||||||
|
for name, mod := range map[string]func(map[string]any){
|
||||||
|
"an ID token": func(a map[string]any) { a["issued_token_type"] = "urn:ietf:params:oauth:token-type:id_token" },
|
||||||
|
"no type": func(a map[string]any) { delete(a, "issued_token_type") },
|
||||||
|
"no lifetime": func(a map[string]any) { delete(a, "expires_in") },
|
||||||
|
"not bearer": func(a map[string]any) { a["token_type"] = "N_A" },
|
||||||
|
"no access token": func(a map[string]any) { delete(a, "access_token") },
|
||||||
|
} {
|
||||||
|
s.answer = map[string]any{"access_token": "x", "token_type": "Bearer", "expires_in": 300, "issued_token_type": tokenTypeAccess}
|
||||||
|
mod(s.answer)
|
||||||
|
if _, err := e.Exchange(context.Background(), "t", "yakpo"); err == nil {
|
||||||
|
t.Errorf("%s: accepted", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n := len(s.forms)
|
||||||
|
if _, err := e.Exchange(context.Background(), "t", ""); err == nil {
|
||||||
|
t.Error("no audience")
|
||||||
|
}
|
||||||
|
if _, err := e.Exchange(context.Background(), "", "yakpo"); err == nil {
|
||||||
|
t.Error("no subject token")
|
||||||
|
}
|
||||||
|
noSecret := &Exchanger{Client: Client{Issuer: s.issuer, ClientID: "yaais"}}
|
||||||
|
if _, err := noSecret.Exchange(context.Background(), "t", "yakpo"); err == nil {
|
||||||
|
t.Error("no secret")
|
||||||
|
}
|
||||||
|
if len(s.forms) != n {
|
||||||
|
t.Errorf("%d requests sent for refused calls", len(s.forms)-n)
|
||||||
|
}
|
||||||
|
if err := e.Revoke(context.Background(), nil); err != nil {
|
||||||
|
t.Errorf("revoking nothing: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
package yaiam
|
||||||
|
|
||||||
|
// SSH certificates (yaiam ADR-0046): a tenant of yaiam is an SSH
|
||||||
|
// certificate authority. A program signs its user in with the device
|
||||||
|
// flow -- Client.Scopes with "ssh"; the client needs that scope and the
|
||||||
|
// audience SSHAudience in yaiam -- and trades the access token and a
|
||||||
|
// public key for a short-lived OpenSSH user certificate. Only the public
|
||||||
|
// key is sent; the private one stays with the program.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SSHScope is the scope a token needs for SSH certificates.
|
||||||
|
const SSHScope = "ssh"
|
||||||
|
|
||||||
|
// SSHAudience is the audience yaiam wants in a token for the SSH
|
||||||
|
// certificates of the tenant whose issuer is issuer
|
||||||
|
// ("https://login.example.org/t/default" -> ".../t/default/ssh").
|
||||||
|
func SSHAudience(issuer string) string { return strings.TrimSuffix(issuer, "/") + "/ssh" }
|
||||||
|
|
||||||
|
// SSHCertificate is a certificate yaiam signed.
|
||||||
|
type SSHCertificate struct {
|
||||||
|
// Certificate is the certificate in authorized_keys format, what an
|
||||||
|
// ssh-agent or a <key>-cert.pub file takes.
|
||||||
|
Certificate string `json:"certificate"`
|
||||||
|
Serial string `json:"serial"`
|
||||||
|
Principals []string `json:"principals"`
|
||||||
|
ValidAfter time.Time `json:"valid_after"`
|
||||||
|
ValidBefore time.Time `json:"valid_before"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SSHCertificate asks for a certificate for publicKey (authorized_keys
|
||||||
|
// format) with the access token t. A refusal is an *Error:
|
||||||
|
// invalid_token (401: sign in again), access_denied (403: no scope ssh,
|
||||||
|
// the client's access rule, or a sign-in without the second factor the
|
||||||
|
// tenant asks for), not_available (404: the tenant issues no
|
||||||
|
// certificates), invalid_request (400: a key yaiam does not certify).
|
||||||
|
func (c *Client) SSHCertificate(ctx context.Context, t *Token, publicKey string) (*SSHCertificate, error) {
|
||||||
|
if t == nil || t.AccessToken == "" {
|
||||||
|
return nil, ErrLoginRequired
|
||||||
|
}
|
||||||
|
if publicKey == "" {
|
||||||
|
return nil, errors.New("yaiam: ssh certificate: no public key")
|
||||||
|
}
|
||||||
|
if err := checkURL("issuer", c.Issuer, c.AllowInsecure); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(map[string]string{"public_key": strings.TrimSpace(publicKey)})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSuffix(c.Issuer, "/")+"/ssh/certificate", bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+t.AccessToken)
|
||||||
|
var out SSHCertificate
|
||||||
|
if err := c.send("ssh certificate", req, &out); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if out.Certificate == "" || !out.ValidBefore.After(out.ValidAfter) {
|
||||||
|
return nil, errors.New("yaiam: ssh certificate: incomplete answer")
|
||||||
|
}
|
||||||
|
return &out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SSHCAKeys are the public keys servers of the tenant trust
|
||||||
|
// (TrustedUserCAKeys), one authorized_keys line each; none while the
|
||||||
|
// tenant issues no certificates.
|
||||||
|
func (c *Client) SSHCAKeys(ctx context.Context) ([]string, error) {
|
||||||
|
if err := checkURL("issuer", c.Issuer, c.AllowInsecure); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(c.Issuer, "/")+"/ssh/ca.pub", nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
status, body, err := c.do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("yaiam: ssh ca.pub: %w", err)
|
||||||
|
}
|
||||||
|
switch status {
|
||||||
|
case http.StatusOK:
|
||||||
|
case http.StatusNotFound:
|
||||||
|
return nil, nil
|
||||||
|
default:
|
||||||
|
return nil, &Error{Endpoint: "ssh ca.pub", Status: status}
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for line := range strings.SplitSeq(string(body), "\n") {
|
||||||
|
if line = strings.TrimSpace(line); line != "" {
|
||||||
|
out = append(out, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package yaiam
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSSHCertificate: the public key and the bearer token go to
|
||||||
|
// <issuer>/ssh/certificate, the answer comes back; a refusal is an
|
||||||
|
// *Error with yaiam's code; no token is ErrLoginRequired; ca.pub lists
|
||||||
|
// the CA keys, none on 404; a plain-http issuer elsewhere than loopback
|
||||||
|
// is refused before anything is sent.
|
||||||
|
func TestSSHCertificate(t *testing.T) {
|
||||||
|
var gotAuth, gotKey string
|
||||||
|
refuse := ""
|
||||||
|
caKeys := "ssh-ed25519 AAAA-one\nssh-ed25519 AAAA-two\n"
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch {
|
||||||
|
case r.Method == http.MethodPost && r.URL.Path == "/t/default/ssh/certificate":
|
||||||
|
gotAuth = r.Header.Get("Authorization")
|
||||||
|
var in map[string]string
|
||||||
|
json.NewDecoder(r.Body).Decode(&in)
|
||||||
|
gotKey = in["public_key"]
|
||||||
|
if refuse != "" {
|
||||||
|
w.WriteHeader(http.StatusForbidden)
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{"error": refuse, "error_description": "no SSH certificate for this token"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"certificate": "ssh-ed25519-cert-v01@openssh.com AAAA", "serial": "42",
|
||||||
|
"principals": []string{"user:alice"}, "valid_after": now.Add(-5 * time.Minute), "valid_before": now.Add(8 * time.Hour)})
|
||||||
|
case r.Method == http.MethodGet && r.URL.Path == "/t/default/ssh/ca.pub":
|
||||||
|
if caKeys == "" {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Write([]byte(caKeys))
|
||||||
|
default:
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
c := &Client{Issuer: ts.URL + "/t/default", ClientID: "ssh"}
|
||||||
|
ctx := context.Background()
|
||||||
|
tok := &Token{AccessToken: "the-token"}
|
||||||
|
|
||||||
|
cert, err := c.SSHCertificate(ctx, tok, " ssh-ed25519 AAAA-user alice@laptop\n")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if gotAuth != "Bearer the-token" || gotKey != "ssh-ed25519 AAAA-user alice@laptop" || cert.Serial != "42" ||
|
||||||
|
len(cert.Principals) != 1 || !strings.HasPrefix(cert.Certificate, "ssh-ed25519-cert") {
|
||||||
|
t.Errorf("sent %q %q, got %+v", gotAuth, gotKey, cert)
|
||||||
|
}
|
||||||
|
refuse = "access_denied"
|
||||||
|
var e *Error
|
||||||
|
if _, err := c.SSHCertificate(ctx, tok, "ssh-ed25519 AAAA"); !errors.As(err, &e) || e.Code != "access_denied" || e.Status != http.StatusForbidden {
|
||||||
|
t.Errorf("refused: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := c.SSHCertificate(ctx, nil, "ssh-ed25519 AAAA"); !errors.Is(err, ErrLoginRequired) {
|
||||||
|
t.Errorf("no token: %v", err)
|
||||||
|
}
|
||||||
|
if SSHAudience(c.Issuer) != ts.URL+"/t/default/ssh" || SSHAudience(c.Issuer+"/") != ts.URL+"/t/default/ssh" {
|
||||||
|
t.Errorf("audience = %q", SSHAudience(c.Issuer))
|
||||||
|
}
|
||||||
|
|
||||||
|
keys, err := c.SSHCAKeys(ctx)
|
||||||
|
if err != nil || len(keys) != 2 || keys[1] != "ssh-ed25519 AAAA-two" {
|
||||||
|
t.Errorf("CA keys = %v, %v", keys, err)
|
||||||
|
}
|
||||||
|
caKeys = ""
|
||||||
|
if keys, err := c.SSHCAKeys(ctx); err != nil || keys != nil {
|
||||||
|
t.Errorf("no CA = %v, %v", keys, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
far := &Client{Issuer: "http://login.example.org/t/default", ClientID: "ssh"}
|
||||||
|
if _, err := far.SSHCertificate(ctx, tok, "ssh-ed25519 AAAA"); err == nil || !strings.Contains(err.Error(), "not https") {
|
||||||
|
t.Errorf("plain http elsewhere: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+488
@@ -0,0 +1,488 @@
|
|||||||
|
package yaiam
|
||||||
|
|
||||||
|
// Signing the users of a web application in (authorization code flow
|
||||||
|
// with PKCE, OpenID Connect Core 3.1). SignIn sends the browser to the
|
||||||
|
// provider with a fresh state, nonce and code verifier, kept in a short
|
||||||
|
// cookie of this browser; Callback checks the state against the cookie,
|
||||||
|
// trades the code for tokens and checks the ID token.
|
||||||
|
//
|
||||||
|
// The ID token comes straight from the token endpoint over TLS, so its
|
||||||
|
// signature is not checked here: OpenID Connect Core 3.1.3.7 lets a
|
||||||
|
// client rely on the TLS server check instead -- no crypto in this
|
||||||
|
// package. Its claims are: iss the issuer, aud this client (azp too when
|
||||||
|
// there are several), not expired, the nonce of this sign-in. The
|
||||||
|
// profile, groups and roles come from UserInfo, which must name the same
|
||||||
|
// subject.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WebScopes are asked for when Web.Scopes is nil: who the user is, their
|
||||||
|
// address, their groups and roles at yaiam (the client must be allowed
|
||||||
|
// "groups" and "roles") and the user attributes released to the client
|
||||||
|
// (yaiam allows "attributes" once some are). A scope the client is not
|
||||||
|
// allowed is left out, not refused.
|
||||||
|
var WebScopes = []string{"openid", "profile", "email", "groups", "roles", "attributes"}
|
||||||
|
|
||||||
|
// signInLifetime is how long a started sign-in may take.
|
||||||
|
const signInLifetime = 10 * time.Minute
|
||||||
|
|
||||||
|
// clockSkew is the leeway for an ID token's exp and iat.
|
||||||
|
const clockSkew = time.Minute
|
||||||
|
|
||||||
|
// Errors of a sign-in.
|
||||||
|
var (
|
||||||
|
// ErrSignInState: the callback does not belong to a sign-in this
|
||||||
|
// browser started (no cookie, another state, too late). Start again.
|
||||||
|
ErrSignInState = errors.New("yaiam: the sign-in does not belong to this browser or took too long")
|
||||||
|
// ErrSignInRefused: the provider answered the callback with an error
|
||||||
|
// (the user cancelled, may not use the application, ...); see the
|
||||||
|
// wrapped *Error for its code.
|
||||||
|
ErrSignInRefused = errors.New("yaiam: the provider refused the sign-in")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Web signs the users of a web application in at one issuer as one
|
||||||
|
// client. Its fields must not change once it is in use; use it by
|
||||||
|
// pointer; it is safe for concurrent use.
|
||||||
|
type Web struct {
|
||||||
|
// Client holds the issuer, the client ID, the scopes (nil:
|
||||||
|
// WebScopes) and the HTTP client. Its Scopes and token store are not
|
||||||
|
// used.
|
||||||
|
Client
|
||||||
|
// ClientSecret authenticates a confidential client at the token
|
||||||
|
// endpoint (client_secret_basic); "" for a public client.
|
||||||
|
ClientSecret string
|
||||||
|
// RedirectURL is this application's callback, registered at the
|
||||||
|
// client, e.g. "https://app.example.org/callback".
|
||||||
|
RedirectURL string
|
||||||
|
// PostLogoutRedirectURL is where the provider sends the browser
|
||||||
|
// after a sign-out (registered at the client); "" for none.
|
||||||
|
PostLogoutRedirectURL string
|
||||||
|
// PublicIssuer is the issuer URL as the browser reaches it, when this
|
||||||
|
// application reaches the provider under another name (a container
|
||||||
|
// network: Issuer "http://oidc:8080/default", PublicIssuer
|
||||||
|
// "http://localhost:8180/default"): the same path on another origin.
|
||||||
|
// The endpoints the browser is sent to (authorization, end session)
|
||||||
|
// that are on Issuer's origin go to PublicIssuer's instead, and the
|
||||||
|
// callback's iss may name either. "" means Issuer.
|
||||||
|
PublicIssuer string
|
||||||
|
// CookieName names the short cookie of a running sign-in; "" means
|
||||||
|
// "yaiam_signin". On https it always gets the prefix "__Host-". One
|
||||||
|
// sign-in per browser at a time: a second one started in another tab
|
||||||
|
// replaces the first, whose callback then is ErrSignInState.
|
||||||
|
CookieName string
|
||||||
|
}
|
||||||
|
|
||||||
|
// SignedIn is who signed in, with the tokens.
|
||||||
|
type SignedIn struct {
|
||||||
|
// Subject is the user's ID at yaiam: it stays the same when the user
|
||||||
|
// is renamed -- the key to keep an application's own data under.
|
||||||
|
Subject string
|
||||||
|
// Username, Name and Email (EmailVerified: confirmed) with the
|
||||||
|
// scopes profile and email.
|
||||||
|
Username, Name, Email string
|
||||||
|
EmailVerified bool
|
||||||
|
// Groups and Roles with the scopes groups and roles: the names of the
|
||||||
|
// user's groups (subgroups' members included) and roles in the tenant.
|
||||||
|
Groups, Roles []string
|
||||||
|
// Attributes with the scope attributes: the user's attributes yaiam
|
||||||
|
// releases to the client (department, cost_center, ...), by name.
|
||||||
|
Attributes map[string]string
|
||||||
|
// ACR is how strongly the user signed in ("pwd", "mfa", "phr"), AMR
|
||||||
|
// with what; AuthTime when.
|
||||||
|
ACR string
|
||||||
|
AMR []string
|
||||||
|
AuthTime time.Time
|
||||||
|
// IDToken is for LogoutURL; Token for the APIs (it holds no refresh
|
||||||
|
// token unless the scopes asked for offline_access).
|
||||||
|
IDToken string
|
||||||
|
Token *Token
|
||||||
|
// ReturnTo is the path SignIn was given.
|
||||||
|
ReturnTo string
|
||||||
|
}
|
||||||
|
|
||||||
|
// String keeps the tokens out of anything printed or logged.
|
||||||
|
func (s *SignedIn) String() string {
|
||||||
|
if s == nil {
|
||||||
|
return "<nil>"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("yaiam.SignedIn{Subject: %q, Username: %q, Groups: %q, ACR: %q, tokens redacted}", s.Subject, s.Username, s.Groups, s.ACR)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GoString is String, for %#v.
|
||||||
|
func (s *SignedIn) GoString() string { return s.String() }
|
||||||
|
|
||||||
|
// signInCookie is what the cookie of a running sign-in holds.
|
||||||
|
type signInCookie struct {
|
||||||
|
State string `json:"s"`
|
||||||
|
Nonce string `json:"n"`
|
||||||
|
Verifier string `json:"v"`
|
||||||
|
ReturnTo string `json:"r"`
|
||||||
|
Expires int64 `json:"e"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Web) secure() bool { return strings.HasPrefix(w.RedirectURL, "https://") }
|
||||||
|
|
||||||
|
func (w *Web) cookieName() string {
|
||||||
|
name := w.CookieName
|
||||||
|
if name == "" {
|
||||||
|
name = "yaiam_signin"
|
||||||
|
}
|
||||||
|
// On https always __Host-: no other host can plant it.
|
||||||
|
if w.secure() && !strings.HasPrefix(name, "__Host-") {
|
||||||
|
return "__Host-" + name
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Web) scope() string {
|
||||||
|
if w.Scopes == nil {
|
||||||
|
return strings.Join(WebScopes, " ")
|
||||||
|
}
|
||||||
|
return strings.Join(w.Scopes, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// check refuses a Web that cannot sign anyone in safely.
|
||||||
|
func (w *Web) check() error {
|
||||||
|
if err := checkURL("redirect URL", w.RedirectURL, w.AllowInsecure); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if w.PostLogoutRedirectURL != "" {
|
||||||
|
if err := checkURL("post-logout redirect URL", w.PostLogoutRedirectURL, w.AllowInsecure); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
scopes := WebScopes
|
||||||
|
if w.Scopes != nil {
|
||||||
|
scopes = w.Scopes
|
||||||
|
}
|
||||||
|
if w.PublicIssuer != "" {
|
||||||
|
if err := checkURL("public issuer", w.PublicIssuer, w.AllowInsecure); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pub, _ := url.Parse(w.PublicIssuer)
|
||||||
|
if iss, err := url.Parse(w.Issuer); err != nil || iss.Path != pub.Path {
|
||||||
|
return errors.New("yaiam: the public issuer must have the issuer's path")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !slices.Contains(scopes, "openid") {
|
||||||
|
return errors.New("yaiam: a sign-in needs the scope openid")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SignIn starts a sign-in: it remembers a fresh state, nonce and PKCE
|
||||||
|
// verifier in a cookie of this browser (HttpOnly, SameSite=Lax, Secure on
|
||||||
|
// https, ten minutes) and redirects the browser to the provider.
|
||||||
|
// returnTo is the path of this application to go to afterwards
|
||||||
|
// (Callback returns it); anything but a local path becomes "/".
|
||||||
|
func (w *Web) SignIn(ctx context.Context, rw http.ResponseWriter, r *http.Request, returnTo string) error {
|
||||||
|
if err := w.check(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
m, err := w.discover(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if m.AuthorizationEndpoint == "" {
|
||||||
|
return errors.New("yaiam: the provider names no authorization endpoint")
|
||||||
|
}
|
||||||
|
c := signInCookie{State: random(), Nonce: random(), Verifier: random() + random(), ReturnTo: localPath(returnTo),
|
||||||
|
Expires: time.Now().Add(signInLifetime).Unix()}
|
||||||
|
raw, err := json.Marshal(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
http.SetCookie(rw, &http.Cookie{Name: w.cookieName(), Value: base64.RawURLEncoding.EncodeToString(raw), Path: "/",
|
||||||
|
MaxAge: int(signInLifetime.Seconds()), HttpOnly: true, Secure: w.secure(), SameSite: http.SameSiteLaxMode})
|
||||||
|
challenge := sha256.Sum256([]byte(c.Verifier))
|
||||||
|
q := url.Values{"response_type": {"code"}, "client_id": {w.ClientID}, "redirect_uri": {w.RedirectURL},
|
||||||
|
"scope": {w.scope()}, "state": {c.State}, "nonce": {c.Nonce},
|
||||||
|
"code_challenge": {base64.RawURLEncoding.EncodeToString(challenge[:])}, "code_challenge_method": {"S256"}}
|
||||||
|
target := w.browser(m.AuthorizationEndpoint)
|
||||||
|
if strings.Contains(target, "?") {
|
||||||
|
target += "&" + q.Encode()
|
||||||
|
} else {
|
||||||
|
target += "?" + q.Encode()
|
||||||
|
}
|
||||||
|
http.Redirect(rw, r, target, http.StatusFound)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// localPath is p when it is a path of this application, else "/": no
|
||||||
|
// redirect to another site after the sign-in. A browser drops tabs and
|
||||||
|
// line breaks from a URL and reads a backslash as a slash, so none of
|
||||||
|
// them, no control character, and no "//" at the start.
|
||||||
|
func localPath(p string) string {
|
||||||
|
if !strings.HasPrefix(p, "/") || strings.HasPrefix(p, "//") ||
|
||||||
|
strings.ContainsFunc(p, func(r rune) bool { return r < 0x20 || r == 0x7f || r == '\\' }) {
|
||||||
|
return "/"
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// random is 32 random bytes, base64url.
|
||||||
|
func random() string {
|
||||||
|
b := make([]byte, 32)
|
||||||
|
rand.Read(b) // never fails (crypto/rand)
|
||||||
|
return base64.RawURLEncoding.EncodeToString(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Callback finishes the sign-in the request r (the provider's redirect
|
||||||
|
// to RedirectURL) belongs to: the state must be the one of this
|
||||||
|
// browser's cookie (which it removes), the code is traded for tokens with
|
||||||
|
// the verifier, the ID token checked, UserInfo asked. A refusal of the
|
||||||
|
// provider is ErrSignInRefused, a callback of another or an old sign-in
|
||||||
|
// ErrSignInState.
|
||||||
|
func (w *Web) Callback(ctx context.Context, rw http.ResponseWriter, r *http.Request) (*SignedIn, error) {
|
||||||
|
if err := w.check(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// The browser's cookie and the state first: a callback of no sign-in
|
||||||
|
// of this browser never reaches the provider.
|
||||||
|
var c signInCookie
|
||||||
|
cookie, cerr := r.Cookie(w.cookieName())
|
||||||
|
http.SetCookie(rw, &http.Cookie{Name: w.cookieName(), Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: w.secure(),
|
||||||
|
SameSite: http.SameSiteLaxMode})
|
||||||
|
if cerr != nil {
|
||||||
|
return nil, ErrSignInState
|
||||||
|
}
|
||||||
|
raw, err := base64.RawURLEncoding.DecodeString(cookie.Value)
|
||||||
|
if err != nil || json.Unmarshal(raw, &c) != nil || c.State == "" || time.Now().Unix() > c.Expires {
|
||||||
|
return nil, ErrSignInState
|
||||||
|
}
|
||||||
|
q := r.URL.Query()
|
||||||
|
if subtle.ConstantTimeCompare([]byte(q.Get("state")), []byte(c.State)) != 1 {
|
||||||
|
return nil, ErrSignInState
|
||||||
|
}
|
||||||
|
// RFC 9207: an iss parameter must name this issuer.
|
||||||
|
if iss := q.Get("iss"); iss != "" && iss != w.Issuer && (w.PublicIssuer == "" || iss != w.PublicIssuer) {
|
||||||
|
return nil, fmt.Errorf("yaiam: the callback comes from issuer %q, not %q", iss, w.Issuer)
|
||||||
|
}
|
||||||
|
if code := q.Get("error"); code != "" {
|
||||||
|
return nil, fmt.Errorf("%w: %w", ErrSignInRefused, &Error{Endpoint: "authorization", Status: http.StatusFound, Code: code,
|
||||||
|
Description: q.Get("error_description")})
|
||||||
|
}
|
||||||
|
code := q.Get("code")
|
||||||
|
if code == "" {
|
||||||
|
return nil, errors.New("yaiam: the callback has no code")
|
||||||
|
}
|
||||||
|
m, err := w.discover(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tok, idToken, err := w.exchange(ctx, m, code, c.Verifier)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
claims, err := w.checkIDToken(idToken, c.Nonce)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := &SignedIn{Subject: claims.Subject, ACR: claims.ACR, AMR: claims.AMR, IDToken: idToken, Token: tok,
|
||||||
|
ReturnTo: localPath(c.ReturnTo)} // the cookie is the browser's: check again
|
||||||
|
if claims.AuthTime > 0 {
|
||||||
|
out.AuthTime = time.Unix(claims.AuthTime, 0)
|
||||||
|
}
|
||||||
|
if m.UserinfoEndpoint != "" {
|
||||||
|
u, err := w.userInfo(ctx, m, tok)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if u.Subject != claims.Subject {
|
||||||
|
return nil, errors.New("yaiam: UserInfo names another user than the ID token")
|
||||||
|
}
|
||||||
|
// Only the JSON boolean true confirms the address: some providers
|
||||||
|
// send the string "true", which a sign-in must not take for it
|
||||||
|
// (nor fail on).
|
||||||
|
out.Username, out.Name, out.Email, out.Groups, out.Roles = u.Username, u.Name, u.Email, u.Groups, u.Roles
|
||||||
|
out.EmailVerified = string(u.EmailVerified) == "true"
|
||||||
|
out.Attributes = u.Attributes
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// exchange trades code for tokens at the token endpoint.
|
||||||
|
func (w *Web) exchange(ctx context.Context, m *metadata, code, verifier string) (*Token, string, error) {
|
||||||
|
form := url.Values{"grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {w.RedirectURL},
|
||||||
|
"code_verifier": {verifier}}
|
||||||
|
if w.ClientSecret == "" {
|
||||||
|
form.Set("client_id", w.ClientID)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, m.TokenEndpoint, strings.NewReader(form.Encode()))
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
if w.ClientSecret != "" {
|
||||||
|
req.SetBasicAuth(url.QueryEscape(w.ClientID), url.QueryEscape(w.ClientSecret)) // RFC 6749 2.3.1
|
||||||
|
}
|
||||||
|
status, body, err := w.do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", fmt.Errorf("yaiam: token: %w", err)
|
||||||
|
}
|
||||||
|
if status != http.StatusOK {
|
||||||
|
return nil, "", oauthError("token", status, body)
|
||||||
|
}
|
||||||
|
var out struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
ExpiresIn int64 `json:"expires_in"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
IDToken string `json:"id_token"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &out); err != nil {
|
||||||
|
return nil, "", fmt.Errorf("yaiam: token: %w", err)
|
||||||
|
}
|
||||||
|
// No ID token: checkIDToken refuses it.
|
||||||
|
if out.AccessToken == "" || !strings.EqualFold(out.TokenType, "Bearer") || out.ExpiresIn <= 0 {
|
||||||
|
return nil, "", errors.New("yaiam: token: no bearer token with a lifetime in the answer")
|
||||||
|
}
|
||||||
|
return &Token{Issuer: w.Issuer, ClientID: w.ClientID, AccessToken: out.AccessToken, RefreshToken: out.RefreshToken,
|
||||||
|
Expiry: time.Now().Add(time.Duration(out.ExpiresIn) * time.Second), Scope: out.Scope}, out.IDToken, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// idClaims are the ID token's claims a sign-in looks at.
|
||||||
|
type idClaims struct {
|
||||||
|
Issuer string `json:"iss"`
|
||||||
|
Subject string `json:"sub"`
|
||||||
|
Audience json.RawMessage `json:"aud"`
|
||||||
|
AZP string `json:"azp"`
|
||||||
|
Expiry int64 `json:"exp"`
|
||||||
|
IssuedAt int64 `json:"iat"`
|
||||||
|
Nonce string `json:"nonce"`
|
||||||
|
ACR string `json:"acr"`
|
||||||
|
AMR []string `json:"amr"`
|
||||||
|
AuthTime int64 `json:"auth_time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkIDToken reads the claims of idToken, which came from the token
|
||||||
|
// endpoint over TLS (OpenID Connect Core 3.1.3.7: no signature check),
|
||||||
|
// and checks them: issuer, audience, expiry, issue time, nonce.
|
||||||
|
func (w *Web) checkIDToken(idToken, nonce string) (*idClaims, error) {
|
||||||
|
parts := strings.Split(idToken, ".")
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return nil, errors.New("yaiam: the ID token is not a JWT")
|
||||||
|
}
|
||||||
|
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("yaiam: the ID token's claims are not base64url")
|
||||||
|
}
|
||||||
|
var c idClaims
|
||||||
|
if err := json.Unmarshal(raw, &c); err != nil {
|
||||||
|
return nil, fmt.Errorf("yaiam: the ID token's claims: %w", err)
|
||||||
|
}
|
||||||
|
var aud []string
|
||||||
|
if err := json.Unmarshal(c.Audience, &aud); err != nil {
|
||||||
|
var one string
|
||||||
|
if json.Unmarshal(c.Audience, &one) != nil {
|
||||||
|
return nil, errors.New("yaiam: the ID token has no audience")
|
||||||
|
}
|
||||||
|
aud = []string{one}
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
switch {
|
||||||
|
case c.Issuer != w.Issuer:
|
||||||
|
return nil, fmt.Errorf("yaiam: the ID token is from issuer %q, not %q", c.Issuer, w.Issuer)
|
||||||
|
case !slices.Contains(aud, w.ClientID):
|
||||||
|
return nil, errors.New("yaiam: the ID token is not for this client")
|
||||||
|
case len(aud) > 1 && c.AZP != w.ClientID:
|
||||||
|
return nil, errors.New("yaiam: the ID token was issued to another client (azp)")
|
||||||
|
case c.Subject == "":
|
||||||
|
return nil, errors.New("yaiam: the ID token names no subject")
|
||||||
|
case c.Expiry == 0 || now.After(time.Unix(c.Expiry, 0).Add(clockSkew)):
|
||||||
|
return nil, errors.New("yaiam: the ID token has expired")
|
||||||
|
case c.IssuedAt == 0 || time.Unix(c.IssuedAt, 0).After(now.Add(clockSkew)):
|
||||||
|
return nil, errors.New("yaiam: the ID token is issued in the future")
|
||||||
|
case subtle.ConstantTimeCompare([]byte(c.Nonce), []byte(nonce)) != 1:
|
||||||
|
return nil, errors.New("yaiam: the ID token is not for this sign-in (nonce)")
|
||||||
|
}
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// webUserInfo is UserInfo's answer with what a web sign-in also takes.
|
||||||
|
type webUserInfo struct {
|
||||||
|
UserInfo
|
||||||
|
EmailVerified json.RawMessage `json:"email_verified"`
|
||||||
|
Groups []string `json:"groups"`
|
||||||
|
Roles []string `json:"roles"`
|
||||||
|
Attributes map[string]string `json:"attributes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Web) userInfo(ctx context.Context, m *metadata, t *Token) (*webUserInfo, error) {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.UserinfoEndpoint, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+t.AccessToken)
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
status, body, err := w.do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("yaiam: userinfo: %w", err)
|
||||||
|
}
|
||||||
|
if status != http.StatusOK {
|
||||||
|
return nil, &Error{Endpoint: "userinfo", Status: status}
|
||||||
|
}
|
||||||
|
var u webUserInfo
|
||||||
|
if err := json.Unmarshal(body, &u); err != nil {
|
||||||
|
return nil, fmt.Errorf("yaiam: userinfo: %w", err)
|
||||||
|
}
|
||||||
|
return &u, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LogoutURL is where to send the browser to sign out at the provider too
|
||||||
|
// (RP-initiated logout): with the ID token of the sign-in as hint and,
|
||||||
|
// when set, PostLogoutRedirectURL. "" when the provider offers none --
|
||||||
|
// then the application ends only its own session.
|
||||||
|
func (w *Web) LogoutURL(ctx context.Context, idToken string) (string, error) {
|
||||||
|
m, err := w.discover(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if m.EndSessionEndpoint == "" {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
q := url.Values{"client_id": {w.ClientID}}
|
||||||
|
if idToken != "" {
|
||||||
|
q.Set("id_token_hint", idToken)
|
||||||
|
}
|
||||||
|
if w.PostLogoutRedirectURL != "" {
|
||||||
|
q.Set("post_logout_redirect_uri", w.PostLogoutRedirectURL)
|
||||||
|
}
|
||||||
|
sep := "?"
|
||||||
|
if strings.Contains(m.EndSessionEndpoint, "?") {
|
||||||
|
sep = "&"
|
||||||
|
}
|
||||||
|
return w.browser(m.EndSessionEndpoint) + sep + q.Encode(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// browser is endpoint as the browser reaches it: on PublicIssuer's
|
||||||
|
// origin when it is on Issuer's.
|
||||||
|
func (w *Web) browser(endpoint string) string {
|
||||||
|
if w.PublicIssuer == "" {
|
||||||
|
return endpoint
|
||||||
|
}
|
||||||
|
e, err := url.Parse(endpoint)
|
||||||
|
iss, err2 := url.Parse(w.Issuer)
|
||||||
|
pub, err3 := url.Parse(w.PublicIssuer)
|
||||||
|
if err != nil || err2 != nil || err3 != nil || e.Scheme != iss.Scheme || e.Host != iss.Host {
|
||||||
|
return endpoint
|
||||||
|
}
|
||||||
|
e.Scheme, e.Host = pub.Scheme, pub.Host
|
||||||
|
return e.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package yaiam
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Refresh gets a new access token for a signed-in user with t's refresh
|
||||||
|
// token (there is one only when the scopes asked for offline_access).
|
||||||
|
// Unlike Client.Refresh it authenticates a confidential client with its
|
||||||
|
// secret. The answer's refresh token replaces t's; keep the result, not
|
||||||
|
// t. A refused refresh token is ErrLoginRequired.
|
||||||
|
func (w *Web) Refresh(ctx context.Context, t *Token) (*Token, error) {
|
||||||
|
if t == nil || t.RefreshToken == "" {
|
||||||
|
return nil, ErrLoginRequired
|
||||||
|
}
|
||||||
|
m, err := w.discover(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
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"`
|
||||||
|
}
|
||||||
|
err = w.postClient(ctx, "token", m.TokenEndpoint, url.Values{"grant_type": {"refresh_token"}, "refresh_token": {t.RefreshToken}}, &out)
|
||||||
|
if isCode(err, "invalid_grant") {
|
||||||
|
return nil, fmt.Errorf("%w (%w)", ErrLoginRequired, err)
|
||||||
|
}
|
||||||
|
if 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")
|
||||||
|
}
|
||||||
|
nt := &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}
|
||||||
|
if nt.RefreshToken == "" {
|
||||||
|
nt.RefreshToken = t.RefreshToken
|
||||||
|
}
|
||||||
|
return nt, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke ends a signed-in user's tokens at the provider (RFC 7009): the
|
||||||
|
// refresh token first, which ends the access tokens it made too, then
|
||||||
|
// the access token. For a sign-out; the browser's session at the
|
||||||
|
// provider ends only through LogoutURL.
|
||||||
|
func (w *Web) Revoke(ctx context.Context, t *Token) error {
|
||||||
|
if t == nil || (t.RefreshToken == "" && t.AccessToken == "") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m, err := w.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 := w.postClient(ctx, "revocation", m.RevocationEndpoint, url.Values{"token": {tok.value}, "token_type_hint": {tok.hint}}, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// postClient posts form as this client: a confidential one with its ID
|
||||||
|
// and secret in a Basic header (RFC 6749 §2.3.1), a public one with
|
||||||
|
// client_id in the form.
|
||||||
|
func (w *Web) postClient(ctx context.Context, name, endpoint string, form url.Values, out any) error {
|
||||||
|
if w.ClientSecret == "" {
|
||||||
|
form.Set("client_id", w.ClientID)
|
||||||
|
}
|
||||||
|
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")
|
||||||
|
if w.ClientSecret != "" {
|
||||||
|
req.SetBasicAuth(url.QueryEscape(w.ClientID), url.QueryEscape(w.ClientSecret))
|
||||||
|
}
|
||||||
|
return w.send(name, req, out)
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package yaiam
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestWebRefreshAndRevoke: a confidential client refreshes and revokes
|
||||||
|
// with its secret in a Basic header and no client_id in the form; a
|
||||||
|
// refused refresh token is ErrLoginRequired.
|
||||||
|
func TestWebRefreshAndRevoke(t *testing.T) {
|
||||||
|
var mu sync.Mutex
|
||||||
|
var forms []url.Values
|
||||||
|
var auths []string
|
||||||
|
var ts *httptest.Server
|
||||||
|
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": ts.URL + "/t/default", "token_endpoint": ts.URL + "/token",
|
||||||
|
"revocation_endpoint": ts.URL + "/revoke"})
|
||||||
|
})
|
||||||
|
record := func(r *http.Request) {
|
||||||
|
r.ParseForm()
|
||||||
|
mu.Lock()
|
||||||
|
forms = append(forms, r.PostForm)
|
||||||
|
auths = append(auths, r.Header.Get("Authorization"))
|
||||||
|
mu.Unlock()
|
||||||
|
}
|
||||||
|
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
record(r)
|
||||||
|
if r.PostForm.Get("refresh_token") != "rt-1" {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
fmt.Fprint(w, `{"error":"invalid_grant"}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprint(w, `{"access_token":"at-2","token_type":"Bearer","expires_in":300,"refresh_token":"rt-2","scope":"openid offline_access"}`)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("POST /revoke", func(w http.ResponseWriter, r *http.Request) { record(r) })
|
||||||
|
ts = httptest.NewServer(mux)
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
w := &Web{Client: Client{Issuer: ts.URL + "/t/default", ClientID: "web"}, ClientSecret: "s3cret", RedirectURL: "http://localhost/cb"}
|
||||||
|
nt, err := w.Refresh(context.Background(), &Token{AccessToken: "at-1", RefreshToken: "rt-1"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if nt.AccessToken != "at-2" || nt.RefreshToken != "rt-2" || nt.ClientID != "web" || time.Until(nt.Expiry) < 4*time.Minute {
|
||||||
|
t.Fatalf("token %+v", nt)
|
||||||
|
}
|
||||||
|
if f := forms[0]; f.Get("grant_type") != "refresh_token" || f.Has("client_id") || auths[0] != "Basic d2ViOnMzY3JldA==" {
|
||||||
|
t.Fatalf("form %v auth %q", f, auths[0])
|
||||||
|
}
|
||||||
|
if _, err := w.Refresh(context.Background(), &Token{RefreshToken: "stale"}); !errors.Is(err, ErrLoginRequired) {
|
||||||
|
t.Fatalf("stale: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := w.Refresh(context.Background(), &Token{AccessToken: "at"}); !errors.Is(err, ErrLoginRequired) {
|
||||||
|
t.Fatalf("no refresh token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
forms, auths = nil, nil
|
||||||
|
if err := w.Revoke(context.Background(), nt); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(forms) != 2 || forms[0].Get("token") != "rt-2" || forms[0].Get("token_type_hint") != "refresh_token" ||
|
||||||
|
forms[1].Get("token") != "at-2" || auths[1] != "Basic d2ViOnMzY3JldA==" {
|
||||||
|
t.Fatalf("revoke forms %v", forms)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A public client sends client_id instead.
|
||||||
|
pub := &Web{Client: Client{Issuer: ts.URL + "/t/default", ClientID: "web"}, RedirectURL: "http://localhost/cb"}
|
||||||
|
forms, auths = nil, nil
|
||||||
|
if _, err := pub.Refresh(context.Background(), &Token{RefreshToken: "rt-1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if forms[0].Get("client_id") != "web" || auths[0] != "" {
|
||||||
|
t.Fatalf("public: %v %q", forms[0], auths[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,424 @@
|
|||||||
|
package yaiam
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// op is a fake OpenID provider for a web sign-in: it hands out the code
|
||||||
|
// "the-code", answers the token endpoint with an ID token made by
|
||||||
|
// idClaims (unsigned: nothing here checks a signature) and UserInfo with
|
||||||
|
// userBody.
|
||||||
|
type op struct {
|
||||||
|
t *testing.T
|
||||||
|
ts *httptest.Server
|
||||||
|
issuer string
|
||||||
|
mu sync.Mutex
|
||||||
|
forms []url.Values
|
||||||
|
auths []string // Authorization headers of the token requests
|
||||||
|
claims func(nonce string) map[string]any
|
||||||
|
userBody string
|
||||||
|
nonce string // the nonce of the last authorization request
|
||||||
|
// noIDToken: the token answer has none
|
||||||
|
noIDToken bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newOP(t *testing.T) *op {
|
||||||
|
o := &op{t: t}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /t/default/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{"issuer": o.issuer, "authorization_endpoint": o.ts.URL + "/authorize",
|
||||||
|
"token_endpoint": o.ts.URL + "/token", "userinfo_endpoint": o.ts.URL + "/userinfo", "end_session_endpoint": o.ts.URL + "/logout"})
|
||||||
|
})
|
||||||
|
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.ParseForm()
|
||||||
|
o.mu.Lock()
|
||||||
|
o.forms = append(o.forms, r.PostForm)
|
||||||
|
o.auths = append(o.auths, r.Header.Get("Authorization"))
|
||||||
|
claims := o.claims(o.nonce)
|
||||||
|
noID := o.noIDToken
|
||||||
|
o.mu.Unlock()
|
||||||
|
if r.PostForm.Get("code") != "the-code" {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
fmt.Fprint(w, `{"error":"invalid_grant"}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out := map[string]any{"access_token": "at-1", "token_type": "Bearer", "expires_in": 300,
|
||||||
|
"id_token": jwt(claims), "scope": "openid profile"}
|
||||||
|
if noID {
|
||||||
|
delete(out, "id_token")
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(out)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /userinfo", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Header.Get("Authorization") != "Bearer at-1" {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprint(w, o.userBody)
|
||||||
|
})
|
||||||
|
o.ts = httptest.NewServer(mux)
|
||||||
|
t.Cleanup(o.ts.Close)
|
||||||
|
o.issuer = o.ts.URL + "/t/default"
|
||||||
|
o.userBody = `{"sub":"u-1","preferred_username":"alice","name":"Alice","email":"alice@example.org","email_verified":true,"groups":["staff","dev"],"roles":["editor"],"attributes":{"department":"IT"}}`
|
||||||
|
o.claims = func(nonce string) map[string]any {
|
||||||
|
now := time.Now()
|
||||||
|
return map[string]any{"iss": o.issuer, "sub": "u-1", "aud": "web", "exp": now.Add(5 * time.Minute).Unix(), "iat": now.Unix(),
|
||||||
|
"nonce": nonce, "acr": "mfa", "amr": []string{"pwd", "otp"}, "auth_time": now.Unix()}
|
||||||
|
}
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// jwt is an unsigned JWT with claims.
|
||||||
|
func jwt(claims map[string]any) string {
|
||||||
|
raw, _ := json.Marshal(claims)
|
||||||
|
return base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256"}`)) + "." + base64.RawURLEncoding.EncodeToString(raw) + ".c2ln"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *op) web() *Web {
|
||||||
|
return &Web{Client: Client{Issuer: o.issuer, ClientID: "web"}, ClientSecret: "s3cret",
|
||||||
|
RedirectURL: "http://localhost:8097/callback", PostLogoutRedirectURL: "http://localhost:8097/"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// start runs SignIn and returns the authorization request's parameters
|
||||||
|
// and the sign-in cookie.
|
||||||
|
func (o *op) start(t *testing.T, w *Web, returnTo string) (url.Values, *http.Cookie) {
|
||||||
|
t.Helper()
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
if err := w.SignIn(context.Background(), rec, httptest.NewRequest(http.MethodGet, "/login", nil), returnTo); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if rec.Code != http.StatusFound {
|
||||||
|
t.Fatalf("status %d", rec.Code)
|
||||||
|
}
|
||||||
|
loc, _ := url.Parse(rec.Header().Get("Location"))
|
||||||
|
if loc.Scheme+"://"+loc.Host+loc.Path != o.ts.URL+"/authorize" {
|
||||||
|
t.Fatalf("redirect to %s", loc)
|
||||||
|
}
|
||||||
|
cs := rec.Result().Cookies()
|
||||||
|
if len(cs) != 1 {
|
||||||
|
t.Fatalf("cookies %v", cs)
|
||||||
|
}
|
||||||
|
q := loc.Query()
|
||||||
|
o.mu.Lock()
|
||||||
|
o.nonce = q.Get("nonce")
|
||||||
|
o.mu.Unlock()
|
||||||
|
return q, cs[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
// callback runs Callback for the redirect back with query and cookie.
|
||||||
|
func callback(w *Web, query string, cookie *http.Cookie) (*SignedIn, *httptest.ResponseRecorder, error) {
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/callback?"+query, nil)
|
||||||
|
if cookie != nil {
|
||||||
|
req.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
s, err := w.Callback(context.Background(), rec, req)
|
||||||
|
return s, rec, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWebSignIn: SignIn sends the browser to the provider with state,
|
||||||
|
// nonce and an S256 challenge, remembered in a short cookie; Callback
|
||||||
|
// trades the code with the verifier (client_secret_basic), checks the ID
|
||||||
|
// token and takes the profile, groups and roles from UserInfo.
|
||||||
|
func TestWebSignIn(t *testing.T) {
|
||||||
|
o := newOP(t)
|
||||||
|
w := o.web()
|
||||||
|
q, cookie := o.start(t, w, "/staff?x=1")
|
||||||
|
if q.Get("response_type") != "code" || q.Get("client_id") != "web" || q.Get("redirect_uri") != w.RedirectURL ||
|
||||||
|
q.Get("scope") != "openid profile email groups roles attributes" || q.Get("code_challenge_method") != "S256" || q.Get("state") == "" || q.Get("nonce") == "" {
|
||||||
|
t.Errorf("authorization request %v", q)
|
||||||
|
}
|
||||||
|
if !cookie.HttpOnly || cookie.SameSite != http.SameSiteLaxMode || cookie.Name != "yaiam_signin" || cookie.Secure || cookie.MaxAge != 600 {
|
||||||
|
t.Errorf("cookie %+v", cookie)
|
||||||
|
}
|
||||||
|
s, rec, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}, "iss": {o.issuer}}.Encode(), cookie)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if s.Subject != "u-1" || s.Username != "alice" || s.Name != "Alice" || s.Email != "alice@example.org" || !s.EmailVerified ||
|
||||||
|
strings.Join(s.Groups, ",") != "staff,dev" || strings.Join(s.Roles, ",") != "editor" || s.Attributes["department"] != "IT" || len(s.Attributes) != 1 || s.ACR != "mfa" || s.AuthTime.IsZero() ||
|
||||||
|
s.ReturnTo != "/staff?x=1" || s.Token.AccessToken != "at-1" || s.IDToken == "" {
|
||||||
|
t.Errorf("signed in %+v", s)
|
||||||
|
}
|
||||||
|
if c := rec.Result().Cookies(); len(c) != 1 || c[0].MaxAge >= 0 {
|
||||||
|
t.Errorf("the cookie was not removed: %v", c)
|
||||||
|
}
|
||||||
|
form := o.forms[0]
|
||||||
|
sum := sha256.Sum256([]byte(form.Get("code_verifier")))
|
||||||
|
if base64.RawURLEncoding.EncodeToString(sum[:]) != q.Get("code_challenge") || form.Get("redirect_uri") != w.RedirectURL ||
|
||||||
|
form.Get("grant_type") != "authorization_code" || form.Has("client_secret") || form.Has("client_id") {
|
||||||
|
t.Errorf("token request %v", form)
|
||||||
|
}
|
||||||
|
if u, p, ok := (&http.Request{Header: http.Header{"Authorization": {o.auths[0]}}}).BasicAuth(); !ok || u != "web" || p != "s3cret" {
|
||||||
|
t.Errorf("client authentication %q", o.auths[0])
|
||||||
|
}
|
||||||
|
for _, leak := range []string{"at-1", s.IDToken} {
|
||||||
|
if strings.Contains(fmt.Sprint(s), leak) || strings.Contains(fmt.Sprintf("%#v", s), leak) {
|
||||||
|
t.Error("a token in what fmt prints")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A public client: the client ID in the form, no Authorization.
|
||||||
|
pub := o.web()
|
||||||
|
pub.ClientSecret = ""
|
||||||
|
q, cookie = o.start(t, pub, "")
|
||||||
|
if s, _, err := callback(pub, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), cookie); err != nil || s.ReturnTo != "/" {
|
||||||
|
t.Fatalf("public: %+v, %v", s, err)
|
||||||
|
}
|
||||||
|
if last := o.forms[len(o.forms)-1]; last.Get("client_id") != "web" || o.auths[len(o.auths)-1] != "" {
|
||||||
|
t.Errorf("public token request %v %q", last, o.auths[len(o.auths)-1])
|
||||||
|
}
|
||||||
|
|
||||||
|
// https: a __Host- cookie, Secure -- a name of one's own too.
|
||||||
|
sec := o.web()
|
||||||
|
sec.RedirectURL = "https://app.example.org/callback"
|
||||||
|
if _, c := o.start(t, sec, "/"); c.Name != "__Host-yaiam_signin" || !c.Secure {
|
||||||
|
t.Errorf("https cookie %+v", c)
|
||||||
|
}
|
||||||
|
sec.CookieName = "mine"
|
||||||
|
if _, c := o.start(t, sec, "/"); c.Name != "__Host-mine" {
|
||||||
|
t.Errorf("https cookie of its own name %+v", c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A planted cookie's return path is checked again.
|
||||||
|
q, cookie = o.start(t, w, "/")
|
||||||
|
raw, _ := base64.RawURLEncoding.DecodeString(cookie.Value)
|
||||||
|
var v signInCookie
|
||||||
|
json.Unmarshal(raw, &v)
|
||||||
|
v.ReturnTo = "//evil.example"
|
||||||
|
raw, _ = json.Marshal(v)
|
||||||
|
cookie.Value = base64.RawURLEncoding.EncodeToString(raw)
|
||||||
|
if s, _, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), cookie); err != nil || s.ReturnTo != "/" {
|
||||||
|
t.Errorf("planted return path: %+v, %v", s, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWebCallbackRefuses: a callback without this browser's cookie, with
|
||||||
|
// another state, after the cookie's time, from another issuer, with an
|
||||||
|
// error of the provider, or whose ID token or UserInfo does not fit,
|
||||||
|
// signs nobody in.
|
||||||
|
func TestWebCallbackRefuses(t *testing.T) {
|
||||||
|
o := newOP(t)
|
||||||
|
w := o.web()
|
||||||
|
good := o.claims
|
||||||
|
try := func(name string, mod func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie), want error, claims func(string) map[string]any) {
|
||||||
|
t.Helper()
|
||||||
|
o.claims = good
|
||||||
|
if claims != nil {
|
||||||
|
o.claims = claims
|
||||||
|
}
|
||||||
|
q, c := o.start(t, w, "/")
|
||||||
|
cb := url.Values{"code": {"the-code"}, "state": {q.Get("state")}}
|
||||||
|
if mod != nil {
|
||||||
|
cb, c = mod(cb, c)
|
||||||
|
}
|
||||||
|
s, _, err := callback(w, cb.Encode(), c)
|
||||||
|
if err == nil || s != nil || want != nil && !errors.Is(err, want) {
|
||||||
|
t.Errorf("%s: %+v, %v", name, s, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try("no cookie", func(q url.Values, _ *http.Cookie) (url.Values, *http.Cookie) { return q, nil }, ErrSignInState, nil)
|
||||||
|
try("another state", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Set("state", "x"); return q, c }, ErrSignInState, nil)
|
||||||
|
try("junk cookie", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { c.Value = "!!"; return q, c }, ErrSignInState, nil)
|
||||||
|
try("expired", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) {
|
||||||
|
raw, _ := base64.RawURLEncoding.DecodeString(c.Value)
|
||||||
|
var v signInCookie
|
||||||
|
json.Unmarshal(raw, &v)
|
||||||
|
v.Expires = time.Now().Add(-time.Second).Unix()
|
||||||
|
raw, _ = json.Marshal(v)
|
||||||
|
c.Value = base64.RawURLEncoding.EncodeToString(raw)
|
||||||
|
return q, c
|
||||||
|
}, ErrSignInState, nil)
|
||||||
|
try("other issuer", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) {
|
||||||
|
q.Set("iss", "https://evil.example")
|
||||||
|
return q, c
|
||||||
|
}, nil, nil)
|
||||||
|
try("provider error", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) {
|
||||||
|
q.Del("code")
|
||||||
|
q.Set("error", "access_denied")
|
||||||
|
return q, c
|
||||||
|
}, ErrSignInRefused, nil)
|
||||||
|
try("no code", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Del("code"); return q, c }, nil, nil)
|
||||||
|
try("bad code", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Set("code", "x"); return q, c }, nil, nil)
|
||||||
|
with := func(k string, v any) func(string) map[string]any {
|
||||||
|
return func(n string) map[string]any { c := good(n); c[k] = v; return c }
|
||||||
|
}
|
||||||
|
try("issuer", nil, nil, with("iss", "https://evil.example"))
|
||||||
|
try("audience", nil, nil, with("aud", "other"))
|
||||||
|
try("several audiences, other azp", nil, nil, with("aud", []string{"web", "other"}))
|
||||||
|
o.userBody = `{"sub":""}`
|
||||||
|
try("no subject", nil, nil, with("sub", ""))
|
||||||
|
o.userBody = `{"sub":"u-1"}`
|
||||||
|
o.noIDToken = true
|
||||||
|
try("no ID token", nil, nil, nil)
|
||||||
|
o.noIDToken = false
|
||||||
|
try("expired token", nil, nil, with("exp", time.Now().Add(-2*time.Minute).Unix()))
|
||||||
|
try("issued in the future", nil, nil, with("iat", time.Now().Add(2*time.Minute).Unix()))
|
||||||
|
try("other nonce", nil, nil, with("nonce", "x"))
|
||||||
|
o.userBody = `{"sub":"u-2","preferred_username":"mallory"}`
|
||||||
|
try("UserInfo of another user", nil, nil, nil)
|
||||||
|
|
||||||
|
// Several audiences with azp this client: fine.
|
||||||
|
o.userBody = `{"sub":"u-1"}`
|
||||||
|
o.claims = func(n string) map[string]any {
|
||||||
|
c := good(n)
|
||||||
|
c["aud"] = []string{"web", "api"}
|
||||||
|
c["azp"] = "web"
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
q, c := o.start(t, w, "/")
|
||||||
|
if _, _, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), c); err != nil {
|
||||||
|
t.Errorf("azp: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWebConfig: an http redirect URL off loopback, or no openid, is
|
||||||
|
// refused; a return path elsewhere becomes "/"; the logout URL carries
|
||||||
|
// the hint and the post-logout redirect.
|
||||||
|
func TestWebConfig(t *testing.T) {
|
||||||
|
o := newOP(t)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/login", nil)
|
||||||
|
bad := o.web()
|
||||||
|
bad.RedirectURL = "http://app.example.org/callback"
|
||||||
|
if err := bad.SignIn(context.Background(), rec, req, "/"); err == nil {
|
||||||
|
t.Error("http redirect URL taken")
|
||||||
|
}
|
||||||
|
noOpenID := o.web()
|
||||||
|
noOpenID.Scopes = []string{"profile"}
|
||||||
|
if err := noOpenID.SignIn(context.Background(), rec, req, "/"); err == nil {
|
||||||
|
t.Error("no openid taken")
|
||||||
|
}
|
||||||
|
for in, want := range map[string]string{"/a?b=c": "/a?b=c", "//evil.example": "/", "https://evil.example": "/", "/\\evil": "/",
|
||||||
|
"": "/", "a": "/", "/x\r\nSet-Cookie: y": "/", "/\t/evil.example": "/", "/\t\\evil": "/", "/a\x7f": "/", "/a\\b": "/"} {
|
||||||
|
if got := localPath(in); got != want {
|
||||||
|
t.Errorf("localPath(%q) = %q", in, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
u, err := o.web().LogoutURL(context.Background(), "the-id-token")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
lu, _ := url.Parse(u)
|
||||||
|
if !strings.HasPrefix(u, o.ts.URL+"/logout?") || lu.Query().Get("id_token_hint") != "the-id-token" ||
|
||||||
|
lu.Query().Get("post_logout_redirect_uri") != "http://localhost:8097/" || lu.Query().Get("client_id") != "web" {
|
||||||
|
t.Errorf("logout URL %s", u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDeviceNeedsItsEndpoint: a provider without a device authorization
|
||||||
|
// endpoint serves a web sign-in, but StartDevice says it has none.
|
||||||
|
func TestDeviceNeedsItsEndpoint(t *testing.T) {
|
||||||
|
o := newOP(t)
|
||||||
|
c := &Client{Issuer: o.issuer, ClientID: "cli"}
|
||||||
|
if _, err := c.StartDevice(context.Background()); err == nil || !strings.Contains(err.Error(), "no device sign-in") {
|
||||||
|
t.Errorf("start device: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWebPublicIssuer: with PublicIssuer the browser goes to the
|
||||||
|
// provider's endpoints on the public origin, the server keeps using
|
||||||
|
// Issuer, and the callback's iss may name either; a public issuer with
|
||||||
|
// another path is refused.
|
||||||
|
func TestWebPublicIssuer(t *testing.T) {
|
||||||
|
o := newOP(t)
|
||||||
|
w := o.web()
|
||||||
|
pubOrigin := strings.Replace(o.ts.URL, "127.0.0.1", "localhost", 1)
|
||||||
|
w.PublicIssuer = pubOrigin + "/t/default"
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
if err := w.SignIn(context.Background(), rec, httptest.NewRequest(http.MethodGet, "/login", nil), "/"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
loc, _ := url.Parse(rec.Header().Get("Location"))
|
||||||
|
if loc.Scheme+"://"+loc.Host+loc.Path != pubOrigin+"/authorize" {
|
||||||
|
t.Fatalf("redirect to %s", loc)
|
||||||
|
}
|
||||||
|
o.mu.Lock()
|
||||||
|
o.nonce = loc.Query().Get("nonce")
|
||||||
|
o.mu.Unlock()
|
||||||
|
cookie := rec.Result().Cookies()[0]
|
||||||
|
cb := url.Values{"code": {"the-code"}, "state": {loc.Query().Get("state")}, "iss": {w.PublicIssuer}}
|
||||||
|
if s, _, err := callback(w, cb.Encode(), cookie); err != nil || s.Subject != "u-1" {
|
||||||
|
t.Fatalf("iss = public issuer: %+v, %v", s, err)
|
||||||
|
}
|
||||||
|
if u, err := w.LogoutURL(context.Background(), ""); err != nil || !strings.HasPrefix(u, pubOrigin+"/logout?") {
|
||||||
|
t.Errorf("logout URL %q, %v", u, err)
|
||||||
|
}
|
||||||
|
other := o.web()
|
||||||
|
other.PublicIssuer = pubOrigin + "/t/other"
|
||||||
|
if err := other.SignIn(context.Background(), httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/login", nil), "/"); err == nil {
|
||||||
|
t.Error("public issuer with another path taken")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWebEmailVerified: only the JSON boolean true confirms the address;
|
||||||
|
// the string "true" or no claim leaves it unconfirmed without failing.
|
||||||
|
func TestWebEmailVerified(t *testing.T) {
|
||||||
|
o := newOP(t)
|
||||||
|
w := o.web()
|
||||||
|
for body, want := range map[string]bool{
|
||||||
|
`{"sub":"u-1","email":"a@example.org","email_verified":true}`: true,
|
||||||
|
`{"sub":"u-1","email":"a@example.org","email_verified":"true"}`: false,
|
||||||
|
`{"sub":"u-1","email":"a@example.org","email_verified":1}`: false,
|
||||||
|
`{"sub":"u-1","email":"a@example.org"}`: false,
|
||||||
|
} {
|
||||||
|
o.userBody = body
|
||||||
|
q, c := o.start(t, w, "/")
|
||||||
|
s, _, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), c)
|
||||||
|
if err != nil || s.EmailVerified != want || s.Email != "a@example.org" {
|
||||||
|
t.Errorf("%s: %+v, %v", body, s, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAllowInsecure: plain http off loopback only with AllowInsecure.
|
||||||
|
func TestAllowInsecure(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
url string
|
||||||
|
insecure bool
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{"http://oidc:8080/default", false, false},
|
||||||
|
{"http://oidc:8080/default", true, true},
|
||||||
|
{"http://127.0.0.1:8080/default", false, true},
|
||||||
|
{"https://login.example.org/t/default", false, true},
|
||||||
|
{"ftp://oidc/default", true, false},
|
||||||
|
{"/default", true, false},
|
||||||
|
} {
|
||||||
|
if err := checkURL("issuer", c.url, c.insecure); (err == nil) != c.ok {
|
||||||
|
t.Errorf("%s (insecure %v): %v", c.url, c.insecure, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w := &Web{Client: Client{Issuer: "http://oidc:8080/default", ClientID: "web", AllowInsecure: true},
|
||||||
|
RedirectURL: "http://app:8787/auth/callback"}
|
||||||
|
if err := w.check(); err != nil {
|
||||||
|
t.Errorf("insecure web: %v", err)
|
||||||
|
}
|
||||||
|
w.AllowInsecure = false
|
||||||
|
if err := w.check(); err == nil {
|
||||||
|
t.Error("http redirect URL off loopback taken without AllowInsecure")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWebCallbackBeforeProvider: a callback without this browser's
|
||||||
|
// sign-in is refused before the provider is asked (here: unreachable).
|
||||||
|
func TestWebCallbackBeforeProvider(t *testing.T) {
|
||||||
|
w := &Web{Client: Client{Issuer: "http://127.0.0.1:9/t/default", ClientID: "web"}, RedirectURL: "http://localhost:8097/callback"}
|
||||||
|
for _, cookie := range []*http.Cookie{nil, {Name: "yaiam_signin", Value: "!!"}} {
|
||||||
|
if _, _, err := callback(w, "code=c&state=s", cookie); !errors.Is(err, ErrSignInState) {
|
||||||
|
t.Errorf("cookie %v: %v", cookie, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+36
-13
@@ -88,8 +88,16 @@ type Client struct {
|
|||||||
// again once the access token runs out.
|
// again once the access token runs out.
|
||||||
Scopes []string
|
Scopes []string
|
||||||
// HTTPClient sends the requests; nil means one with a 30 s timeout.
|
// HTTPClient sends the requests; nil means one with a 30 s timeout.
|
||||||
// Redirects are never followed, whichever client it is.
|
// Redirects are never followed, whichever client it is. It must check
|
||||||
|
// TLS certificates: a web sign-in trusts the ID token because it
|
||||||
|
// comes from the token endpoint over TLS.
|
||||||
HTTPClient *http.Client
|
HTTPClient *http.Client
|
||||||
|
// AllowInsecure accepts plain http on any host, not only on loopback:
|
||||||
|
// for a test installation whose provider sits on a closed network
|
||||||
|
// (e.g. a compose network, "http://oidc:8080/default"). Without TLS a
|
||||||
|
// web sign-in's ID token is only as trustworthy as that network --
|
||||||
|
// never set it for a provider reached over the internet.
|
||||||
|
AllowInsecure bool
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
meta *metadata
|
meta *metadata
|
||||||
@@ -103,6 +111,8 @@ type metadata struct {
|
|||||||
DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`
|
DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`
|
||||||
RevocationEndpoint string `json:"revocation_endpoint"`
|
RevocationEndpoint string `json:"revocation_endpoint"`
|
||||||
UserinfoEndpoint string `json:"userinfo_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
|
// httpClient is HTTPClient (or the default) without redirects: an answer
|
||||||
@@ -132,7 +142,7 @@ func (c *Client) discover(ctx context.Context) (*metadata, error) {
|
|||||||
if m != nil {
|
if m != nil {
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
if err := checkURL("issuer", c.Issuer); err != nil {
|
if err := checkURL("issuer", c.Issuer, c.AllowInsecure); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if c.ClientID == "" {
|
if c.ClientID == "" {
|
||||||
@@ -157,14 +167,16 @@ func (c *Client) discover(ctx context.Context) (*metadata, error) {
|
|||||||
if m.Issuer != c.Issuer {
|
if m.Issuer != c.Issuer {
|
||||||
return nil, fmt.Errorf("yaiam: discovery names the issuer %q, not %q", m.Issuer, c.Issuer)
|
return nil, fmt.Errorf("yaiam: discovery names the issuer %q, not %q", m.Issuer, c.Issuer)
|
||||||
}
|
}
|
||||||
for name, u := range map[string]string{"token_endpoint": m.TokenEndpoint, "device_authorization_endpoint": m.DeviceAuthorizationEndpoint} {
|
if err := checkURL("token_endpoint", m.TokenEndpoint, c.AllowInsecure); err != nil {
|
||||||
if err := checkURL(name, u); err != nil {
|
return nil, err
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
for name, u := range map[string]string{"revocation_endpoint": m.RevocationEndpoint, "userinfo_endpoint": m.UserinfoEndpoint} {
|
// The others only where a flow needs them (device: StartDevice; web:
|
||||||
|
// Web.SignIn); those that are named must be https.
|
||||||
|
for name, u := range map[string]string{"revocation_endpoint": m.RevocationEndpoint, "userinfo_endpoint": m.UserinfoEndpoint,
|
||||||
|
"device_authorization_endpoint": m.DeviceAuthorizationEndpoint, "authorization_endpoint": m.AuthorizationEndpoint,
|
||||||
|
"end_session_endpoint": m.EndSessionEndpoint} {
|
||||||
if u != "" {
|
if u != "" {
|
||||||
if err := checkURL(name, u); err != nil {
|
if err := checkURL(name, u, c.AllowInsecure); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -176,8 +188,8 @@ func (c *Client) discover(ctx context.Context) (*metadata, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// checkURL refuses anything but an absolute https URL, or http on a
|
// checkURL refuses anything but an absolute https URL, or http on a
|
||||||
// loopback host.
|
// loopback host (any host with insecure).
|
||||||
func checkURL(name, s string) error {
|
func checkURL(name, s string, insecure bool) error {
|
||||||
u, err := url.Parse(s)
|
u, err := url.Parse(s)
|
||||||
if err != nil || u.Host == "" {
|
if err != nil || u.Host == "" {
|
||||||
return fmt.Errorf("yaiam: %s %q is not an absolute URL", name, s)
|
return fmt.Errorf("yaiam: %s %q is not an absolute URL", name, s)
|
||||||
@@ -185,7 +197,7 @@ func checkURL(name, s string) error {
|
|||||||
switch {
|
switch {
|
||||||
case u.Scheme == "https":
|
case u.Scheme == "https":
|
||||||
return nil
|
return nil
|
||||||
case u.Scheme == "http" && isLoopback(u.Hostname()):
|
case u.Scheme == "http" && (insecure || isLoopback(u.Hostname())):
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return fmt.Errorf("yaiam: %s %q is not https", name, s)
|
return fmt.Errorf("yaiam: %s %q is not https", name, s)
|
||||||
@@ -201,16 +213,21 @@ func isLoopback(host string) bool {
|
|||||||
|
|
||||||
// do sends req and reads at most maxBody of the answer.
|
// do sends req and reads at most maxBody of the answer.
|
||||||
func (c *Client) do(req *http.Request) (int, []byte, error) {
|
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)
|
resp, err := c.httpClient().Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, nil, err
|
return 0, nil, err
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))
|
body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, nil, err
|
return 0, nil, err
|
||||||
}
|
}
|
||||||
if len(body) > maxBody {
|
if int64(len(body)) > limit {
|
||||||
return 0, nil, errors.New("answer too large")
|
return 0, nil, errors.New("answer too large")
|
||||||
}
|
}
|
||||||
return resp.StatusCode, body, nil
|
return resp.StatusCode, body, nil
|
||||||
@@ -225,6 +242,12 @@ func (c *Client) post(ctx context.Context, name, endpoint string, form url.Value
|
|||||||
}
|
}
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
|
return c.send(name, req, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// send sends req. A 200 answer is decoded into out (if not nil); any
|
||||||
|
// other is returned as *Error.
|
||||||
|
func (c *Client) send(name string, req *http.Request, out any) error {
|
||||||
status, body, err := c.do(req)
|
status, body, err := c.do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("yaiam: %s: %w", name, err)
|
return fmt.Errorf("yaiam: %s: %w", name, err)
|
||||||
|
|||||||
Reference in new issue
Block a user