rebase: bump golang.org/x/oauth2 in /actions/retest

Bumps [golang.org/x/oauth2](https://github.com/golang/oauth2) from 0.29.0 to 0.30.0.
- [Commits](https://github.com/golang/oauth2/compare/v0.29.0...v0.30.0)

---
updated-dependencies:
- dependency-name: golang.org/x/oauth2
  dependency-version: 0.30.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
dependabot[bot] 2025-05-05 21:20:28 +00:00 committed by mergify[bot]
parent 86576b4e11
commit 4147d5d15a
11 changed files with 84 additions and 94 deletions

View File

@ -6,7 +6,7 @@ toolchain go1.23.6
require ( require (
github.com/google/go-github v17.0.0+incompatible github.com/google/go-github v17.0.0+incompatible
golang.org/x/oauth2 v0.29.0 golang.org/x/oauth2 v0.30.0
) )
require github.com/google/go-querystring v1.1.0 // indirect require github.com/google/go-querystring v1.1.0 // indirect

View File

@ -1,10 +1,9 @@
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY= github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY=
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
golang.org/x/oauth2 v0.29.0 h1:WdYw2tdTK1S8olAzWHdgeqfy+Mtm9XNhv/xJsY65d98= golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.29.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View File

@ -2,5 +2,5 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
// Package internal contains support packages for oauth2 package. // Package internal contains support packages for [golang.org/x/oauth2].
package internal package internal

View File

@ -13,7 +13,7 @@ import (
) )
// ParseKey converts the binary contents of a private key file // ParseKey converts the binary contents of a private key file
// to an *rsa.PrivateKey. It detects whether the private key is in a // to an [*rsa.PrivateKey]. It detects whether the private key is in a
// PEM container or not. If so, it extracts the private key // PEM container or not. If so, it extracts the private key
// from PEM container before conversion. It only supports PEM // from PEM container before conversion. It only supports PEM
// containers with no passphrase. // containers with no passphrase.

View File

@ -10,7 +10,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"math" "math"
"mime" "mime"
"net/http" "net/http"
@ -26,9 +25,9 @@ import (
// the requests to access protected resources on the OAuth 2.0 // the requests to access protected resources on the OAuth 2.0
// provider's backend. // provider's backend.
// //
// This type is a mirror of oauth2.Token and exists to break // This type is a mirror of [golang.org/x/oauth2.Token] and exists to break
// an otherwise-circular dependency. Other internal packages // an otherwise-circular dependency. Other internal packages
// should convert this Token into an oauth2.Token before use. // should convert this Token into an [golang.org/x/oauth2.Token] before use.
type Token struct { type Token struct {
// AccessToken is the token that authorizes and authenticates // AccessToken is the token that authorizes and authenticates
// the requests. // the requests.
@ -50,9 +49,16 @@ type Token struct {
// mechanisms for that TokenSource will not be used. // mechanisms for that TokenSource will not be used.
Expiry time.Time Expiry time.Time
// ExpiresIn is the OAuth2 wire format "expires_in" field,
// which specifies how many seconds later the token expires,
// relative to an unknown time base approximately around "now".
// It is the application's responsibility to populate
// `Expiry` from `ExpiresIn` when required.
ExpiresIn int64 `json:"expires_in,omitempty"`
// Raw optionally contains extra metadata from the server // Raw optionally contains extra metadata from the server
// when updating a token. // when updating a token.
Raw interface{} Raw any
} }
// tokenJSON is the struct representing the HTTP response from OAuth2 // tokenJSON is the struct representing the HTTP response from OAuth2
@ -99,14 +105,6 @@ func (e *expirationTime) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op.
//
// Deprecated: this function no longer does anything. Caller code that
// wants to avoid potential extra HTTP requests made during
// auto-probing of the provider's auth style should set
// Endpoint.AuthStyle.
func RegisterBrokenAuthHeaderProvider(tokenURL string) {}
// AuthStyle is a copy of the golang.org/x/oauth2 package's AuthStyle type. // AuthStyle is a copy of the golang.org/x/oauth2 package's AuthStyle type.
type AuthStyle int type AuthStyle int
@ -143,6 +141,11 @@ func (lc *LazyAuthStyleCache) Get() *AuthStyleCache {
return c return c
} }
type authStyleCacheKey struct {
url string
clientID string
}
// AuthStyleCache is the set of tokenURLs we've successfully used via // AuthStyleCache is the set of tokenURLs we've successfully used via
// RetrieveToken and which style auth we ended up using. // RetrieveToken and which style auth we ended up using.
// It's called a cache, but it doesn't (yet?) shrink. It's expected that // It's called a cache, but it doesn't (yet?) shrink. It's expected that
@ -150,26 +153,26 @@ func (lc *LazyAuthStyleCache) Get() *AuthStyleCache {
// small. // small.
type AuthStyleCache struct { type AuthStyleCache struct {
mu sync.Mutex mu sync.Mutex
m map[string]AuthStyle // keyed by tokenURL m map[authStyleCacheKey]AuthStyle
} }
// lookupAuthStyle reports which auth style we last used with tokenURL // lookupAuthStyle reports which auth style we last used with tokenURL
// when calling RetrieveToken and whether we have ever done so. // when calling RetrieveToken and whether we have ever done so.
func (c *AuthStyleCache) lookupAuthStyle(tokenURL string) (style AuthStyle, ok bool) { func (c *AuthStyleCache) lookupAuthStyle(tokenURL, clientID string) (style AuthStyle, ok bool) {
c.mu.Lock() c.mu.Lock()
defer c.mu.Unlock() defer c.mu.Unlock()
style, ok = c.m[tokenURL] style, ok = c.m[authStyleCacheKey{tokenURL, clientID}]
return return
} }
// setAuthStyle adds an entry to authStyleCache, documented above. // setAuthStyle adds an entry to authStyleCache, documented above.
func (c *AuthStyleCache) setAuthStyle(tokenURL string, v AuthStyle) { func (c *AuthStyleCache) setAuthStyle(tokenURL, clientID string, v AuthStyle) {
c.mu.Lock() c.mu.Lock()
defer c.mu.Unlock() defer c.mu.Unlock()
if c.m == nil { if c.m == nil {
c.m = make(map[string]AuthStyle) c.m = make(map[authStyleCacheKey]AuthStyle)
} }
c.m[tokenURL] = v c.m[authStyleCacheKey{tokenURL, clientID}] = v
} }
// newTokenRequest returns a new *http.Request to retrieve a new token // newTokenRequest returns a new *http.Request to retrieve a new token
@ -210,9 +213,9 @@ func cloneURLValues(v url.Values) url.Values {
} }
func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values, authStyle AuthStyle, styleCache *AuthStyleCache) (*Token, error) { func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values, authStyle AuthStyle, styleCache *AuthStyleCache) (*Token, error) {
needsAuthStyleProbe := authStyle == 0 needsAuthStyleProbe := authStyle == AuthStyleUnknown
if needsAuthStyleProbe { if needsAuthStyleProbe {
if style, ok := styleCache.lookupAuthStyle(tokenURL); ok { if style, ok := styleCache.lookupAuthStyle(tokenURL, clientID); ok {
authStyle = style authStyle = style
needsAuthStyleProbe = false needsAuthStyleProbe = false
} else { } else {
@ -242,7 +245,7 @@ func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string,
token, err = doTokenRoundTrip(ctx, req) token, err = doTokenRoundTrip(ctx, req)
} }
if needsAuthStyleProbe && err == nil { if needsAuthStyleProbe && err == nil {
styleCache.setAuthStyle(tokenURL, authStyle) styleCache.setAuthStyle(tokenURL, clientID, authStyle)
} }
// Don't overwrite `RefreshToken` with an empty value // Don't overwrite `RefreshToken` with an empty value
// if this was a token refreshing request. // if this was a token refreshing request.
@ -257,7 +260,7 @@ func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20)) body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
r.Body.Close() r.Body.Close()
if err != nil { if err != nil {
return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
@ -312,7 +315,8 @@ func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) {
TokenType: tj.TokenType, TokenType: tj.TokenType,
RefreshToken: tj.RefreshToken, RefreshToken: tj.RefreshToken,
Expiry: tj.expiry(), Expiry: tj.expiry(),
Raw: make(map[string]interface{}), ExpiresIn: int64(tj.ExpiresIn),
Raw: make(map[string]any),
} }
json.Unmarshal(body, &token.Raw) // no error checks for optional fields json.Unmarshal(body, &token.Raw) // no error checks for optional fields
} }

