|
| 1 | +package identityprovider |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "net/url" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/google/uuid" |
| 13 | + "golang.org/x/xerrors" |
| 14 | + |
| 15 | + "github.com/coder/coder/v2/coderd/database" |
| 16 | + "github.com/coder/coder/v2/coderd/database/dbtime" |
| 17 | + "github.com/coder/coder/v2/coderd/httpapi" |
| 18 | + "github.com/coder/coder/v2/coderd/httpmw" |
| 19 | + "github.com/coder/coder/v2/codersdk" |
| 20 | + "github.com/coder/coder/v2/cryptorand" |
| 21 | +) |
| 22 | + |
| 23 | +type authorizeParams struct { |
| 24 | + clientID string |
| 25 | + redirectURL *url.URL |
| 26 | + responseType codersdk.OAuth2ProviderResponseType |
| 27 | + scope []string |
| 28 | + state string |
| 29 | +} |
| 30 | + |
| 31 | +func extractAuthorizeParams(r *http.Request, callbackURL string) (authorizeParams, []codersdk.ValidationError, error) { |
| 32 | + p := httpapi.NewQueryParamParser() |
| 33 | + vals := r.URL.Query() |
| 34 | + |
| 35 | + p.Required("state", "response_type", "client_id") |
| 36 | + |
| 37 | + // TODO: Can we make this a URL straight out of the database? |
| 38 | + cb, err := url.Parse(callbackURL) |
| 39 | + if err != nil { |
| 40 | + return authorizeParams{}, nil, err |
| 41 | + } |
| 42 | + params := authorizeParams{ |
| 43 | + clientID: p.String(vals, "", "client_id"), |
| 44 | + redirectURL: p.URL(vals, cb, "redirect_uri"), |
| 45 | + responseType: httpapi.ParseCustom(p, vals, "", "response_type", httpapi.ParseEnum[codersdk.OAuth2ProviderResponseType]), |
| 46 | + scope: p.Strings(vals, []string{}, "scope"), |
| 47 | + state: p.String(vals, "", "state"), |
| 48 | + } |
| 49 | + |
| 50 | + // We add "redirected" when coming from the authorize page. |
| 51 | + _ = p.String(vals, "", "redirected") |
| 52 | + |
| 53 | + if err := validateRedirectURL(cb, params.redirectURL.String()); err != nil { |
| 54 | + p.Errors = append(p.Errors, codersdk.ValidationError{ |
| 55 | + Field: "redirect_uri", |
| 56 | + Detail: fmt.Sprintf("Query param %q is invalid", "redirect_uri"), |
| 57 | + }) |
| 58 | + } |
| 59 | + |
| 60 | + p.ErrorExcessParams(vals) |
| 61 | + return params, p.Errors, nil |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Authorize displays an HTML page for authorizing an application when the user |
| 66 | + * has first been redirected to this path and generates a code and redirects to |
| 67 | + * the app's callback URL after the user clicks "allow" on that page, which is |
| 68 | + * detected via the origin and referer headers. |
| 69 | + */ |
| 70 | +func Authorize(db database.Store, accessURL *url.URL) http.HandlerFunc { |
| 71 | + handler := func(rw http.ResponseWriter, r *http.Request) { |
| 72 | + ctx := r.Context() |
| 73 | + apiKey := httpmw.APIKey(r) |
| 74 | + app := httpmw.OAuth2ProviderApp(r) |
| 75 | + |
| 76 | + params, validationErrs, err := extractAuthorizeParams(r, app.CallbackURL) |
| 77 | + if err != nil { |
| 78 | + httpapi.Write(r.Context(), rw, http.StatusInternalServerError, codersdk.Response{ |
| 79 | + Message: "Failed to validate query parameters.", |
| 80 | + Detail: err.Error(), |
| 81 | + }) |
| 82 | + return |
| 83 | + } |
| 84 | + if len(validationErrs) > 0 { |
| 85 | + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 86 | + Message: "Invalid query params.", |
| 87 | + Validations: validationErrs, |
| 88 | + }) |
| 89 | + return |
| 90 | + } |
| 91 | + |
| 92 | + // TODO: Ignoring scope for now, but should look into implementing. |
| 93 | + // 40 characters matches the length of GitHub's client secrets. |
| 94 | + rawCode, err := cryptorand.String(40) |
| 95 | + if err != nil { |
| 96 | + httpapi.Write(r.Context(), rw, http.StatusInternalServerError, codersdk.Response{ |
| 97 | + Message: "Failed to generate OAuth2 app authorization code.", |
| 98 | + }) |
| 99 | + return |
| 100 | + } |
| 101 | + hashedCode := Hash(rawCode, app.ID) |
| 102 | + err = db.InTx(func(tx database.Store) error { |
| 103 | + // Delete any previous codes. |
| 104 | + err = tx.DeleteOAuth2ProviderAppCodesByAppAndUserID(ctx, database.DeleteOAuth2ProviderAppCodesByAppAndUserIDParams{ |
| 105 | + AppID: app.ID, |
| 106 | + UserID: apiKey.UserID, |
| 107 | + }) |
| 108 | + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 109 | + return xerrors.Errorf("delete oauth2 app codes: %w", err) |
| 110 | + } |
| 111 | + |
| 112 | + // Insert the new code. |
| 113 | + _, err = tx.InsertOAuth2ProviderAppCode(ctx, database.InsertOAuth2ProviderAppCodeParams{ |
| 114 | + ID: uuid.New(), |
| 115 | + CreatedAt: dbtime.Now(), |
| 116 | + // TODO: Configurable expiration? Ten minutes matches GitHub. |
| 117 | + ExpiresAt: dbtime.Now().Add(time.Duration(10) * time.Minute), |
| 118 | + HashedSecret: hashedCode[:], |
| 119 | + AppID: app.ID, |
| 120 | + UserID: apiKey.UserID, |
| 121 | + }) |
| 122 | + if err != nil { |
| 123 | + return xerrors.Errorf("insert oauth2 authorization code: %w", err) |
| 124 | + } |
| 125 | + |
| 126 | + return nil |
| 127 | + }, nil) |
| 128 | + if err != nil { |
| 129 | + httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 130 | + Message: "Failed to generate OAuth2 authorization code.", |
| 131 | + Detail: err.Error(), |
| 132 | + }) |
| 133 | + return |
| 134 | + } |
| 135 | + |
| 136 | + newQuery := params.redirectURL.Query() |
| 137 | + newQuery.Add("code", rawCode) |
| 138 | + newQuery.Add("state", params.state) |
| 139 | + params.redirectURL.RawQuery = newQuery.Encode() |
| 140 | + |
| 141 | + http.Redirect(rw, r, params.redirectURL.String(), http.StatusTemporaryRedirect) |
| 142 | + } |
| 143 | + |
| 144 | + // Always wrap with its custom mw. |
| 145 | + return authorizeMW(accessURL)(http.HandlerFunc(handler)).ServeHTTP |
| 146 | +} |
| 147 | + |
| 148 | +// validateRedirectURL validates that the redirectURL is contained in baseURL. |
| 149 | +func validateRedirectURL(baseURL *url.URL, redirectURL string) error { |
| 150 | + redirect, err := url.Parse(redirectURL) |
| 151 | + if err != nil { |
| 152 | + return err |
| 153 | + } |
| 154 | + // It can be a sub-directory but not a sub-domain, as we have apps on |
| 155 | + // sub-domains so it seems too dangerous. |
| 156 | + if redirect.Host != baseURL.Host || !strings.HasPrefix(redirect
10000
span>.Path, baseURL.Path) { |
| 157 | + return xerrors.New("invalid redirect URL") |
| 158 | + } |
| 159 | + return nil |
| 160 | +} |
0 commit comments