| 40 | ) |
| 41 | |
| 42 | func extractTokenRequest(r *http.Request, callbackURL *url.URL) (codersdk.OAuth2TokenRequest, []codersdk.ValidationError, error) { |
| 43 | p := httpapi.NewQueryParamParser() |
| 44 | err := r.ParseForm() |
| 45 | if err != nil { |
| 46 | return codersdk.OAuth2TokenRequest{}, nil, xerrors.Errorf("parse form: %w", err) |
| 47 | } |
| 48 | |
| 49 | vals := r.Form |
| 50 | p.RequiredNotEmpty("grant_type") |
| 51 | grantType := httpapi.ParseCustom(p, vals, "", "grant_type", httpapi.ParseEnum[codersdk.OAuth2ProviderGrantType]) |
| 52 | |
| 53 | // Grant-type specific validation - must be called before parsing values. |
| 54 | switch grantType { |
| 55 | case codersdk.OAuth2ProviderGrantTypeRefreshToken: |
| 56 | p.RequiredNotEmpty("refresh_token") |
| 57 | case codersdk.OAuth2ProviderGrantTypeAuthorizationCode: |
| 58 | p.RequiredNotEmpty("code") |
| 59 | } |
| 60 | |
| 61 | req := codersdk.OAuth2TokenRequest{ |
| 62 | GrantType: grantType, |
| 63 | ClientID: p.String(vals, "", "client_id"), |
| 64 | ClientSecret: p.String(vals, "", "client_secret"), |
| 65 | Code: p.String(vals, "", "code"), |
| 66 | RedirectURI: p.String(vals, "", "redirect_uri"), |
| 67 | RefreshToken: p.String(vals, "", "refresh_token"), |
| 68 | CodeVerifier: p.String(vals, "", "code_verifier"), |
| 69 | Resource: p.String(vals, "", "resource"), |
| 70 | Scope: p.String(vals, "", "scope"), |
| 71 | } |
| 72 | |
| 73 | // RFC 6749 §2.3.1: confidential clients may authenticate via HTTP Basic. |
| 74 | if user, pass, ok := r.BasicAuth(); ok && user != "" { |
| 75 | if req.ClientID != "" && req.ClientID != user { |
| 76 | return codersdk.OAuth2TokenRequest{}, nil, errConflictingClientAuth |
| 77 | } |
| 78 | if req.ClientSecret != "" && req.ClientSecret != pass { |
| 79 | return codersdk.OAuth2TokenRequest{}, nil, errConflictingClientAuth |
| 80 | } |
| 81 | |
| 82 | req.ClientID = user |
| 83 | req.ClientSecret = pass |
| 84 | } |
| 85 | |
| 86 | // Grant-specific required checks that can be satisfied via HTTP Basic. |
| 87 | if req.GrantType == codersdk.OAuth2ProviderGrantTypeAuthorizationCode { |
| 88 | if req.ClientID == "" { |
| 89 | p.Errors = append(p.Errors, codersdk.ValidationError{ |
| 90 | Field: "client_id", |
| 91 | Detail: "Parameter \"client_id\" is required and cannot be empty", |
| 92 | }) |
| 93 | } |
| 94 | if req.ClientSecret == "" { |
| 95 | p.Errors = append(p.Errors, codersdk.ValidationError{ |
| 96 | Field: "client_secret", |
| 97 | Detail: "Parameter \"client_secret\" is required and cannot be empty", |
| 98 | }) |
| 99 | } |