View File

@ -9,8 +9,8 @@ import (
"net/http" "net/http"
) )
// HTTPClient is the context key to use with golang.org/x/net/context's // HTTPClient is the context key to use with [context.WithValue]
// WithValue function to associate an *http.Client value with a context. // to associate an [*http.Client] value with a context.
var HTTPClient ContextKey var HTTPClient ContextKey
// ContextKey is just an empty struct. It exists so HTTPClient can be // ContextKey is just an empty struct. It exists so HTTPClient can be

View File

@ -22,9 +22,9 @@ import (
) )
// NoContext is the default context you should supply if not using // NoContext is the default context you should supply if not using
// your own context.Context (see https://golang.org/x/net/context). // your own [context.Context].
// //
// Deprecated: Use context.Background() or context.TODO() instead. // Deprecated: Use [context.Background] or [context.TODO] instead.
var NoContext = context.TODO() var NoContext = context.TODO()
// RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op. // RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op.
@ -37,8 +37,8 @@ func RegisterBrokenAuthHeaderProvider(tokenURL string) {}
// Config describes a typical 3-legged OAuth2 flow, with both the // Config describes a typical 3-legged OAuth2 flow, with both the
// client application information and the server's endpoint URLs. // client application information and the server's endpoint URLs.
// For the client credentials 2-legged OAuth2 flow, see the clientcredentials // For the client credentials 2-legged OAuth2 flow, see the
// package (https://golang.org/x/oauth2/clientcredentials). // [golang.org/x/oauth2/clientcredentials] package.
type Config struct { type Config struct {
// ClientID is the application's ID. // ClientID is the application's ID.
ClientID string ClientID string
@ -46,7 +46,7 @@ type Config struct {
// ClientSecret is the application's secret. // ClientSecret is the application's secret.
ClientSecret string ClientSecret string
// Endpoint contains the resource server's token endpoint // Endpoint contains the authorization server's token endpoint
// URLs. These are constants specific to each server and are // URLs. These are constants specific to each server and are
// often available via site-specific packages, such as // often available via site-specific packages, such as
// google.Endpoint or github.Endpoint. // google.Endpoint or github.Endpoint.
@ -135,7 +135,7 @@ type setParam struct{ k, v string }
func (p setParam) setValue(m url.Values) { m.Set(p.k, p.v) } func (p setParam) setValue(m url.Values) { m.Set(p.k, p.v) }
// SetAuthURLParam builds an AuthCodeOption which passes key/value parameters // SetAuthURLParam builds an [AuthCodeOption] which passes key/value parameters
// to a provider's authorization endpoint. // to a provider's authorization endpoint.
func SetAuthURLParam(key, value string) AuthCodeOption { func SetAuthURLParam(key, value string) AuthCodeOption {
return setParam{key, value} return setParam{key, value}
@ -148,8 +148,8 @@ func SetAuthURLParam(key, value string) AuthCodeOption {
// request and callback. The authorization server includes this value when // request and callback. The authorization server includes this value when
// redirecting the user agent back to the client. // redirecting the user agent back to the client.
// //
// Opts may include AccessTypeOnline or AccessTypeOffline, as well // Opts may include [AccessTypeOnline] or [AccessTypeOffline], as well
// as ApprovalForce. // as [ApprovalForce].
// //
// To protect against CSRF attacks, opts should include a PKCE challenge // To protect against CSRF attacks, opts should include a PKCE challenge
// (S256ChallengeOption). Not all servers support PKCE. An alternative is to // (S256ChallengeOption). Not all servers support PKCE. An alternative is to
@ -194,7 +194,7 @@ func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string {
// and when other authorization grant types are not available." // and when other authorization grant types are not available."
// See https://tools.ietf.org/html/rfc6749#section-4.3 for more info. // See https://tools.ietf.org/html/rfc6749#section-4.3 for more info.
// //
// The provided context optionally controls which HTTP client is used. See the HTTPClient variable. // The provided context optionally controls which HTTP client is used. See the [HTTPClient] variable.
func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) { func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) {
v := url.Values{ v := url.Values{
"grant_type": {"password"}, "grant_type": {"password"},
@ -212,10 +212,10 @@ func (c *Config) PasswordCredentialsToken(ctx context.Context, username, passwor
// It is used after a resource provider redirects the user back // It is used after a resource provider redirects the user back
// to the Redirect URI (the URL obtained from AuthCodeURL). // to the Redirect URI (the URL obtained from AuthCodeURL).
// //
// The provided context optionally controls which HTTP client is used. See the HTTPClient variable. // The provided context optionally controls which HTTP client is used. See the [HTTPClient] variable.
// //
// The code will be in the *http.Request.FormValue("code"). Before // The code will be in the [http.Request.FormValue]("code"). Before
// calling Exchange, be sure to validate FormValue("state") if you are // calling Exchange, be sure to validate [http.Request.FormValue]("state") if you are
// using it to protect against CSRF attacks. // using it to protect against CSRF attacks.
// //
// If using PKCE to protect against CSRF attacks, opts should include a // If using PKCE to protect against CSRF attacks, opts should include a
@ -242,10 +242,10 @@ func (c *Config) Client(ctx context.Context, t *Token) *http.Client {
return NewClient(ctx, c.TokenSource(ctx, t)) return NewClient(ctx, c.TokenSource(ctx, t))
} }
// TokenSource returns a TokenSource that returns t until t expires, // TokenSource returns a [TokenSource] that returns t until t expires,
// automatically refreshing it as necessary using the provided context. // automatically refreshing it as necessary using the provided context.
// //
// Most users will use Config.Client instead. // Most users will use [Config.Client] instead.
func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource { func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource {
tkr := &tokenRefresher{ tkr := &tokenRefresher{
ctx: ctx, ctx: ctx,
@ -260,7 +260,7 @@ func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource {
} }
} }
// tokenRefresher is a TokenSource that makes "grant_type"=="refresh_token" // tokenRefresher is a TokenSource that makes "grant_type=refresh_token"
// HTTP requests to renew a token using a RefreshToken. // HTTP requests to renew a token using a RefreshToken.
type tokenRefresher struct { type tokenRefresher struct {
ctx context.Context // used to get HTTP requests ctx context.Context // used to get HTTP requests
@ -305,8 +305,7 @@ type reuseTokenSource struct {
} }
// Token returns the current token if it's still valid, else will // Token returns the current token if it's still valid, else will
// refresh the current token (using r.Context for HTTP client // refresh the current token and return the new one.
// information) and return the new one.
func (s *reuseTokenSource) Token() (*Token, error) { func (s *reuseTokenSource) Token() (*Token, error) {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
@ -322,7 +321,7 @@ func (s *reuseTokenSource) Token() (*Token, error) {
return t, nil return t, nil
} }
// StaticTokenSource returns a TokenSource that always returns the same token. // StaticTokenSource returns a [TokenSource] that always returns the same token.
// Because the provided token t is never refreshed, StaticTokenSource is only // Because the provided token t is never refreshed, StaticTokenSource is only
// useful for tokens that never expire. // useful for tokens that never expire.
func StaticTokenSource(t *Token) TokenSource { func StaticTokenSource(t *Token) TokenSource {
@ -338,16 +337,16 @@ func (s staticTokenSource) Token() (*Token, error) {
return s.t, nil return s.t, nil
} }
// HTTPClient is the context key to use with golang.org/x/net/context's // HTTPClient is the context key to use with [context.WithValue]
// WithValue function to associate an *http.Client value with a context. // to associate a [*http.Client] value with a context.
var HTTPClient internal.ContextKey var HTTPClient internal.ContextKey
// NewClient creates an *http.Client from a Context and TokenSource. // NewClient creates an [*http.Client] from a [context.Context] and [TokenSource].
// The returned client is not valid beyond the lifetime of the context. // The returned client is not valid beyond the lifetime of the context.
// //
// Note that if a custom *http.Client is provided via the Context it // Note that if a custom [*http.Client] is provided via the [context.Context] it
// is used only for token acquisition and is not used to configure the // is used only for token acquisition and is not used to configure the
// *http.Client returned from NewClient. // [*http.Client] returned from NewClient.
// //
// As a special case, if src is nil, a non-OAuth2 client is returned // As a special case, if src is nil, a non-OAuth2 client is returned
// using the provided context. This exists to support related OAuth2 // using the provided context. This exists to support related OAuth2
@ -368,7 +367,7 @@ func NewClient(ctx context.Context, src TokenSource) *http.Client {
} }
} }
// ReuseTokenSource returns a TokenSource which repeatedly returns the // ReuseTokenSource returns a [TokenSource] which repeatedly returns the
// same token as long as it's valid, starting with t. // same token as long as it's valid, starting with t.
// When its cached token is invalid, a new token is obtained from src. // When its cached token is invalid, a new token is obtained from src.
// //
@ -376,10 +375,10 @@ func NewClient(ctx context.Context, src TokenSource) *http.Client {
// (such as a file on disk) between runs of a program, rather than // (such as a file on disk) between runs of a program, rather than
// obtaining new tokens unnecessarily. // obtaining new tokens unnecessarily.
// //
// The initial token t may be nil, in which case the TokenSource is // The initial token t may be nil, in which case the [TokenSource] is
// wrapped in a caching version if it isn't one already. This also // wrapped in a caching version if it isn't one already. This also
// means it's always safe to wrap ReuseTokenSource around any other // means it's always safe to wrap ReuseTokenSource around any other
// TokenSource without adverse effects. // [TokenSource] without adverse effects.
func ReuseTokenSource(t *Token, src TokenSource) TokenSource { func ReuseTokenSource(t *Token, src TokenSource) TokenSource {
// Don't wrap a reuseTokenSource in itself. That would work, // Don't wrap a reuseTokenSource in itself. That would work,
// but cause an unnecessary number of mutex operations. // but cause an unnecessary number of mutex operations.
@ -397,8 +396,8 @@ func ReuseTokenSource(t *Token, src TokenSource) TokenSource {
} }
} }
// ReuseTokenSourceWithExpiry returns a TokenSource that acts in the same manner as the // ReuseTokenSourceWithExpiry returns a [TokenSource] that acts in the same manner as the
// TokenSource returned by ReuseTokenSource, except the expiry buffer is // [TokenSource] returned by [ReuseTokenSource], except the expiry buffer is
// configurable. The expiration time of a token is calculated as // configurable. The expiration time of a token is calculated as
// t.Expiry.Add(-earlyExpiry). // t.Expiry.Add(-earlyExpiry).
func ReuseTokenSourceWithExpiry(t *Token, src TokenSource, earlyExpiry time.Duration) TokenSource { func ReuseTokenSourceWithExpiry(t *Token, src TokenSource, earlyExpiry time.Duration) TokenSource {

View File

@ -1,6 +1,7 @@
// Copyright 2023 The Go Authors. All rights reserved. // Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package oauth2 package oauth2
import ( import (
@ -20,9 +21,9 @@ const (
// This follows recommendations in RFC 7636. // This follows recommendations in RFC 7636.
// //
// A fresh verifier should be generated for each authorization. // A fresh verifier should be generated for each authorization.
// S256ChallengeOption(verifier) should then be passed to Config.AuthCodeURL // The resulting verifier should be passed to [Config.AuthCodeURL] or [Config.DeviceAuth]
// (or Config.DeviceAuth) and VerifierOption(verifier) to Config.Exchange // with [S256ChallengeOption], and to [Config.Exchange] or [Config.DeviceAccessToken]
// (or Config.DeviceAccessToken). // with [VerifierOption].
func GenerateVerifier() string { func GenerateVerifier() string {
// "RECOMMENDED that the output of a suitable random number generator be // "RECOMMENDED that the output of a suitable random number generator be
// used to create a 32-octet sequence. The octet sequence is then // used to create a 32-octet sequence. The octet sequence is then
@ -36,22 +37,22 @@ func GenerateVerifier() string {
return base64.RawURLEncoding.EncodeToString(data) return base64.RawURLEncoding.EncodeToString(data)
} }
// VerifierOption returns a PKCE code verifier AuthCodeOption. It should be // VerifierOption returns a PKCE code verifier [AuthCodeOption]. It should only be
// passed to Config.Exchange or Config.DeviceAccessToken only. // passed to [Config.Exchange] or [Config.DeviceAccessToken].
func VerifierOption(verifier string) AuthCodeOption { func VerifierOption(verifier string) AuthCodeOption {
return setParam{k: codeVerifierKey, v: verifier} return setParam{k: codeVerifierKey, v: verifier}
} }
// S256ChallengeFromVerifier returns a PKCE code challenge derived from verifier with method S256. // S256ChallengeFromVerifier returns a PKCE code challenge derived from verifier with method S256.
// //
// Prefer to use S256ChallengeOption where possible. // Prefer to use [S256ChallengeOption] where possible.
func S256ChallengeFromVerifier(verifier string) string { func S256ChallengeFromVerifier(verifier string) string {
sha := sha256.Sum256([]byte(verifier)) sha := sha256.Sum256([]byte(verifier))
return base64.RawURLEncoding.EncodeToString(sha[:]) return base64.RawURLEncoding.EncodeToString(sha[:])
} }
// S256ChallengeOption derives a PKCE code challenge derived from verifier with // S256ChallengeOption derives a PKCE code challenge derived from verifier with
// method S256. It should be passed to Config.AuthCodeURL or Config.DeviceAuth // method S256. It should be passed to [Config.AuthCodeURL] or [Config.DeviceAuth]
// only. // only.
func S256ChallengeOption(verifier string) AuthCodeOption { func S256ChallengeOption(verifier string) AuthCodeOption {
return challengeOption{ return challengeOption{

View File

@ -44,7 +44,7 @@ type Token struct {
// Expiry is the optional expiration time of the access token. // Expiry is the optional expiration time of the access token.
// //
// If zero, TokenSource implementations will reuse the same // If zero, [TokenSource] implementations will reuse the same
// token forever and RefreshToken or equivalent // token forever and RefreshToken or equivalent
// mechanisms for that TokenSource will not be used. // mechanisms for that TokenSource will not be used.
Expiry time.Time `json:"expiry,omitempty"` Expiry time.Time `json:"expiry,omitempty"`
@ -58,7 +58,7 @@ type Token struct {
// raw optionally contains extra metadata from the server // raw optionally contains extra metadata from the server
// when updating a token. // when updating a token.
raw interface{} raw any
// expiryDelta is used to calculate when a token is considered // expiryDelta is used to calculate when a token is considered
// expired, by subtracting from Expiry. If zero, defaultExpiryDelta // expired, by subtracting from Expiry. If zero, defaultExpiryDelta
@ -86,16 +86,16 @@ func (t *Token) Type() string {
// SetAuthHeader sets the Authorization header to r using the access // SetAuthHeader sets the Authorization header to r using the access
// token in t. // token in t.
// //
// This method is unnecessary when using Transport or an HTTP Client // This method is unnecessary when using [Transport] or an HTTP Client
// returned by this package. // returned by this package.
func (t *Token) SetAuthHeader(r *http.Request) { func (t *Token) SetAuthHeader(r *http.Request) {
r.Header.Set("Authorization", t.Type()+" "+t.AccessToken) r.Header.Set("Authorization", t.Type()+" "+t.AccessToken)
} }
// WithExtra returns a new Token that's a clone of t, but using the // WithExtra returns a new [Token] that's a clone of t, but using the
// provided raw extra map. This is only intended for use by packages // provided raw extra map. This is only intended for use by packages
// implementing derivative OAuth2 flows. // implementing derivative OAuth2 flows.
func (t *Token) WithExtra(extra interface{}) *Token { func (t *Token) WithExtra(extra any) *Token {
t2 := new(Token) t2 := new(Token)
*t2 = *t *t2 = *t
t2.raw = extra t2.raw = extra
@ -105,8 +105,8 @@ func (t *Token) WithExtra(extra interface{}) *Token {
// Extra returns an extra field. // Extra returns an extra field.
// Extra fields are key-value pairs returned by the server as a // Extra fields are key-value pairs returned by the server as a
// part of the token retrieval response. // part of the token retrieval response.
func (t *Token) Extra(key string) interface{} { func (t *Token) Extra(key string) any {
if raw, ok := t.raw.(map[string]interface{}); ok { if raw, ok := t.raw.(map[string]any); ok {
return raw[key] return raw[key]
} }
@ -163,6 +163,7 @@ func tokenFromInternal(t *internal.Token) *Token {
TokenType: t.TokenType, TokenType: t.TokenType,
RefreshToken: t.RefreshToken, RefreshToken: t.RefreshToken,
Expiry: t.Expiry, Expiry: t.Expiry,
ExpiresIn: t.ExpiresIn,
raw: t.Raw, raw: t.Raw,
} }
} }

View File

@ -11,12 +11,12 @@ import (
"sync" "sync"
) )
// Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests, // Transport is an [http.RoundTripper] that makes OAuth 2.0 HTTP requests,
// wrapping a base RoundTripper and adding an Authorization header // wrapping a base [http.RoundTripper] and adding an Authorization header
// with a token from the supplied Sources. // with a token from the supplied [TokenSource].
// //
// Transport is a low-level mechanism. Most code will use the // Transport is a low-level mechanism. Most code will use the
// higher-level Config.Client method instead. // higher-level [Config.Client] method instead.
type Transport struct { type Transport struct {
// Source supplies the token to add to outgoing requests' // Source supplies the token to add to outgoing requests'
// Authorization headers. // Authorization headers.
@ -47,7 +47,7 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
return nil, err return nil, err
} }
req2 := cloneRequest(req) // per RoundTripper contract req2 := req.Clone(req.Context())
token.SetAuthHeader(req2) token.SetAuthHeader(req2)
// req.Body is assumed to be closed by the base RoundTripper. // req.Body is assumed to be closed by the base RoundTripper.
@ -73,17 +73,3 @@ func (t *Transport) base() http.RoundTripper {
} }
return http.DefaultTransport return http.DefaultTransport
} }
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request) *http.Request {
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *r
// deep copy of the Header
r2.Header = make(http.Header, len(r.Header))
for k, s := range r.Header {
r2.Header[k] = append([]string(nil), s...)
}
return r2
}

View File

@ -4,7 +4,7 @@ github.com/google/go-github/github
# github.com/google/go-querystring v1.1.0 # github.com/google/go-querystring v1.1.0
## explicit; go 1.10 ## explicit; go 1.10
github.com/google/go-querystring/query github.com/google/go-querystring/query
# golang.org/x/oauth2 v0.29.0 # golang.org/x/oauth2 v0.30.0
## explicit; go 1.23.0 ## explicit; go 1.23.0
golang.org/x/oauth2 golang.org/x/oauth2
golang.org/x/oauth2/internal golang.org/x/oauth2/internal