(ctx context.Context, db database.Store, app database.OAuth2ProviderApp, lifetimes codersdk.SessionLifetime, req codersdk.OAuth2TokenRequest)
| 212 | } |
| 213 | |
| 214 | func authorizationCodeGrant(ctx context.Context, db database.Store, app database.OAuth2ProviderApp, lifetimes codersdk.SessionLifetime, req codersdk.OAuth2TokenRequest) (codersdk.OAuth2TokenResponse, error) { |
| 215 | // Validate the client secret. |
| 216 | secret, err := ParseFormattedSecret(req.ClientSecret) |
| 217 | if err != nil { |
| 218 | return codersdk.OAuth2TokenResponse{}, errBadSecret |
| 219 | } |
| 220 | //nolint:gocritic // OAuth2 system context — users cannot read secrets |
| 221 | dbSecret, err := db.GetOAuth2ProviderAppSecretByPrefix(dbauthz.AsSystemOAuth2(ctx), []byte(secret.Prefix)) |
| 222 | if errors.Is(err, sql.ErrNoRows) { |
| 223 | return codersdk.OAuth2TokenResponse{}, errBadSecret |
| 224 | } |
| 225 | if err != nil { |
| 226 | return codersdk.OAuth2TokenResponse{}, err |
| 227 | } |
| 228 | |
| 229 | equalSecret := apikey.ValidateHash(dbSecret.HashedSecret, secret.Secret) |
| 230 | if !equalSecret { |
| 231 | return codersdk.OAuth2TokenResponse{}, errBadSecret |
| 232 | } |
| 233 | |
| 234 | // Validate the authorization code. |
| 235 | code, err := ParseFormattedSecret(req.Code) |
| 236 | if err != nil { |
| 237 | return codersdk.OAuth2TokenResponse{}, errBadCode |
| 238 | } |
| 239 | //nolint:gocritic // OAuth2 system context — no authenticated user during token exchange |
| 240 | dbCode, err := db.GetOAuth2ProviderAppCodeByPrefix(dbauthz.AsSystemOAuth2(ctx), []byte(code.Prefix)) |
| 241 | if errors.Is(err, sql.ErrNoRows) { |
| 242 | return codersdk.OAuth2TokenResponse{}, errBadCode |
| 243 | } |
| 244 | if err != nil { |
| 245 | return codersdk.OAuth2TokenResponse{}, err |
| 246 | } |
| 247 | equalCode := apikey.ValidateHash(dbCode.HashedSecret, code.Secret) |
| 248 | if !equalCode { |
| 249 | return codersdk.OAuth2TokenResponse{}, errBadCode |
| 250 | } |
| 251 | |
| 252 | // Ensure the code has not expired. |
| 253 | if dbCode.ExpiresAt.Before(dbtime.Now()) { |
| 254 | return codersdk.OAuth2TokenResponse{}, errBadCode |
| 255 | } |
| 256 | |
| 257 | // Verify redirect_uri matches the one used during authorization |
| 258 | // (RFC 6749 §4.1.3). |
| 259 | if dbCode.RedirectUri.Valid && dbCode.RedirectUri.String != "" { |
| 260 | if req.RedirectURI != dbCode.RedirectUri.String { |
| 261 | return codersdk.OAuth2TokenResponse{}, errBadCode |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | // PKCE is mandatory for all authorization code flows |
| 266 | // (OAuth 2.1). Verify the code verifier against the stored |
| 267 | // challenge. |
| 268 | if req.CodeVerifier == "" { |
| 269 | return codersdk.OAuth2TokenResponse{}, errInvalidPKCE |
| 270 | } |
| 271 | if !dbCode.CodeChallenge.Valid || dbCode.CodeChallenge.String == "" { |
no test coverage detected