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 "). 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) }