Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d062f559f | ||
|
|
c2a5e3928a | ||
|
|
560a1ead8a |
No files matched your search
@@ -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); sign a web application's users in (code flow with PKCE) and read users and groups from yaiam's admin API (2026-11-17) |
|
| `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.
|
||||||
|
|
||||||
@@ -179,6 +179,11 @@ out, _ := web.LogoutURL(ctx, u.IDToken)
|
|||||||
is sent to the endpoints on the public origin; the server keeps
|
is sent to the endpoints on the public origin; the server keeps
|
||||||
`Issuer`. `AllowInsecure` (on `Client`) accepts plain http off
|
`Issuer`. `AllowInsecure` (on `Client`) accepts plain http off
|
||||||
loopback, for a test installation on a closed network only.
|
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` reads a tenant's users, groups and group members from yaiam's
|
||||||
admin API with a service client's token (client credentials, cached
|
admin API with a service client's token (client credentials, cached
|
||||||
@@ -188,6 +193,49 @@ An example web application is yaiam's `examples/webapp`; an end-to-end
|
|||||||
test against a real yaiam-authd is yaiam's
|
test against a real yaiam-authd is yaiam's
|
||||||
`internal/oidcprovider/weblogin_test.go`.
|
`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;
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -242,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