|
| 1 | +package identityprovider |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/sha256" |
| 5 | + "net/http" |
| 6 | + "net/url" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/google/uuid" |
| 11 | + "golang.org/x/xerrors" |
| 12 | + |
| 13 | + "github.com/coder/coder/v2/coderd/database" |
| 14 | + "github.com/coder/coder/v2/coderd/database/dbtime" |
| 15 | + "github.com/coder/coder/v2/coderd/httpapi" |
| 16 | + "github.com/coder/coder/v2/coderd/httpmw" |
| 17 | + "github.com/coder/coder/v2/codersdk" |
| 18 | + "github.com/coder/coder/v2/cryptorand" |
| 19 | +) |
| 20 | + |
| 21 | +/** |
| 22 | + * Authorize displays an HTML for authorizing an application when the user has |
| 23 | + * first been redirected to this path and generates a code and redirects to the |
| 24 | + * app's callback URL after the user clicks "allow" on that page. |
| 25 | + */ |
| 26 | +func Authorize(db database.Store, accessURL *url.URL) http.HandlerFunc { |
| 27 | + handler := func(rw http.ResponseWriter, r *http.Request) { |
| 28 | + ctx := r.Context() |
| 29 | + apiKey, ok := httpmw.APIKeyOptional(r) |
| 30 | + if !ok { |
| 31 | + // TODO: Should this be unauthorized? Or Forbidden? |
| 32 | + // This should redirect to a login page. |
| 33 | + httpapi.Forbidden(rw) |
| 34 | + return |
| 35 | + } |
| 36 | + |
| 37 | + app := httpmw.OAuth2ProviderApp(r) |
| 38 | + |
| 39 | + // TODO: @emyrk this should always work, maybe make callbackURL a *url.URL? |
| 40 | + callbackURL, _ := url.Parse(app.CallbackURL) |
| 41 | + |
| 42 | + // TODO: Should validate these on the HTML page as well and show errors |
| 43 | + // there rather than wait until this endpoint to show them. |
| 44 | + p := httpapi.NewQueryParamParser() |
| 45 | + vals := r.URL.Query() |
| 46 | + p.Required("state", "response_type") |
| 47 | + state := p.String(vals, "", "state") |
| 48 | + scope := p.Strings(vals, []string{}, "scope") |
| 49 | + // Client_id is already parsed in the mw above. |
| 50 | + _ = p.String(vals, "", "client_id") |
| 51 | + redirectURL := p.URL(vals, callbackURL, "redirect_uri") |
| 52 | + responseType := p.String(vals, "", "response_type") |
| 53 | + // TODO: Redirected might exist but it should not cause validation errors. |
| 54 | + _ = p.String(vals, "", "redirected") |
| 55 | + p.ErrorExcessParams(vals) |
| 56 | + if len(p.Errors) > 0 { |
| 57 | + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 58 | + Message: "Invalid query params.", |
| 59 | + Validations: p.Errors, |
| 60 | + }) |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + // TODO: @emyrk what other ones are there? |
| 65 | + if responseType != "code" { |
| 66 | + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 67 | + Message: "Invalid response type.", |
| 68 | + }) |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + // TODO: @emyrk handle scope? |
| 73 | + _ = scope |
| 74 | + |
| 75 | + if err := validateRedirectURL(app.CallbackURL, redirectURL.String()); err != nil { |
| 76 | + httpapi.Write(r.Context(), rw, http.StatusBadRequest, codersdk.Response{ |
| 77 | + Message: "Invalid redirect URL.", |
| 78 | + }) |
| 79 | + return |
| 80 | + } |
| 81 | + // 40 characters matches the length of GitHub's client secrets. |
| 82 | + rawSecret, err := cryptorand.String(40) |
| 83 | + if err != nil { |
| 84 | + httpapi.Write(r.Context(), rw, http.StatusInternalServerError, codersdk.Response{ |
| 85 | + Message: "Failed to generate OAuth2 app authorization code.", |
| 86 | + }) |
| 87 | + return |
| 88 | + } |
| 89 | + hashed := sha256.Sum256([]byte(rawSecret)) |
| 90 | + _, err = db.InsertOAuth2ProviderAppCode(ctx, database.InsertOAuth2ProviderAppCodeParams{ |
| 91 | + ID: uuid.New(), |
| 92 | + CreatedAt: dbtime.Now(), |
| 93 | + // TODO: Configurable expiration? |
| 94 | + ExpiresAt: dbtime.Now().Add(time.Duration(10) * time.Minute), |
| 95 | + HashedSecret: hashed[:], |
| 96 | + AppID: app.ID, |
| 97 | + UserID: apiKey.UserID, |
| 98 | + }) |
| 99 | + if err != nil { |
| 100 | + httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 101 | + Message: "Internal error insert OAuth2 authorization code.", |
| 102 | + Detail: err.Error(), |
| 103 | + }) |
| 104 | + return |
| 105 | + } |
| 106 | + |
| 107 | + newQuery := redirectURL.Query() |
| 108 | + newQuery.Add("code", rawSecret) |
| 109 | + newQuery.Add("state", state) |
| 110 | + redirectURL.RawQuery = newQuery.Encode() |
| 111 | + |
| 112 | + http.Redirect(rw, r, redirectURL.String(), http.StatusTemporaryRedirect) |
| 113 | + } |
| 114 | + |
| 115 | + // Always wrap with its custom mw. |
| 116 | + return authorizeMW(accessURL)(http.HandlerFunc(handler)).ServeHTTP |
| 117 | +} |
| 118 | + |
| 119 | +// validateRedirectURL validates that the redirectURL is contained in baseURL. |
| 120 | +func validateRedirectURL(baseURL string, redirectURL string) error { |
| 121 | + base, err := url.Parse(baseURL) |
| 122 | + if err != nil { |
| 123 | + return err |
| 124 | + } |
| 125 | + |
| 126 | + redirect, err := url.Parse(redirectURL) |
| 127 | + if err != nil { |
| 128 | + return err |
| 129 | + } |
| 130 | + // It can be a sub-directory but not a sub-domain, as we have apps on |
| 131 | + // sub-domains so it seems too dangerous. |
| 132 | + if redirect.Host != base.Host || !strings.HasPrefix(redirect.Path, base.Path) { |
| 133 | + return xerrors.New("invalid redirect URL") |
| 134 | + } |
| 135 | + return nil |
| 136 | +} |
0 commit comments