Skip to content

Commit

Permalink
apiserver.go: Break out rate limiting logic and apply to authExportPu…
Browse files Browse the repository at this point in the history
…blic
  • Loading branch information
jentfoo committed Apr 14, 2023
1 parent 00a9bd0 commit 454925b
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions lib/web/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -3632,22 +3632,28 @@ func (h *Handler) WithLimiter(fn httplib.HandlerFunc) httprouter.Handle {
// should be used when you need to nest this inside another HandlerFunc.
func (h *Handler) WithLimiterHandlerFunc(fn httplib.HandlerFunc) httplib.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
remote, _, err := net.SplitHostPort(r.RemoteAddr)
err := h.rateLimitRequest(r)
if err != nil {
return nil, trace.Wrap(err)
}
err = h.limiter.RegisterRequest(remote, nil /* customRate */)
// MaxRateError doesn't play well with errors.Is, hence the cast.
if _, ok := err.(*ratelimit.MaxRateError); ok {
return nil, trace.LimitExceeded(err.Error())
}
if err != nil {
return nil, trace.Wrap(err)
return nil, err
}
return fn(w, r, p)
}
}

func (h *Handler) rateLimitRequest(r *http.Request) error {
remote, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return trace.Wrap(err)
}

err = h.limiter.RegisterRequest(remote, nil /* customRate */)
// MaxRateError doesn't play well with errors.Is, hence the cast.
if _, ok := err.(*ratelimit.MaxRateError); ok {
return trace.LimitExceeded(err.Error())
}
return trace.Wrap(err)
}

// AuthenticateRequest authenticates request using combination of a session cookie
// and bearer token
func (h *Handler) AuthenticateRequest(w http.ResponseWriter, r *http.Request, checkBearerToken bool) (*SessionContext, error) {
Expand Down Expand Up @@ -3884,6 +3890,11 @@ func SSOSetWebSessionAndRedirectURL(w http.ResponseWriter, r *http.Request, resp
// GET /webapi/sites/:site/auth/export?type=<auth type>
// GET /webapi/auth/export?type=<auth type>
func (h *Handler) authExportPublic(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
err := h.rateLimitRequest(r)
if err != nil {
http.Error(w, err.Error(), trace.ErrorToCode(err))
return
}
authorities, err := client.ExportAuthorities(
r.Context(),
h.GetProxyClient(),
Expand Down

0 comments on commit 454925b

Please sign in to comment.