Files
coder/coderd/oauth2provider/tokens.go
T
Bobby Ho 1818844069 fix: ignore unrecognized parameters at the token endpoint (#29139)
fix(oauth2): ignore unrecognized token request parameters

Align `/oauth2/tokens` with OAuth 2.1 §3.2 and `/oauth2/authorize` by ignoring unknown parameters and logging only their names at debug level, never values. Continue rejecting duplicate known parameters, with tests covering all nine and shared unknown-parameter inputs across both endpoints. Misspelled optional parameters are now ignored rather than returning 400. Changes are limited to `coderd/oauth2provider`, with no new endpoints or schema changes.

Closes https://linear.app/codercom/issue/PLAT-577
2026-09-09 11:42:57 -07:00

806 lines
31 KiB
Go

package oauth2provider
import (
"context"
"database/sql"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strings"
"time"
"github.com/google/uuid"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/apikey"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
)
var (
// errBadSecret means the user provided a bad secret.
errBadSecret = xerrors.New("Invalid client secret")
// errBadCode means the user provided a bad code.
errBadCode = xerrors.New("Invalid code")
// errBadToken means the user provided a bad token.
errBadToken = xerrors.New("Invalid token")
// errInvalidPKCE means the PKCE verification failed.
errInvalidPKCE = xerrors.New("invalid code_verifier")
// errInvalidResource means the resource parameter validation failed.
errInvalidResource = xerrors.New("invalid resource parameter")
// errConflictingClientAuth means the client provided credentials in both the
// request body and HTTP Basic, but they did not match.
errConflictingClientAuth = xerrors.New("conflicting client authentication")
// errUnmintableScope means the scope stored on a grant names something no
// API key can be minted from.
errUnmintableScope = xerrors.New("scope is not a valid API key scope")
// errStaleScope means the app's registered scopes narrowed after the code
// was issued and no longer cover the code's scope.
errStaleScope = xerrors.New("scope is no longer allowed by this app's registered scopes; authorize again to obtain a code within the current scopes")
// errScopeNotGranted means a request asked for more than the resource owner
// granted. The ceiling is the grant itself rather than the app's allowlist,
// and nothing but a new authorization raises it, so the message says so.
errScopeNotGranted = xerrors.New("scope requests permissions beyond the scope originally granted; a refresh cannot widen a grant, so authorize again to obtain a broader one")
)
// checkScopeStillCovered rechecks a grant's scope against the app's registered
// scopes as they stand now, which can change during a code's ten minute life.
// Only the client can change them, through its RFC 7592 registration.
//
// Refresh deliberately does not call this. A narrowed registration is applied
// at the next authorization rather than mid-session, so tightening an app's
// scopes does not break integrations that are already running.
func checkScopeStillCovered(ctx context.Context, logger slog.Logger, app database.OAuth2ProviderApp, granted string) error {
if noScopeAllowlist(app.Scope) {
return nil
}
allowlist := grantableScopes(app.Scope.String)
if len(allowlist) == 0 {
logger.Warn(ctx, "oauth2 code redemption refused: no registered scope is grantable",
slog.F("app_id", app.ID.String()))
return errNoGrantableScope
}
// Canonicalized because the row may have been written by an older server.
outside, err := firstScopeBeyondCeiling(ctx, logger, phaseRedeem, app.ID, allowlist, canonicalScopes(strings.Fields(granted)))
if err != nil {
return err
}
if outside != "" {
logger.Warn(ctx, "oauth2 code redemption refused by the app's registered scopes",
slog.F("app_id", app.ID.String()),
slog.F("allowlist", strings.Join(allowlist, " ")),
slog.F("scope", outside))
return xerrors.Errorf("'%s': %w", outside, errStaleScope)
}
return nil
}
// narrowAccessScope returns the scope for the access token this request mints.
// A request may ask for part of the grant but never more (RFC 6749 §6), and a
// request naming no scope gets the whole grant. The grant itself is unchanged,
// so a later request may ask for a different part of it.
func narrowAccessScope(ctx context.Context, logger slog.Logger, phase string, appID uuid.UUID, granted string, requested []string) (string, error) {
// The row may have been written by an older server.
ceiling := canonicalScopes(strings.Fields(granted))
// Before the comparison, so a stored name this deployment dropped is named
// in a 400 rather than failing to expand into a 500.
if _, err := scopeStringToAPIKeyScopes(strings.Join(ceiling, " ")); err != nil {
return "", err
}
if len(requested) == 0 {
return strings.Join(ceiling, " "), nil
}
// First, so a typo reads as an unknown scope rather than as a coverage
// check RBAC could not decide.
if unknown, ok := firstUnknownScope(requested); ok {
logger.Warn(ctx, "oauth2 token request refused: scope outside the catalog",
slog.F("phase", phase),
slog.F("app_id", appID.String()),
slog.F("scope", unknown))
return "", xerrors.Errorf("'%s': %w", unknown, errUnknownScope)
}
narrowed := canonicalScopes(requested)
outside, err := firstScopeBeyondCeiling(ctx, logger, phase, appID, ceiling, narrowed)
if err != nil {
return "", err
}
if outside != "" {
// Logged like every other scope refusal in this package: without it a
// leaked token being probed for what it can be traded up to looks the
// same as an ordinary client error.
logger.Warn(ctx, "oauth2 token request refused: scope beyond the grant",
slog.F("phase", phase),
slog.F("app_id", appID.String()),
slog.F("granted", granted),
slog.F("scope", outside))
return "", xerrors.Errorf("'%s': %w", outside, errScopeNotGranted)
}
return strings.Join(narrowed, " "), nil
}
// scopeStringToAPIKeyScopes converts a grant's stored scope into the scope list
// an API key is minted with. Names are checked here, not in apikey.Generate,
// whose error would surface as a 500. An empty list is an error rather than an
// unrestricted key.
func scopeStringToAPIKeyScopes(scope string) (database.APIKeyScopes, error) {
names := strings.Fields(scope)
if len(names) == 0 {
return nil, xerrors.Errorf("'%s': %w", scope, errUnmintableScope)
}
scopes := make(database.APIKeyScopes, 0, len(names))
for _, name := range names {
s := database.APIKeyScope(name)
if !s.Valid() {
return nil, xerrors.Errorf("'%s': %w", name, errUnmintableScope)
}
scopes = append(scopes, s)
}
return scopes, nil
}
// extractTokenRequest parses and validates the /oauth2/tokens form. It takes
// the app because whether client_secret is required depends on the client
// type.
func extractTokenRequest(r *http.Request, logger slog.Logger, primary *url.URL, alternates []*url.URL, app database.OAuth2ProviderApp) (codersdk.OAuth2TokenRequest, []codersdk.ValidationError, error) {
p := httpapi.NewQueryParamParser()
err := r.ParseForm()
if err != nil {
return codersdk.OAuth2TokenRequest{}, nil, xerrors.Errorf("parse form: %w", err)
}
vals := r.Form
p.RequiredNotEmpty("grant_type")
grantType := httpapi.ParseCustom(p, vals, "", "grant_type", httpapi.ParseEnum[codersdk.OAuth2ProviderGrantType])
// Grant-type specific validation - must be called before parsing values.
switch grantType {
case codersdk.OAuth2ProviderGrantTypeRefreshToken:
p.RequiredNotEmpty("refresh_token")
case codersdk.OAuth2ProviderGrantTypeAuthorizationCode:
p.RequiredNotEmpty("code")
}
req := codersdk.OAuth2TokenRequest{
GrantType: grantType,
ClientID: p.String(vals, "", "client_id"),
ClientSecret: p.String(vals, "", "client_secret"),
Code: p.String(vals, "", "code"),
RedirectURI: p.String(vals, "", "redirect_uri"),
RefreshToken: p.String(vals, "", "refresh_token"),
CodeVerifier: p.String(vals, "", "code_verifier"),
Resource: p.String(vals, "", "resource"),
Scope: p.String(vals, "", "scope"),
}
// RFC 6749 §2.3.1: confidential clients may authenticate via HTTP Basic.
if user, pass, ok := r.BasicAuth(); ok && user != "" {
if req.ClientID != "" && req.ClientID != user {
return codersdk.OAuth2TokenRequest{}, nil, errConflictingClientAuth
}
if req.ClientSecret != "" && req.ClientSecret != pass {
return codersdk.OAuth2TokenRequest{}, nil, errConflictingClientAuth
}
req.ClientID = user
req.ClientSecret = pass
}
// Grant-specific required checks that can be satisfied via HTTP Basic.
if req.GrantType == codersdk.OAuth2ProviderGrantTypeAuthorizationCode {
if req.ClientID == "" {
p.Errors = append(p.Errors, codersdk.ValidationError{
Field: "client_id",
Detail: "Parameter \"client_id\" is required and cannot be empty",
})
}
// Public clients have no secret; PKCE is their proof of possession
// (RFC 7591 §2, OAuth 2.1 §2.1).
if !app.IsPublic() && req.ClientSecret == "" {
p.Errors = append(p.Errors, codersdk.ValidationError{
Field: "client_secret",
Detail: "Parameter \"client_secret\" is required and cannot be empty",
})
}
// A code_verifier outside RFC 7636 §4.1's bounds is a syntax error
// (RFC 6749 §5.2), distinct from a well-formed verifier that fails the
// PKCE hash comparison in authorizationCodeGrant, which RFC 7636 §4.6
// maps to invalid_grant instead. Checking it here, alongside the other
// syntax validation, keeps the two failure modes distinguishable.
if !ValidPKCEFormat(req.CodeVerifier) {
p.Errors = append(p.Errors, codersdk.ValidationError{
Field: "code_verifier",
Detail: "must be 43 to 128 characters from the unreserved character set [A-Za-z0-9-._~] (RFC 7636 §4.1)",
})
}
}
// Validate redirect URI - errors are added to p.Errors.
_ = p.RedirectURL(vals, primary, alternates, "redirect_uri")
// Validate resource parameter syntax (RFC 8707): must be absolute URI without fragment.
if err := validateResourceParameter(req.Resource); err != nil {
p.Errors = append(p.Errors, codersdk.ValidationError{
Field: "resource",
Detail: "must be an absolute URI without fragment",
})
}
// RFC 6749 §3.2 and OAuth 2.1 §3.2: unrecognized parameters MUST be ignored,
// so a client_assertion or a DPoP parameter is not this endpoint's business.
// Repeats of the parameters read above are still rejected, by parseSingle.
if ignored := ignoredParams(p, vals); len(ignored) > 0 {
logger.Debug(r.Context(), "ignoring unrecognized token parameters",
slog.F("params", ignored))
}
if len(p.Errors) > 0 {
return codersdk.OAuth2TokenRequest{}, p.Errors, xerrors.Errorf("invalid query params: %w", p.Errors)
}
return req, nil, nil
}
// writeTokenError renders an RFC 6749 §5.2 error body. Descriptions can quote
// what the client sent, so they are confined and capped here rather than at each
// call site, leaving the guarantee with the endpoint.
func writeTokenError(ctx context.Context, rw http.ResponseWriter, status int, code codersdk.OAuth2ErrorCode, description string) {
// Sanitized before the cap, so the bound is on what the client receives.
httpapi.WriteOAuth2Error(ctx, rw, status, code, capErrorDescription(sanitizeErrorDescription(description)))
}
// Tokens
// Uses Sessions.DefaultDuration for access token (API key) TTL and
// Sessions.RefreshDefaultDuration for refresh token TTL.
func Tokens(db database.Store, lifetimes codersdk.SessionLifetime, logger slog.Logger) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
app := httpmw.OAuth2ProviderApp(r)
primary, alternates, err := registeredRedirectURIs(app)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to validate form values.",
Detail: err.Error(),
})
return
}
req, validationErrs, err := extractTokenRequest(r, logger, primary, alternates, app)
if err != nil {
if errors.Is(err, errConflictingClientAuth) {
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidRequest, "Conflicting client credentials between Authorization header and request body")
return
}
// Check for specific validation errors in priority order
if slices.ContainsFunc(validationErrs, func(validationError codersdk.ValidationError) bool {
return validationError.Field == "grant_type"
}) {
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeUnsupportedGrantType, "The grant type is missing or unsupported")
return
}
// Check for missing required parameters for authorization_code grant
for _, field := range []string{"code", "client_id", "client_secret"} {
if slices.ContainsFunc(validationErrs, func(validationError codersdk.ValidationError) bool {
return validationError.Field == field
}) {
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidRequest, fmt.Sprintf("Missing required parameter: %s", field))
return
}
}
// A malformed code_verifier gets its own message so a client that
// sent a well-formed but wrong verifier (rejected later, as
// invalid_grant, by the PKCE hash comparison) can tell the two
// failures apart instead of retrying the same bad verifier forever.
if slices.ContainsFunc(validationErrs, func(validationError codersdk.ValidationError) bool {
return validationError.Field == "code_verifier"
}) {
// Spelled out: §5.2 excludes the section sign.
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidRequest, "The code_verifier parameter must be 43 to 128 characters from the unreserved character set [A-Za-z0-9-._~] (RFC 7636 section 4.1)")
return
}
// Generic invalid request for other validation errors
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidRequest, "The request is missing required parameters or is otherwise malformed")
return
}
var token codersdk.OAuth2TokenResponse
//nolint:gocritic,revive // More cases will be added later.
switch req.GrantType {
// TODO: Client creds, device code.
case codersdk.OAuth2ProviderGrantTypeRefreshToken:
token, err = refreshTokenGrant(ctx, db, logger, app, lifetimes, req)
case codersdk.OAuth2ProviderGrantTypeAuthorizationCode:
token, err = authorizationCodeGrant(ctx, db, logger, app, lifetimes, req)
default:
// This should handle truly invalid grant types
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeUnsupportedGrantType, fmt.Sprintf("The grant type %q is not supported", req.GrantType))
return
}
if errors.Is(err, errBadSecret) {
writeTokenError(ctx, rw, http.StatusUnauthorized, codersdk.OAuth2ErrorCodeInvalidClient, "The client credentials are invalid")
return
}
if errors.Is(err, errBadCode) {
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidGrant, "The authorization code is invalid or expired")
return
}
if errors.Is(err, errInvalidPKCE) {
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidGrant, "The PKCE code verifier is invalid")
return
}
if errors.Is(err, errInvalidResource) {
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidTarget, "The resource parameter is invalid")
return
}
if errors.Is(err, errBadToken) {
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidGrant, "The refresh token is invalid or expired")
return
}
// invalid_grant, not invalid_scope (RFC 6749 §5.2): all three report a
// problem with the stored grant, which the client cannot fix by asking
// differently. That includes errUnmintableScope: the catalog check runs
// first and every catalog name is mintable, so a requested scope never
// reaches it.
if errors.Is(err, errUnmintableScope) || errors.Is(err, errStaleScope) ||
errors.Is(err, errNoGrantableScope) {
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidGrant, err.Error())
return
}
// invalid_scope for these: the refresh named them itself, so the
// client can fix it by asking differently.
if errors.Is(err, errUnknownScope) || errors.Is(err, errScopeNotGranted) {
writeTokenError(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidScope, err.Error())
return
}
if errors.Is(err, errCoverageUndecidable) {
writeTokenError(ctx, rw, http.StatusInternalServerError, codersdk.OAuth2ErrorCodeServerError, "The requested scope could not be evaluated")
return
}
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to exchange token",
Detail: err.Error(),
})
return
}
// Some client libraries allow this to be "application/x-www-form-urlencoded". We can implement that upon
// request. The same libraries should also accept JSON. If implemented, choose based on "Accept" header.
httpapi.Write(ctx, rw, http.StatusOK, token)
}
}
// revokeOAuth2CodeOnPKCEFailure deletes a code that failed PKCE verification so
// it cannot be replayed with further code_verifier guesses (RFC 6749 §10.5).
//
// A failed delete is logged on the request's log line rather than returned: a
// distinct error would tell a caller whether its code is still redeemable.
// sql.ErrNoRows is not logged, since a code that is already gone satisfies the
// goal.
//
// The delete uses a context detached from the request, which is canceled when
// the client disconnects. Otherwise a caller could fail PKCE, drop the
// connection, and keep its code redeemable.
func revokeOAuth2CodeOnPKCEFailure(ctx context.Context, db database.Store, codeID uuid.UUID) {
revokeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
//nolint:gocritic // OAuth2 system context, no authenticated user during token exchange
if _, err := db.DeleteOAuth2ProviderAppCodeByID(dbauthz.AsSystemOAuth2(revokeCtx), codeID); err != nil && !errors.Is(err, sql.ErrNoRows) {
if rlogger := loggermw.RequestLoggerFromContext(ctx); rlogger != nil {
rlogger.WithFields(slog.F("oauth2_pkce_failure_code_revoke_error", err.Error()))
}
}
}
func authorizationCodeGrant(ctx context.Context, db database.Store, logger slog.Logger, app database.OAuth2ProviderApp, lifetimes codersdk.SessionLifetime, req codersdk.OAuth2TokenRequest) (codersdk.OAuth2TokenResponse, error) {
// A public client has no secret to validate, and its token references
// none. PKCE and the dbCode.AppID check are what bind the exchange to the
// client instead.
var appSecretID uuid.NullUUID
if !app.IsPublic() {
secret, err := ParseFormattedSecret(req.ClientSecret)
if err != nil {
return codersdk.OAuth2TokenResponse{}, errBadSecret
}
//nolint:gocritic // OAuth2 system context, users cannot read secrets
dbSecret, err := db.GetOAuth2ProviderAppSecretByPrefix(dbauthz.AsSystemOAuth2(ctx), []byte(secret.Prefix))
if errors.Is(err, sql.ErrNoRows) {
return codersdk.OAuth2TokenResponse{}, errBadSecret
}
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
equalSecret := apikey.ValidateHash(dbSecret.HashedSecret, secret.Secret)
if !equalSecret {
return codersdk.OAuth2TokenResponse{}, errBadSecret
}
// The secret must belong to the app named by client_id, which arrives
// unverified in the request. Otherwise a valid secret for one app
// could issue a token for another.
if dbSecret.AppID != app.ID {
return codersdk.OAuth2TokenResponse{}, errBadSecret
}
appSecretID = uuid.NullUUID{UUID: dbSecret.ID, Valid: true}
}
// Validate the authorization code.
code, err := ParseFormattedSecret(req.Code)
if err != nil {
return codersdk.OAuth2TokenResponse{}, errBadCode
}
//nolint:gocritic // OAuth2 system context, no authenticated user during token exchange
dbCode, err := db.GetOAuth2ProviderAppCodeByPrefix(dbauthz.AsSystemOAuth2(ctx), []byte(code.Prefix))
if errors.Is(err, sql.ErrNoRows) {
return codersdk.OAuth2TokenResponse{}, errBadCode
}
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
equalCode := apikey.ValidateHash(dbCode.HashedSecret, code.Secret)
if !equalCode {
return codersdk.OAuth2TokenResponse{}, errBadCode
}
// Likewise the code must belong to the app named by client_id. A public
// client runs no secret check, so this is the only thing tying the
// exchange to that app.
if dbCode.AppID != app.ID {
return codersdk.OAuth2TokenResponse{}, errBadCode
}
// Ensure the code has not expired.
if dbCode.ExpiresAt.Before(dbtime.Now()) {
return codersdk.OAuth2TokenResponse{}, errBadCode
}
// Verify redirect_uri matches the one used during authorization
// (RFC 6749 §4.1.3).
if dbCode.RedirectUri.Valid && dbCode.RedirectUri.String != "" {
if req.RedirectURI != dbCode.RedirectUri.String {
return codersdk.OAuth2TokenResponse{}, errBadCode
}
}
// PKCE is mandatory for all authorization code flows (OAuth 2.1).
// extractTokenRequest already rejected a malformed verifier as
// invalid_request, so a mismatch here is a wrong but well-formed verifier,
// RFC 7636 §4.6's invalid_grant case.
//
// The code is revoked on failure because RFC 6749 §10.5 requires codes to be
// single-use: one that survived would let a leaked code be replayed with
// unthrottled verifier guesses.
if !dbCode.CodeChallenge.Valid || dbCode.CodeChallenge.String == "" {
// The authorize endpoint requires a challenge, so this is defense in
// depth.
revokeOAuth2CodeOnPKCEFailure(ctx, db, dbCode.ID)
return codersdk.OAuth2TokenResponse{}, errInvalidPKCE
}
if !VerifyPKCE(dbCode.CodeChallenge.String, req.CodeVerifier) {
revokeOAuth2CodeOnPKCEFailure(ctx, db, dbCode.ID)
return codersdk.OAuth2TokenResponse{}, errInvalidPKCE
}
// Verify resource parameter consistency (RFC 8707)
if dbCode.ResourceUri.Valid && dbCode.ResourceUri.String != "" {
// Resource was specified during authorization - it must match in token request
if req.Resource == "" {
return codersdk.OAuth2TokenResponse{}, errInvalidResource
}
if req.Resource != dbCode.ResourceUri.String {
return codersdk.OAuth2TokenResponse{}, errInvalidResource
}
} else if req.Resource != "" {
// Resource was not specified during authorization but is now provided
return codersdk.OAuth2TokenResponse{}, errInvalidResource
}
// Before the allowlist check: RBAC cannot expand a name that is not a real
// scope, so that check would answer "could not be determined" rather than
// naming the stored scope to fix.
if _, err := scopeStringToAPIKeyScopes(dbCode.Scope); err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
if err := checkScopeStillCovered(ctx, logger, app, dbCode.Scope); err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
// An exchange may narrow too. RFC 6749 §4.1.3 defines no scope parameter
// here, but the form carries one, and accepting it silently would hand back
// the broader token the client asked to give up.
accessScope, err := narrowAccessScope(ctx, logger, phaseRedeem, app.ID, dbCode.Scope, strings.Fields(req.Scope))
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
// apikey.Generate defaults to coder:all when this is empty.
scopes, err := scopeStringToAPIKeyScopes(accessScope)
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
// Generate a refresh token.
refreshToken, err := GenerateSecret()
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
// Generate the API key we will swap for the code.
tokenName := fmt.Sprintf("%s_%s_oauth_session_token", dbCode.UserID, app.ID)
key, sessionToken, err := apikey.Generate(apikey.CreateParams{
UserID: dbCode.UserID,
LoginType: database.LoginTypeOAuth2ProviderApp,
DefaultLifetime: lifetimes.DefaultDuration.Value(),
Scopes: scopes,
// For now, we allow only one token per app and user at a time.
TokenName: tokenName,
})
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
// Grab the user roles so we can perform the exchange as the user. ScopeAll
// because this actor writes the key: narrowing it to the granted scope would
// deny api_key:create. The issued token is bounded by api_keys.scopes.
actor, _, err := httpmw.UserRBACSubject(ctx, db, dbCode.UserID, rbac.ScopeAll)
if err != nil {
return codersdk.OAuth2TokenResponse{}, xerrors.Errorf("fetch user actor: %w", err)
}
// Do the actual token exchange in the database.
// Determine refresh token expiry independently from the access token.
refreshLifetime := lifetimes.RefreshDefaultDuration.Value()
if refreshLifetime == 0 {
refreshLifetime = lifetimes.DefaultDuration.Value()
}
refreshExpiresAt := dbtime.Now().Add(refreshLifetime)
err = db.InTx(func(tx database.Store) error {
ctx := dbauthz.As(ctx, actor)
// Spend the code. RFC 6749 §10.5 requires single use: a code that
// survived its own redemption could be replayed by anyone who
// intercepted it. Spending it inside the transaction ties it to the
// token, so a later failure leaves the code redeemable.
_, err := tx.DeleteOAuth2ProviderAppCodeByID(ctx, dbCode.ID)
if errors.Is(err, sql.ErrNoRows) {
return errBadCode
}
if err != nil {
return xerrors.Errorf("delete oauth2 app code: %w", err)
}
// Delete the previous key, if any.
prevKey, err := tx.GetAPIKeyByName(ctx, database.GetAPIKeyByNameParams{
UserID: dbCode.UserID,
TokenName: tokenName,
})
if err == nil {
err = tx.DeleteAPIKeyByID(ctx, prevKey.ID)
}
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return xerrors.Errorf("delete api key by name: %w", err)
}
newKey, err := tx.InsertAPIKey(ctx, key)
if err != nil {
return xerrors.Errorf("insert oauth2 access token: %w", err)
}
_, err = tx.InsertOAuth2ProviderAppToken(ctx, database.InsertOAuth2ProviderAppTokenParams{
ID: uuid.New(),
CreatedAt: dbtime.Now(),
ExpiresAt: refreshExpiresAt,
HashPrefix: []byte(refreshToken.Prefix),
RefreshHash: refreshToken.Hashed,
AppID: dbCode.AppID,
AppSecretID: appSecretID,
APIKeyID: newKey.ID,
UserID: dbCode.UserID,
Audience: dbCode.ResourceUri,
Scope: dbCode.Scope,
})
if err != nil {
return xerrors.Errorf("insert oauth2 refresh token: %w", err)
}
return nil
}, nil)
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
return codersdk.OAuth2TokenResponse{
AccessToken: sessionToken,
TokenType: codersdk.OAuth2TokenTypeBearer,
RefreshToken: refreshToken.Formatted,
ExpiresIn: int64(time.Until(key.ExpiresAt).Seconds()),
Scope: accessScope,
Expiry: &key.ExpiresAt,
}, nil
}
func refreshTokenGrant(ctx context.Context, db database.Store, logger slog.Logger, app database.OAuth2ProviderApp, lifetimes codersdk.SessionLifetime, req codersdk.OAuth2TokenRequest) (codersdk.OAuth2TokenResponse, error) {
// Validate the token.
token, err := ParseFormattedSecret(req.RefreshToken)
if err != nil {
return codersdk.OAuth2TokenResponse{}, errBadToken
}
//nolint:gocritic // OAuth2 system context, no authenticated user during refresh
dbToken, err := db.GetOAuth2ProviderAppTokenByPrefix(dbauthz.AsSystemOAuth2(ctx), []byte(token.Prefix))
if errors.Is(err, sql.ErrNoRows) {
return codersdk.OAuth2TokenResponse{}, errBadToken
}
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
equal := apikey.ValidateHash(dbToken.RefreshHash, token.Secret)
if !equal {
return codersdk.OAuth2TokenResponse{}, errBadToken
}
// The token must belong to the app identified by the request's
// client_id, which is otherwise unauthenticated at this point (it is
// parsed straight from the request with no verification). Without this
// check, a stolen refresh token could be refreshed under a different
// app's client_id, re-parenting the token's app_id and breaking the
// issuing app's ability to revoke it.
if dbToken.AppID != app.ID {
return codersdk.OAuth2TokenResponse{}, errBadToken
}
// Ensure the token has not expired.
if dbToken.ExpiresAt.Before(dbtime.Now()) {
return codersdk.OAuth2TokenResponse{}, errBadToken
}
// Verify resource parameter consistency for refresh tokens (RFC 8707)
if req.Resource != "" {
// If resource is provided in refresh request, it must match the original token's audience
if !dbToken.Audience.Valid || dbToken.Audience.String != req.Resource {
return codersdk.OAuth2TokenResponse{}, errInvalidResource
}
}
accessScope, err := narrowAccessScope(ctx, logger, phaseRefresh, app.ID, dbToken.Scope, strings.Fields(req.Scope))
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
// Grab the user roles so we can perform the refresh as the user.
//nolint:gocritic // OAuth2 system context, need to read the previous API key
prevKey, err := db.GetAPIKeyByID(dbauthz.AsSystemOAuth2(ctx), dbToken.APIKeyID)
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
// ScopeAll for the same reason as in authorizationCodeGrant.
actor, _, err := httpmw.UserRBACSubject(ctx, db, prevKey.UserID, rbac.ScopeAll)
if err != nil {
return codersdk.OAuth2TokenResponse{}, xerrors.Errorf("fetch user actor: %w", err)
}
// Generate a new refresh token.
refreshToken, err := GenerateSecret()
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
scopes, err := scopeStringToAPIKeyScopes(accessScope)
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
// Generate the new API key.
tokenName := fmt.Sprintf("%s_%s_oauth_session_token", prevKey.UserID, app.ID)
key, sessionToken, err := apikey.Generate(apikey.CreateParams{
UserID: prevKey.UserID,
LoginType: database.LoginTypeOAuth2ProviderApp,
DefaultLifetime: lifetimes.DefaultDuration.Value(),
Scopes: scopes,
// For now, we allow only one token per app and user at a time.
TokenName: tokenName,
})
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
// Replace the token.
// Determine refresh token expiry independently from the access token.
refreshLifetime := lifetimes.RefreshDefaultDuration.Value()
if refreshLifetime == 0 {
refreshLifetime = lifetimes.DefaultDuration.Value()
}
refreshExpiresAt := dbtime.Now().Add(refreshLifetime)
err = db.InTx(func(tx database.Store) error {
ctx := dbauthz.As(ctx, actor)
err = tx.DeleteAPIKeyByID(ctx, prevKey.ID) // This cascades to the token.
if err != nil {
return xerrors.Errorf("delete oauth2 app token: %w", err)
}
newKey, err := tx.InsertAPIKey(ctx, key)
if err != nil {
return xerrors.Errorf("insert oauth2 access token: %w", err)
}
_, err = tx.InsertOAuth2ProviderAppToken(ctx, database.InsertOAuth2ProviderAppTokenParams{
ID: uuid.New(),
CreatedAt: dbtime.Now(),
ExpiresAt: refreshExpiresAt,
HashPrefix: []byte(refreshToken.Prefix),
RefreshHash: refreshToken.Hashed,
AppID: dbToken.AppID,
AppSecretID: dbToken.AppSecretID,
APIKeyID: newKey.ID,
UserID: dbToken.UserID,
Audience: dbToken.Audience,
// The consented grant, not accessScope: this column is the ceiling
// later refreshes are bounded by, and the only record of what the
// user approved. A rotated refresh token carries the scope of the
// one presented (OAuth 2.1 §4.3.3).
Scope: dbToken.Scope,
})
if err != nil {
return xerrors.Errorf("insert oauth2 refresh token: %w", err)
}
return nil
}, nil)
if err != nil {
return codersdk.OAuth2TokenResponse{}, err
}
return codersdk.OAuth2TokenResponse{
AccessToken: sessionToken,
TokenType: codersdk.OAuth2TokenTypeBearer,
RefreshToken: refreshToken.Formatted,
ExpiresIn: int64(time.Until(key.ExpiresAt).Seconds()),
Scope: accessScope,
Expiry: &key.ExpiresAt,
}, nil
}
// validateResourceParameter validates that a resource parameter conforms to RFC 8707:
// must be an absolute URI without fragment component.
func validateResourceParameter(resource string) error {
if resource == "" {
return nil // Resource parameter is optional
}
u, err := url.Parse(resource)
if err != nil {
return xerrors.Errorf("invalid URI syntax: %w", err)
}
if u.Scheme == "" {
return xerrors.New("must be an absolute URI with scheme")
}
if u.Fragment != "" {
return xerrors.New("must not contain fragment component")
}
return nil
}