diff --git a/README.md b/README.md index 9261a81..a8fb02b 100644 --- a/README.md +++ b/README.md @@ -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/confluence` | small Confluence REST API client (classic content API) | | `atlassian/internal/transport` | the HTTP machinery both share; not importable from outside | -| `yaiam` | sign a command-line program in at yaiam (device flow, RFC 8628) and keep its tokens (YAIAM-710, 2026-11-09); 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) | +| `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) | Standard library only, no third-party dependencies. @@ -179,6 +179,11 @@ out, _ := web.LogoutURL(ctx, u.IDToken) 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 diff --git a/yaiam/web_refresh.go b/yaiam/web_refresh.go new file mode 100644 index 0000000..2e625ad --- /dev/null +++ b/yaiam/web_refresh.go @@ -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) +} diff --git a/yaiam/web_refresh_test.go b/yaiam/web_refresh_test.go new file mode 100644 index 0000000..afc6923 --- /dev/null +++ b/yaiam/web_refresh_test.go @@ -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]) + } +}