Merge branch 'origin/main' into 'next-release/main'

This commit is contained in:
oauth committed 2026-11-13 19:20:08 +00:00
commit b75ab410da
22 files changed
+1422 -14

No files matched your search

+1
View File
@@ -21,6 +21,7 @@ require (
github.com/gabriel-vasile/mimetype v1.4.15
github.com/ggwhite/go-masker v1.1.0
github.com/go-chi/chi/v5 v5.4.0
github.com/go-chi/httprate v0.16.1
github.com/go-chi/render v1.0.3
github.com/go-ldap/ldap/v3 v3.4.15
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3
+2
View File
@@ -305,6 +305,8 @@ github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoM
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-chi/chi/v5 v5.4.0 h1:+ufzvFTGKyin26Or5DLrlIDq4ygIDBVcj7oVNeeaYFE=
github.com/go-chi/chi/v5 v5.4.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
github.com/go-chi/httprate v0.16.1 h1:q2M8FmDsI4oEr1oRX43N+VeA0Ujd1tb/EasrSzXy87o=
github.com/go-chi/httprate v0.16.1/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
+57
View File
@@ -0,0 +1,57 @@
package middleware
import (
"errors"
"net/http"
"time"
"github.com/go-chi/httprate"
revactx "github.com/opencloud-eu/reva/v2/pkg/ctx"
)
var errNoAuthenticatedUser = errors.New("no authenticated user")
// RateLimitPerAuthenticatedUser limits the number of requests that each
// authenticated user can make within the given window. Requests beyond the
// limit get a 429 response with a Retry-After header. A limit of 0 or less
// disables the limit.
//
// limitReached writes the response to a request beyond the limit, so that a
// service can answer in its own error format. The Retry-After header is set
// already when it is called, and it must set the status 429 itself. If it is
// nil, the response is a plain text 429.
//
// It requires an authenticated user in the request context, and so must come
// after the middleware that authenticates the request: requests without one
// get a 401 response. The requests are counted by the id of that user, not by
// anything in the request, so that clients can't get around the limit by
// varying the URL.
//
// The counters are kept in memory, separately by every instance of the
// service, and by every call of this function: use one call per route that
// needs its own limit.
func RateLimitPerAuthenticatedUser(limit int, window time.Duration, limitReached http.HandlerFunc) func(http.Handler) http.Handler {
if limit <= 0 {
return func(next http.Handler) http.Handler {
return next
}
}
return httprate.LimitBy(limit, window, authenticatedUserID,
// httprate answers with its plain text 429 if this is nil
httprate.WithLimitHandler(limitReached),
httprate.WithErrorHandler(func(w http.ResponseWriter, _ *http.Request, _ error) {
// the only error is a missing user: the default answer
// would be a 428, which is misleading
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
}),
)
}
// authenticatedUserID is the httprate.KeyFunc of RateLimitPerAuthenticatedUser.
func authenticatedUserID(r *http.Request) (string, error) {
u, ok := revactx.ContextGetUser(r.Context())
if !ok || u.GetId().GetOpaqueId() == "" {
return "", errNoAuthenticatedUser
}
return u.GetId().GetOpaqueId(), nil
}
+73
View File
@@ -0,0 +1,73 @@
package middleware
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
revactx "github.com/opencloud-eu/reva/v2/pkg/ctx"
"github.com/stretchr/testify/assert"
)
func TestRateLimitPerAuthenticatedUser(t *testing.T) {
ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
// do sends a request as the given user, or without one if user is empty
do := func(h http.Handler, user, path string) *httptest.ResponseRecorder {
ctx := context.Background()
if user != "" {
ctx = revactx.ContextSetUser(ctx, &userv1beta1.User{Id: &userv1beta1.UserId{OpaqueId: user}})
}
rr := httptest.NewRecorder()
h.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, path, nil).WithContext(ctx))
return rr
}
t.Run("limits each user on their own", func(t *testing.T) {
h := RateLimitPerAuthenticatedUser(2, time.Minute, nil)(ok)
assert.Equal(t, http.StatusOK, do(h, "alice", "/a").Code)
assert.Equal(t, http.StatusOK, do(h, "alice", "/a").Code)
rr := do(h, "alice", "/a")
assert.Equal(t, http.StatusTooManyRequests, rr.Code)
assert.NotEmpty(t, rr.Header().Get("Retry-After"))
assert.Equal(t, http.StatusOK, do(h, "bob", "/a").Code)
})
t.Run("counts by user, not by URL", func(t *testing.T) {
h := RateLimitPerAuthenticatedUser(2, time.Minute, nil)(ok)
assert.Equal(t, http.StatusOK, do(h, "alice", "/a").Code)
assert.Equal(t, http.StatusOK, do(h, "alice", "/a/").Code)
assert.Equal(t, http.StatusTooManyRequests, do(h, "alice", "/b?x=1").Code)
})
t.Run("rejects requests without an authenticated user", func(t *testing.T) {
h := RateLimitPerAuthenticatedUser(2, time.Minute, nil)(ok)
assert.Equal(t, http.StatusUnauthorized, do(h, "", "/a").Code)
})
t.Run("a limit of 0 disables it", func(t *testing.T) {
h := RateLimitPerAuthenticatedUser(0, time.Minute, nil)(ok)
for range 5 {
assert.Equal(t, http.StatusOK, do(h, "alice", "/a").Code)
}
})
t.Run("answers beyond the limit with the given handler", func(t *testing.T) {
limitReached := func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(`{"error":"slow down"}`))
}
h := RateLimitPerAuthenticatedUser(1, time.Minute, limitReached)(ok)
assert.Equal(t, http.StatusOK, do(h, "alice", "/a").Code)
rr := do(h, "alice", "/a")
assert.Equal(t, http.StatusTooManyRequests, rr.Code)
assert.Equal(t, "application/json", rr.Header().Get("Content-Type"))
assert.JSONEq(t, `{"error":"slow down"}`, rr.Body.String())
// set before the handler is called
assert.NotEmpty(t, rr.Header().Get("Retry-After"))
})
}
+14
View File
@@ -164,6 +164,20 @@ The client that is used to authenticate with keycloak has to be able to list use
These roles are only available to assign if the client is in the `master` realm.
:::
## Rate Limit For The Personal Data Export
Every personal data export collects the data of the user and writes it to a file in the user's personal space, which takes time and resources. To keep users from starting exports over and over, the number of exports a user can start is limited to 5 per minute. Further requests within the same minute are answered with the HTTP status `429 Too Many Requests` and a `Retry-After` header that tells the client how long to wait at most before trying again.
The limit can be changed with `GRAPH_EXPORT_PERSONAL_DATA_RATE_LIMIT`, for example to allow 2 exports per minute:
```bash
GRAPH_EXPORT_PERSONAL_DATA_RATE_LIMIT=2
```
Setting it to `0` disables the limit.
Every instance of the `graph` service counts the requests on its own, in memory. When several instances run behind a load balancer, a user can start up to this number of exports per minute on each of them, and a restart of an instance resets its counts.
## Translations
The `graph` service has embedded translations sourced via transifex to provide a basic set of translated languages. These embedded translations are available for all deployment scenarios. In addition, the service supports custom translations, though it is currently not possible to just add custom translations to embedded ones. If custom translations are configured, the embedded ones are not used. To configure custom translations, the `GRAPH_TRANSLATION_PATH` environment variable needs to point to a base folder that will contain the translation files. This path must be available from all instances of the graph service, a shared storage is recommended. Translation files must be of type [.po](https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html#PO-Files) or [.mo](https://www.gnu.org/software/gettext/manual/html_node/Binaries.html). For each language, the filename needs to be `graph.po` (or `graph.mo`) and stored in a folder structure defining the language code. In general the path/name pattern for a translation file needs to be:
+6 -5
View File
@@ -134,11 +134,12 @@ type Identity struct {
// API represents API configuration parameters.
type API struct {
GroupMembersPatchLimit int `yaml:"group_members_patch_limit" env:"GRAPH_GROUP_MEMBERS_PATCH_LIMIT" desc:"The amount of group members allowed to be added with a single patch request." introductionVersion:"1.0.0"`
UsernameMatch string `yaml:"graph_username_match" env:"GRAPH_USERNAME_MATCH" desc:"Apply restrictions to usernames. Supported values are 'default' and 'none'. When set to 'default', user names must not start with a number and are restricted to ASCII characters. When set to 'none', no restrictions are applied. The default value is 'default'." introductionVersion:"1.0.0"`
AssignDefaultUserRole bool `yaml:"graph_assign_default_user_role" env:"GRAPH_ASSIGN_DEFAULT_USER_ROLE" desc:"Whether to assign newly created users the default role 'User'. Set this to 'false' if you want to assign roles manually, or if the role assignment should happen at first login. Set this to 'true' (the default) to assign the role 'User' when creating a new user." introductionVersion:"1.0.0"`
IdentitySearchMinLength int `yaml:"graph_identity_search_min_length" env:"GRAPH_IDENTITY_SEARCH_MIN_LENGTH" desc:"The minimum length the search term needs to have for unprivileged users when searching for users or groups." introductionVersion:"1.0.0"`
ShowUserEmailInResults bool `yaml:"show_email_in_results" env:"OC_SHOW_USER_EMAIL_IN_RESULTS" desc:"Include user email addresses in responses. If absent or set to false emails will be omitted from results. Please note that admin users can always see all email addresses." introductionVersion:"1.0.0"`
GroupMembersPatchLimit int `yaml:"group_members_patch_limit" env:"GRAPH_GROUP_MEMBERS_PATCH_LIMIT" desc:"The amount of group members allowed to be added with a single patch request." introductionVersion:"1.0.0"`
UsernameMatch string `yaml:"graph_username_match" env:"GRAPH_USERNAME_MATCH" desc:"Apply restrictions to usernames. Supported values are 'default' and 'none'. When set to 'default', user names must not start with a number and are restricted to ASCII characters. When set to 'none', no restrictions are applied. The default value is 'default'." introductionVersion:"1.0.0"`
AssignDefaultUserRole bool `yaml:"graph_assign_default_user_role" env:"GRAPH_ASSIGN_DEFAULT_USER_ROLE" desc:"Whether to assign newly created users the default role 'User'. Set this to 'false' if you want to assign roles manually, or if the role assignment should happen at first login. Set this to 'true' (the default) to assign the role 'User' when creating a new user." introductionVersion:"1.0.0"`
IdentitySearchMinLength int `yaml:"graph_identity_search_min_length" env:"GRAPH_IDENTITY_SEARCH_MIN_LENGTH" desc:"The minimum length the search term needs to have for unprivileged users when searching for users or groups." introductionVersion:"1.0.0"`
ShowUserEmailInResults bool `yaml:"show_email_in_results" env:"OC_SHOW_USER_EMAIL_IN_RESULTS" desc:"Include user email addresses in responses. If absent or set to false emails will be omitted from results. Please note that admin users can always see all email addresses." introductionVersion:"1.0.0"`
ExportPersonalDataRateLimit int `yaml:"export_personal_data_rate_limit" env:"GRAPH_EXPORT_PERSONAL_DATA_RATE_LIMIT" desc:"The maximum number of personal data exports a user can start per minute. Each instance of the graph service counts on its own, so with several instances, a user can start up to this number of exports on each of them. Set it to 0 to disable the limit." introductionVersion:"%%NEXT%%"`
}
// Events combines the configuration options for the event bus.
@@ -71,10 +71,11 @@ func DefaultConfig() *config.Config {
DisplayName: "OpenCloud",
},
API: config.API{
GroupMembersPatchLimit: 20,
UsernameMatch: "default",
AssignDefaultUserRole: true,
IdentitySearchMinLength: 3,
GroupMembersPatchLimit: 20,
UsernameMatch: "default",
AssignDefaultUserRole: true,
IdentitySearchMinLength: 3,
ExportPersonalDataRateLimit: 5,
},
Reva: shared.DefaultRevaConfig(),
Spaces: config.Spaces{
@@ -0,0 +1,45 @@
package middleware
import (
"net/http"
"net/url"
"github.com/go-chi/chi/v5"
"github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode"
revactx "github.com/opencloud-eu/reva/v2/pkg/ctx"
)
// RequireOwnUserID rejects requests whose URL parameter urlParam, the user id
// in the route pattern (e.g. "userID" for "/users/{userID}"), isn't the ID of
// the authenticated user, for endpoints that let users act only on
// themselves. A route without that parameter rejects every request. It must
// come after the authentication, and before any middleware that keeps state
// per user, such as a rate limit, so that requests for other users don't
// count against them.
func RequireOwnUserID(urlParam string, logger log.Logger) func(next http.Handler) http.Handler {
l := log.Logger{Logger: logger.With().Str("middleware", "requireOwnUserID").Logger()}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, ok := revactx.ContextGetUser(r.Context())
if !ok {
errorcode.AccessDenied.Render(w, r, http.StatusUnauthorized, "Unauthorized")
return
}
userID, err := url.PathUnescape(chi.URLParam(r, urlParam))
if err != nil {
l.Debug().Err(err).Str("userid", chi.URLParam(r, urlParam)).Msg("could not unescape the user id")
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid user id")
return
}
if userID == "" || userID != u.GetId().GetOpaqueId() {
l.Info().Str("userid", u.GetId().GetOpaqueId()).Str("requestedUserID", userID).Msg("user id in the request is not the user's own")
// 403 would arguably be the more fitting status code, but
// clients may rely on the 400 that this has always returned.
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "not permitted for other users")
return
}
next.ServeHTTP(w, r)
})
}
}
@@ -0,0 +1,61 @@
package middleware
import (
"context"
"net/http"
"net/http/httptest"
"testing"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/go-chi/chi/v5"
"github.com/opencloud-eu/opencloud/pkg/log"
revactx "github.com/opencloud-eu/reva/v2/pkg/ctx"
)
func TestRequireOwnUserID(t *testing.T) {
router := chi.NewRouter()
router.With(RequireOwnUserID("userID", log.NopLogger())).
Post("/users/{userID}/action", dummyHandler{}.ServeHTTP)
// a misconfigured route, whose parameter has another name
router.With(RequireOwnUserID("userID", log.NopLogger())).
Post("/users/{id}/other", dummyHandler{}.ServeHTTP)
tests := []struct {
name string
path string
user string
noUser bool // no user in the context at all
status int
}{
{name: "own user id", path: "/users/alice/action", user: "alice", status: http.StatusOK},
{name: "own user id, escaped", path: "/users/al%69ce/action", user: "alice", status: http.StatusOK},
{name: "own user id with an escaped slash", path: "/users/a%2Fb/action", user: "a/b", status: http.StatusOK},
{name: "other user id", path: "/users/bob/action", user: "alice", status: http.StatusBadRequest},
// U+200B ZERO WIDTH SPACE after the user id
{name: "own user id with an invisible character", path: "/users/alice%E2%80%8B/action", user: "alice", status: http.StatusBadRequest},
// "e" followed by U+0301 COMBINING ACUTE ACCENT, the decomposed form of the "\u00e9" in the user id
{name: "own user id in another unicode normalization form", path: "/users/jos%65%CC%81/action", user: "jos\u00e9", status: http.StatusBadRequest},
{name: "own user id with different case", path: "/users/Alice/action", user: "alice", status: http.StatusBadRequest},
{name: "invalid escape", path: "/users/al%zzce/action", user: "alice", status: http.StatusBadRequest},
{name: "route without the parameter", path: "/users/alice/other", user: "alice", status: http.StatusBadRequest},
{name: "user without an id, route without the parameter", path: "/users/alice/other", user: "", status: http.StatusBadRequest},
{name: "no authenticated user", path: "/users/alice/action", noUser: true, status: http.StatusUnauthorized},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/", nil)
// set the path afterwards: NewRequest rejects invalid escapes
req.URL.Path = ""
req.URL.RawPath = tt.path
ctx := context.Background()
if !tt.noUser {
ctx = revactx.ContextSetUser(ctx, &userv1beta1.User{Id: &userv1beta1.UserId{OpaqueId: tt.user}})
}
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req.WithContext(ctx))
if rr.Code != tt.status {
t.Errorf("got status %d, want %d", rr.Code, tt.status)
}
})
}
}
+16 -4
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"path/filepath"
"strconv"
@@ -79,14 +80,25 @@ func (g Graph) getPersonalSpace(ctx context.Context, u *user.UserId) (*provider.
return res.GetStorageSpaces()[0], nil
}
// exportPersonalDataLimitReached answers a request to export the personal data
// beyond the rate limit, in the error format of the other graph endpoints. The
// rate limit has set the Retry-After header already.
func exportPersonalDataLimitReached(w http.ResponseWriter, r *http.Request) {
errorcode.ActivityLimitReached.Render(w, r, http.StatusTooManyRequests, "too many exports of personal data, try again later")
}
// ExportPersonalData exports all personal data the system holds
func (g Graph) ExportPersonalData(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
u := revactx.ContextMustGetUser(ctx)
if reqUserID := chi.URLParam(r, "userID"); reqUserID != u.GetId().GetOpaqueId() {
g.logger.Info().Msg("uid mismatch")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("personal data export for other users are not permitted"))
// The RequireOwnUserID middleware on the route rejects requests for other
// users already. Check it here again all the same: exporting the data of
// one user to another must never happen, also when the route is changed
// by mistake.
if userID, err := url.PathUnescape(chi.URLParam(r, "userID")); err != nil || userID == "" || userID != u.GetId().GetOpaqueId() {
g.logger.Error().Err(err).Str("userid", u.GetId().GetOpaqueId()).Str("requestedUserID", chi.URLParam(r, "userID")).
Msg("personal data export for another user reached the handler: is the RequireOwnUserID middleware missing on the route?")
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "not permitted for other users")
return
}
// Get location from request
@@ -0,0 +1,46 @@
package svc
import (
"context"
"net/http"
"net/http/httptest"
"testing"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/go-chi/chi/v5"
revactx "github.com/opencloud-eu/reva/v2/pkg/ctx"
"github.com/stretchr/testify/assert"
"github.com/opencloud-eu/opencloud/pkg/log"
)
// The handler checks the user id on its own as well, so that a route without
// the RequireOwnUserID middleware still can't export the data of other users.
// It is called directly here, without any middleware, and with a Graph that
// has no gateway: a request that got past the check would panic.
func TestExportPersonalDataRejectsOtherUsersWithoutMiddleware(t *testing.T) {
logger := log.NopLogger()
g := Graph{BaseGraphService: BaseGraphService{logger: &logger}}
for _, tc := range []struct {
name string
user string
urlUser string
}{
{name: "other user", user: "alice", urlUser: "bob"},
{name: "invalid escape", user: "alice", urlUser: "al%zzce"},
{name: "user without an id and no user id in the URL", user: "", urlUser: ""},
} {
t.Run(tc.name, func(t *testing.T) {
rctx := chi.NewRouteContext()
rctx.URLParams.Add("userID", tc.urlUser)
ctx := context.WithValue(context.Background(), chi.RouteCtxKey, rctx)
ctx = revactx.ContextSetUser(ctx, &userv1beta1.User{Id: &userv1beta1.UserId{OpaqueId: tc.user}})
rr := httptest.NewRecorder()
g.ExportPersonalData(rr, httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx))
assert.Equal(t, http.StatusBadRequest, rr.Code)
})
}
}
@@ -0,0 +1,140 @@
package svc_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
revactx "github.com/opencloud-eu/reva/v2/pkg/ctx"
"github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool"
cs3mocks "github.com/opencloud-eu/reva/v2/tests/cs3mocks/mocks"
"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc"
"github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/pkg/shared"
"github.com/opencloud-eu/opencloud/services/graph/mocks"
"github.com/opencloud-eu/opencloud/services/graph/pkg/config"
"github.com/opencloud-eu/opencloud/services/graph/pkg/config/defaults"
"github.com/opencloud-eu/opencloud/services/graph/pkg/metrics"
service "github.com/opencloud-eu/opencloud/services/graph/pkg/service/v0"
)
var _ = Describe("ExportPersonalData", func() {
var (
cfg *config.Config
ctx context.Context
)
newService := func() service.Service {
pool.RemoveSelector("GatewaySelector" + "eu.opencloud.api.gateway")
gatewayClient := &cs3mocks.GatewayAPIClient{}
gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"eu.opencloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return gatewayClient
},
)
logger := log.NewLogger()
metrics, _ := metrics.New(prometheus.NewRegistry(), &logger, func([]string) (string, string) { return "", "" })
svc, err := service.NewService(
service.Config(cfg),
service.Metrics(metrics),
service.WithGatewaySelector(gatewaySelector),
service.EventsPublisher(&mocks.Publisher{}),
service.PermissionService(&mocks.Permissions{}),
)
Expect(err).ToNot(HaveOccurred())
return svc
}
// export sends an export request for the user with the given id. The
// storage location has an unsupported file extension, so that a request
// that reaches the handler fails right away, with a response that differs
// from those of the middlewares in front of it.
export := func(svc service.Service, path string) *httptest.ResponseRecorder {
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"storageLocation": "/export.txt"}`))
r = r.WithContext(ctx)
rr := httptest.NewRecorder()
svc.ServeHTTP(rr, r)
return rr
}
reachedHandler := func(rr *httptest.ResponseRecorder) bool {
return rr.Code == http.StatusBadRequest && strings.Contains(rr.Body.String(), "only json format")
}
BeforeEach(func() {
ctx = revactx.ContextSetUser(context.Background(), &userv1beta1.User{
Id: &userv1beta1.UserId{OpaqueId: "alice"},
})
cfg = defaults.FullDefaultConfig()
cfg.Identity.LDAP.CACert = ""
cfg.TokenManager.JWTSecret = "loremipsum"
cfg.Commons = &shared.Commons{}
cfg.GRPCClientTLS = &shared.GRPCClientTLS{}
cfg.API.ExportPersonalDataRateLimit = 2
})
It("rejects exports for other users", func() {
svc := newService()
rr := export(svc, "/graph/v1.0/users/bob/exportPersonalData")
Expect(rr.Code).To(Equal(http.StatusBadRequest))
Expect(reachedHandler(rr)).To(BeFalse())
})
It("limits the exports of a user, also when the path varies", func() {
svc := newService()
Expect(reachedHandler(export(svc, "/graph/v1.0/users/alice/exportPersonalData"))).To(BeTrue())
Expect(reachedHandler(export(svc, "/graph/v1.0/users/alice/exportPersonalData/"))).To(BeTrue())
Expect(export(svc, "/graph/v1.0/users/al%69ce/exportPersonalData").Code).To(Equal(http.StatusTooManyRequests))
})
It("answers beyond the limit in the error format of graph, with Retry-After", func() {
svc := newService()
export(svc, "/graph/v1.0/users/alice/exportPersonalData")
export(svc, "/graph/v1.0/users/alice/exportPersonalData")
rr := export(svc, "/graph/v1.0/users/alice/exportPersonalData")
Expect(rr.Code).To(Equal(http.StatusTooManyRequests))
Expect(rr.Header().Get("Retry-After")).ToNot(BeEmpty())
var body struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
Expect(json.Unmarshal(rr.Body.Bytes(), &body)).To(Succeed())
Expect(body.Error.Code).To(Equal("activityLimitReached"))
})
It("rejects requests for other users before they count against any limit", func() {
svc := newService()
for range 5 {
Expect(export(svc, "/graph/v1.0/users/bob/exportPersonalData").Code).To(Equal(http.StatusBadRequest))
}
// alice still has her whole budget
Expect(reachedHandler(export(svc, "/graph/v1.0/users/alice/exportPersonalData"))).To(BeTrue())
Expect(reachedHandler(export(svc, "/graph/v1.0/users/alice/exportPersonalData"))).To(BeTrue())
// and so has bob
ctx = revactx.ContextSetUser(context.Background(), &userv1beta1.User{
Id: &userv1beta1.UserId{OpaqueId: "bob"},
})
Expect(reachedHandler(export(svc, "/graph/v1.0/users/bob/exportPersonalData"))).To(BeTrue())
Expect(reachedHandler(export(svc, "/graph/v1.0/users/bob/exportPersonalData"))).To(BeTrue())
})
It("doesn't limit the exports when the limit is 0", func() {
cfg.API.ExportPersonalDataRateLimit = 0
svc := newService()
for range 5 {
Expect(reachedHandler(export(svc, "/graph/v1.0/users/alice/exportPersonalData"))).To(BeTrue())
}
})
})
+12 -1
View File
@@ -18,6 +18,7 @@ import (
"github.com/opencloud-eu/reva/v2/pkg/bytesize"
"github.com/opencloud-eu/reva/v2/pkg/store"
ocmiddleware "github.com/opencloud-eu/opencloud/pkg/middleware"
"github.com/opencloud-eu/opencloud/pkg/roles"
"github.com/opencloud-eu/opencloud/pkg/service/grpc"
"github.com/opencloud-eu/opencloud/pkg/tracing"
@@ -345,7 +346,17 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx
r.Route("/{userID}", func(r chi.Router) {
r.Get("/", svc.GetUser)
r.Get("/drive", svc.GetUserDrive)
r.Post("/exportPersonalData", svc.ExportPersonalData)
r.With(
// users may only export their own personal data, never
// that of another user; this comes before the rate
// limit, so that requests for other users are rejected
// without counting against anyone's limit
graphm.RequireOwnUserID("userID", options.Logger),
// every export collects all the data of the user and
// writes it into their personal space, which is
// expensive: limit how often a user can start one
ocmiddleware.RateLimitPerAuthenticatedUser(options.Config.API.ExportPersonalDataRateLimit, time.Minute, exportPersonalDataLimitReached),
).Post("/exportPersonalData", svc.ExportPersonalData)
r.Post("/teamwork/sendActivityNotification", svc.SendActivityNotification)
r.Route("/photo/$value", func(r chi.Router) {
r.Get("/", usersUserProfilePhotoApi.GetProfilePhoto(GetSlugValue("userID")))
+20
View File
@@ -0,0 +1,20 @@
Copyright (c) 2015-present Peter Kieltyka (https://github.com/pkieltyka).
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+264
View File
@@ -0,0 +1,264 @@
# httprate - HTTP Rate Limiter
![CI workflow](https://github.com/go-chi/httprate/actions/workflows/ci.yml/badge.svg)
![Benchmark workflow](https://github.com/go-chi/httprate/actions/workflows/benchmark.yml/badge.svg)
[![GoDoc Widget]][GoDoc]
[GoDoc]: https://pkg.go.dev/github.com/go-chi/httprate
[GoDoc Widget]: https://godoc.org/github.com/go-chi/httprate?status.svg
`net/http` request rate limiter based on the Sliding Window Counter pattern inspired by
CloudFlare https://blog.cloudflare.com/counting-things-a-lot-of-different-things.
> [!WARNING]
> **Security: `LimitByRealIP` / `KeyByRealIP` / `WithKeyByRealIP` are deprecated.**
> They derive the rate-limit key from client-supplied headers (`True-Client-IP`,
> `X-Real-IP`, `X-Forwarded-For`) with no proxy-trust check, so a remote
> attacker can spoof the key — either rotating it to **evade** the limit or
> pinning it to a victim's IP to **lock that victim out** (HTTP 429). This is the
> same flaw fixed in chi's `middleware.RealIP` (see
> [GHSA-9g5q-2w5x-hmxf](https://github.com/go-chi/chi/security/advisories/GHSA-9g5q-2w5x-hmxf),
> [GHSA-rjr7-jggh-pgcp](https://github.com/go-chi/chi/security/advisories/GHSA-rjr7-jggh-pgcp),
> [GHSA-3fxj-6jh8-hvhx](https://github.com/go-chi/chi/security/advisories/GHSA-3fxj-6jh8-hvhx)).
> Rate-limit by a **trusted** client IP instead — see
> [Rate limit by client IP behind a proxy](#rate-limit-by-client-ip-behind-a-proxy).
The sliding window counter pattern is accurate, smooths traffic and offers a simple counter
design to share a rate-limit among a cluster of servers. For example, if you'd like
to use redis to coordinate a rate-limit across a group of microservices you just need
to implement the `httprate.LimitCounter` interface to support an atomic increment and get.
## Backends
- [x] Local in-memory backend (default)
- [x] Redis backend: https://github.com/go-chi/httprate-redis
## Example
```go
package main
import (
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/httprate"
)
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
// Enable httprate request limiter of 100 requests per minute, keyed by the
// client IP.
//
// There is no safe default IP source, so you state your trust model
// explicitly: one of chi's middleware.ClientIPFrom* middlewares (chi v5.3.0+)
// resolves the client IP, and the KeyFunc reads it back with
// middleware.GetClientIP. Pick the chi ClientIPFrom* that matches your
// deployment — here we assume the server is directly exposed to clients (no
// proxy), so the client IP is the TCP peer (RemoteAddr). Behind a reverse
// proxy or CDN, use ClientIPFromXFF / ClientIPFromHeader instead; see "Rate
// limit by client IP behind a proxy" below.
//
// httprate.CanonicalizeIP buckets IPv6 clients by their /64 so they can't
// rotate within it to win fresh buckets (see that section for why).
//
// To have a single rate-limiter for all requests, use a constant key:
// httprate.LimitBy(.., httprate.Key("*")).
//
// Please see _example/main.go for more, or read the library code.
r.Use(middleware.ClientIPFromRemoteAddr)
r.Use(httprate.LimitBy(100, time.Minute, func(r *http.Request) (string, error) {
return httprate.CanonicalizeIP(middleware.GetClientIP(r.Context())), nil
}))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("."))
})
http.ListenAndServe(":3333", r)
}
```
## Common use cases
### Rate limit by client IP behind a proxy
If your app runs behind a reverse proxy, load balancer, or CDN, the request's
`RemoteAddr` is the proxy, not the client. Resolving the real client IP safely
means deciding *which* hop to trust — there is no safe default, and trusting a
client-supplied header blindly is exactly the spoofing bug behind the deprecated
`LimitByRealIP`.
Use chi's [`middleware.ClientIPFrom*`](https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromXFF)
middlewares (chi `v5.3.0+`) to resolve a trusted client IP, then rate-limit by
it with a `LimitBy` `KeyFunc` that reads it back and canonicalizes it:
```go
import (
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/httprate"
)
// 1. Resolve a trusted client IP. Pick exactly ONE that matches your
// deployment (see the table below):
r.Use(middleware.ClientIPFromXFF("10.0.0.0/8"))
// 2. Rate-limit by that trusted client IP.
r.Use(httprate.LimitBy(100, time.Minute, clientIPKey))
// clientIPKey is the rate-limit key. middleware.GetClientIP reads the IP
// resolved in step 1; httprate.CanonicalizeIP buckets IPv6 clients by /64.
func clientIPKey(r *http.Request) (string, error) {
return httprate.CanonicalizeIP(middleware.GetClientIP(r.Context())), nil
}
```
> [!NOTE]
> `middleware.GetClientIP` returns the *full* client IP. Keying on it directly
> lets an IPv6 client rotate within its own `/64` (2^64 addresses via SLAAC) to
> get a fresh bucket per request and bypass the limit. `httprate.CanonicalizeIP`
> buckets IPv6 by `/64` (IPv4 unchanged) — copy its logic and widen the prefix
> (e.g. `/56`, `/48`) if your clients are delegated a larger block. The
> deprecated `KeyByIP` / `KeyByRealIP` did this canonicalization for you;
> `CanonicalizeIP` keeps it while making the trust model and prefix your choice.
Pick the one `ClientIPFrom*` middleware that matches how requests reach you:
| Your setup | Use |
| --- | --- |
| Directly on the public internet, no proxy | `middleware.ClientIPFromRemoteAddr` |
| Behind nginx (`X-Real-IP`), Cloudflare (`CF-Connecting-IP`), Apache (`X-Client-IP`) | `middleware.ClientIPFromHeader("X-Real-IP")` |
| Behind one or more proxies whose IP ranges you can list | `middleware.ClientIPFromXFF("10.0.0.0/8", ...)` |
| Behind a known, fixed number of proxies with dynamic IPs | `middleware.ClientIPFromXFFTrustedProxies(2)` |
See chi's [Choosing a ClientIP middleware](https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#hdr-Choosing_a_ClientIP_middleware)
for the full picker.
> [!IMPORTANT]
> If no `ClientIPFrom*` middleware is installed upstream, `middleware.GetClientIP`
> returns `""` and **every request shares a single global rate-limit bucket**.
> That's strictly more restrictive (not a security hole), but it's a footgun —
> you'll trip the limit after `requestLimit` total requests in dev. Make sure
> exactly one `ClientIPFrom*` middleware runs before the limiter.
A `KeyFunc` is just `func(r *http.Request) (string, error)`, so it isn't tied to
chi — read the client IP (or tenant/user ID) from wherever echo, fiber, gin, or
your own middleware stashes it on the request, and return it.
### Rate limit by IP and URL path (aka endpoint)
```go
// clientIPKey is the KeyFunc from "Rate limit by client IP behind a proxy" above.
r.Use(httprate.LimitBy(
10, // requests
10*time.Second, // per duration
httprate.JoinKeys(clientIPKey, httprate.KeyByEndpoint),
))
```
### Rate limit by arbitrary keys
```go
r.Use(httprate.LimitBy(
100,
time.Minute,
// an oversimplified example of rate limiting by a custom header
func(r *http.Request) (string, error) {
return r.Header.Get("X-Access-Token"), nil
},
))
```
### Rate limit by request payload
```go
// Rate-limiter for login endpoint.
loginRateLimiter := httprate.NewRateLimiter(5, time.Minute)
r.Post("/login", func(w http.ResponseWriter, r *http.Request) {
var payload struct {
Username string `json:"username"`
Password string `json:"password"`
}
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil || payload.Username == "" || payload.Password == "" {
w.WriteHeader(400)
return
}
// Rate-limit login at 5 req/min.
if loginRateLimiter.RespondOnLimit(w, r, payload.Username) {
return
}
w.Write([]byte("login at 5 req/min\n"))
})
```
### Send specific response for rate-limited requests
The default response is `HTTP 429` with `Too Many Requests` body. You can override it with:
```go
r.Use(httprate.LimitBy(
10,
time.Minute,
clientIPKey, // the KeyFunc from "Rate limit by client IP behind a proxy" above
httprate.WithLimitHandler(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, `{"error": "Rate-limited. Please, slow down."}`, http.StatusTooManyRequests)
}),
))
```
### Send specific response on errors
An error can be returned by:
- A custom key function provided by `httprate.WithKeyFunc(customKeyFn)`
- A custom backend provided by `httprateredis.WithRedisLimitCounter(customBackend)`
- The default local in-memory counter is guaranteed not return any errors
- Backends that fall-back to the local in-memory counter (e.g. [httprate-redis](https://github.com/go-chi/httprate-redis)) can choose not to return any errors either
```go
r.Use(httprate.LimitBy(
10,
time.Minute,
clientIPKey, // the KeyFunc from "Rate limit by client IP behind a proxy" above
httprate.WithErrorHandler(func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, fmt.Sprintf(`{"error": %q}`, err), http.StatusPreconditionRequired)
}),
httprate.WithLimitCounter(customBackend),
))
```
### Send custom response headers
```go
r.Use(httprate.LimitBy(
1000,
time.Minute,
clientIPKey, // the KeyFunc from "Rate limit by client IP behind a proxy" above
httprate.WithResponseHeaders(httprate.ResponseHeaders{
Limit: "X-RateLimit-Limit",
Remaining: "X-RateLimit-Remaining",
Reset: "X-RateLimit-Reset",
RetryAfter: "Retry-After",
Increment: "", // omit
}),
))
```
### Omit response headers
```go
r.Use(httprate.LimitBy(
1000,
time.Minute,
clientIPKey, // the KeyFunc from "Rate limit by client IP behind a proxy" above
httprate.WithResponseHeaders(httprate.ResponseHeaders{}),
))
```
## LICENSE
MIT
+32
View File
@@ -0,0 +1,32 @@
package httprate
import "context"
type ctxKey int
const (
incrementKey ctxKey = iota
requestLimitKey
)
func WithIncrement(ctx context.Context, value int) context.Context {
return context.WithValue(ctx, incrementKey, value)
}
func getIncrement(ctx context.Context) int {
if value, ok := ctx.Value(incrementKey).(int); ok {
return value
}
return 1
}
func WithRequestLimit(ctx context.Context, value int) context.Context {
return context.WithValue(ctx, requestLimitKey, value)
}
func getRequestLimit(ctx context.Context) int {
if value, ok := ctx.Value(requestLimitKey).(int); ok {
return value
}
return 0
}
+150
View File
@@ -0,0 +1,150 @@
package httprate
import (
"net"
"net/http"
"strings"
"time"
)
// This file collects the deprecated public surface in one place. These are kept
// for backward compatibility and still compile/behave as before, but new code
// should migrate to the replacements called out in each doc comment. httprate
// has not reached a stable v1, so a future major release may remove them.
// Deprecated: Use LimitBy(requestLimit, windowLength, keyFn, options...) instead,
// which makes the rate-limit key an explicit, required argument rather than an
// optional WithKeyFuncs. Pass the key function directly (e.g. a KeyFunc that
// reads a trusted client IP — see CanonicalizeIP), or httprate.Key("*") for a
// single global bucket. The remaining options
// (WithLimitCounter, WithLimitHandler, WithResponseHeaders, ...) carry over
// unchanged as LimitBy's trailing variadic.
func Limit(requestLimit int, windowLength time.Duration, options ...Option) func(next http.Handler) http.Handler {
// Key("*") is the default key; any WithKeyFuncs in options overrides it.
return LimitBy(requestLimit, windowLength, Key("*"), options...)
}
// Deprecated: Use LimitBy(requestLimit, windowLength, Key("*")) instead — a
// single global rate-limit bucket keyed by a constant. (LimitAll already keys
// every request by "*" under the hood; this just makes that explicit.)
func LimitAll(requestLimit int, windowLength time.Duration) func(next http.Handler) http.Handler {
return LimitBy(requestLimit, windowLength, Key("*"))
}
// Deprecated: LimitByIP keys off r.RemoteAddr (see KeyByIP). It is not
// spoofable, but behind a reverse proxy, load balancer, or CDN r.RemoteAddr is
// the proxy's address, so every client sharing that proxy lands in one bucket —
// usually the wrong key in production. State your trust model explicitly:
// install one of chi's middleware.ClientIPFrom* middlewares (chi v5.3.0+) and
// key off the resolved IP (CanonicalizeIP buckets IPv6 by /64):
//
// // Directly exposed to clients (LimitByIP's exact behavior, made explicit):
// r.Use(middleware.ClientIPFromRemoteAddr)
// r.Use(httprate.LimitBy(requestLimit, windowLength, func(r *http.Request) (string, error) {
// return httprate.CanonicalizeIP(middleware.GetClientIP(r.Context())), nil
// }))
func LimitByIP(requestLimit int, windowLength time.Duration) func(next http.Handler) http.Handler {
return LimitBy(requestLimit, windowLength, KeyByIP)
}
// Deprecated: LimitByRealIP is built on the spoofable KeyByRealIP and lets a
// remote attacker forge the rate-limit key — see GHSA-9g5q-2w5x-hmxf,
// GHSA-rjr7-jggh-pgcp, GHSA-3fxj-6jh8-hvhx for the equivalent flaw in chi's
// middleware.RealIP. Install one of chi's middleware.ClientIPFrom* middlewares
// (chi v5.3.0+) and key off the resolved IP instead (CanonicalizeIP buckets
// IPv6 by /64):
//
// r.Use(middleware.ClientIPFromXFF("10.0.0.0/8"))
// r.Use(httprate.LimitBy(requestLimit, windowLength, func(r *http.Request) (string, error) {
// return httprate.CanonicalizeIP(middleware.GetClientIP(r.Context())), nil
// }))
func LimitByRealIP(requestLimit int, windowLength time.Duration) func(next http.Handler) http.Handler {
return LimitBy(requestLimit, windowLength, KeyByRealIP)
}
// Deprecated: KeyByRealIP trusts the client-supplied True-Client-IP,
// X-Real-IP, and X-Forwarded-For headers without verifying any proxy chain, so
// a remote attacker can forge the rate-limit key — see GHSA-9g5q-2w5x-hmxf,
// GHSA-rjr7-jggh-pgcp, GHSA-3fxj-6jh8-hvhx for the equivalent flaw in chi's
// middleware.RealIP. On a rate-limiter this is two-sided: an attacker can evade
// the limit by rotating the spoofed header (unbounded buckets) or lock a victim
// out by pinning the header to the victim's IP (exhausting their bucket).
//
// Install one of chi's middleware.ClientIPFrom* middlewares (chi v5.3.0+) and
// key off the resolved IP instead (CanonicalizeIP buckets IPv6 by /64):
//
// r.Use(middleware.ClientIPFromXFF("10.0.0.0/8"))
// r.Use(httprate.LimitBy(100, time.Minute, func(r *http.Request) (string, error) {
// return httprate.CanonicalizeIP(middleware.GetClientIP(r.Context())), nil
// }))
func KeyByRealIP(r *http.Request) (string, error) {
var ip string
if tcip := r.Header.Get("True-Client-IP"); tcip != "" {
ip = tcip
} else if xrip := r.Header.Get("X-Real-IP"); xrip != "" {
ip = xrip
} else if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
i := strings.Index(xff, ", ")
if i == -1 {
i = len(xff)
}
ip = xff[:i]
} else {
var err error
ip, _, err = net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
}
return CanonicalizeIP(ip), nil
}
// Deprecated: WithKeyByRealIP installs the spoofable KeyByRealIP and lets a
// remote attacker forge the rate-limit key — see GHSA-9g5q-2w5x-hmxf,
// GHSA-rjr7-jggh-pgcp, GHSA-3fxj-6jh8-hvhx for the equivalent flaw in chi's
// middleware.RealIP. Install one of chi's middleware.ClientIPFrom* middlewares
// (chi v5.3.0+) and key off the resolved IP with LimitBy instead (see
// CanonicalizeIP).
func WithKeyByRealIP() Option {
return WithKeyFuncs(KeyByRealIP)
}
// Deprecated: KeyByIP keys off r.RemoteAddr, the TCP peer that opened the
// connection. Unlike KeyByRealIP it is NOT spoofable (RemoteAddr is set by
// net/http, never from a header) — but behind a reverse proxy, load balancer,
// or CDN, r.RemoteAddr is the proxy's address, so every client sharing that
// proxy lands in one rate-limit bucket. That's usually the wrong key in
// production, and there is no safe default IP source.
//
// State your trust model explicitly with one of chi's middleware.ClientIPFrom*
// middlewares (chi v5.3.0+) and key off the resolved IP (CanonicalizeIP buckets
// IPv6 by /64):
//
// // Directly exposed to clients (KeyByIP's exact behavior, made explicit):
// r.Use(middleware.ClientIPFromRemoteAddr)
// r.Use(httprate.LimitBy(100, time.Minute, func(r *http.Request) (string, error) {
// return httprate.CanonicalizeIP(middleware.GetClientIP(r.Context())), nil
// }))
//
// // Behind a proxy: use ClientIPFromXFF / ClientIPFromHeader / ... instead.
//
// KeyByIP returns the IPv4 address unchanged, or the /64 prefix for IPv6.
func KeyByIP(r *http.Request) (string, error) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
return CanonicalizeIP(ip), nil
}
// Deprecated: WithKeyByIP installs KeyByIP, which keys off r.RemoteAddr — the
// proxy's address behind a reverse proxy, load balancer, or CDN, and usually
// the wrong key in production (see KeyByIP). It is not a spoofing issue, but
// there is no safe default IP source. State your trust model explicitly:
// install one of chi's middleware.ClientIPFrom* middlewares (chi v5.3.0+) and
// key off the resolved IP with LimitBy instead (see CanonicalizeIP).
func WithKeyByIP() Option {
return WithKeyFuncs(KeyByIP)
}
+168
View File
@@ -0,0 +1,168 @@
package httprate
import (
"net"
"net/http"
"strings"
"time"
)
// LimitBy is the canonical entry point for rate-limiting by an explicit key.
//
// It is shorthand for Limit with keyFn installed as the rate-limit key. The
// key is a required positional argument, so every call site has to state, on
// purpose, what it rate-limits by.
//
// To rate-limit by a trusted client IP behind a proxy, resolve the IP with one
// of chi's middleware.ClientIPFrom* middlewares (chi v5.3.0+) and read it back
// in the KeyFunc; CanonicalizeIP buckets IPv6 clients by their /64:
//
// r.Use(middleware.ClientIPFromXFF("10.0.0.0/8"))
// r.Use(httprate.LimitBy(100, time.Minute, func(r *http.Request) (string, error) {
// return httprate.CanonicalizeIP(middleware.GetClientIP(r.Context())), nil
// }))
//
// Use JoinKeys to rate-limit by more than one dimension at once:
//
// r.Use(httprate.LimitBy(100, time.Minute,
// httprate.JoinKeys(clientIPKey, httprate.KeyByEndpoint)))
func LimitBy(requestLimit int, windowLength time.Duration, keyFn KeyFunc, options ...Option) func(next http.Handler) http.Handler {
return NewRateLimiter(requestLimit, windowLength, append([]Option{WithKeyFuncs(keyFn)}, options...)...).Handler
}
type KeyFunc func(r *http.Request) (string, error)
type Option func(rl *RateLimiter)
// Set custom response headers. If empty, the header is omitted.
type ResponseHeaders struct {
Limit string // Default: X-RateLimit-Limit
Remaining string // Default: X-RateLimit-Remaining
Increment string // Default: X-RateLimit-Increment
Reset string // Default: X-RateLimit-Reset
RetryAfter string // Default: Retry-After
}
func Key(key string) func(r *http.Request) (string, error) {
return func(r *http.Request) (string, error) {
return key, nil
}
}
// CanonicalizeIP normalizes a client IP string for use as a rate-limit key:
//
// - IPv4 addresses are returned unchanged. IPv4 mapped IPv6 addresses use
// their dotted IPv4 form.
// - IPv6 addresses are reduced to their /64 prefix. An IPv6 client typically
// controls a whole /64 (2^64 addresses via SLAAC), so keying on the full
// address would let it rotate within its own /64 to win a fresh bucket per
// request and bypass a per-IP limit. Widen/narrow the prefix yourself if your
// clients are delegated a larger block (e.g. a /56 or /48).
// - Any other string, including "", is returned unchanged.
//
// httprate stays router-agnostic, so it does not resolve the client IP for you —
// pair CanonicalizeIP with whatever does. With chi's middleware.ClientIPFrom*
// (chi v5.3.0+) and middleware.GetClientIP:
//
// r.Use(middleware.ClientIPFromXFF("10.0.0.0/8"))
// r.Use(httprate.LimitBy(100, time.Minute, func(r *http.Request) (string, error) {
// return httprate.CanonicalizeIP(middleware.GetClientIP(r.Context())), nil
// }))
//
// WARNING: if the resolver returns "" (e.g. no ClientIPFrom* middleware is
// installed upstream), CanonicalizeIP returns "" and every request shares a
// single global rate-limit bucket. Strictly more restrictive, but a footgun —
// make sure the client IP is actually resolved upstream.
func CanonicalizeIP(ip string) string {
isIPv6 := false
// This is how net.ParseIP decides if an address is IPv6
// https://cs.opensource.google/go/go/+/refs/tags/go1.17.7:src/net/ip.go;l=704
for i := 0; !isIPv6 && i < len(ip); i++ {
switch ip[i] {
case '.':
// IPv4
return ip
case ':':
// IPv6
isIPv6 = true
}
}
if !isIPv6 {
// Not an IP address at all
return ip
}
ipv6 := net.ParseIP(ip)
if ipv6 == nil {
return ip
}
if ipv4 := ipv6.To4(); ipv4 != nil {
return ipv4.String()
}
return ipv6.Mask(net.CIDRMask(64, 128)).String()
}
func KeyByEndpoint(r *http.Request) (string, error) {
return r.URL.Path, nil
}
func WithKeyFuncs(keyFuncs ...KeyFunc) Option {
return func(rl *RateLimiter) {
if len(keyFuncs) > 0 {
rl.keyFn = JoinKeys(keyFuncs...)
}
}
}
func WithLimitHandler(h http.HandlerFunc) Option {
return func(rl *RateLimiter) {
rl.onRateLimited = h
}
}
func WithErrorHandler(h func(http.ResponseWriter, *http.Request, error)) Option {
return func(rl *RateLimiter) {
rl.onError = h
}
}
func WithLimitCounter(c LimitCounter) Option {
return func(rl *RateLimiter) {
rl.limitCounter = c
}
}
func WithResponseHeaders(headers ResponseHeaders) Option {
return func(rl *RateLimiter) {
rl.headers = headers
}
}
func WithNoop() Option {
return func(rl *RateLimiter) {}
}
// JoinKeys joins the results of several KeyFuncs into a single key with ":"
// separators, so they can be passed to LimitBy's positional key slot for
// multi-dimensional rate-limiting:
//
// r.Use(httprate.LimitBy(100, time.Minute,
// httprate.JoinKeys(clientIPKey, httprate.KeyByEndpoint)))
//
// where clientIPKey is your own client-IP KeyFunc (see LimitBy and
// CanonicalizeIP). It is the positional-argument equivalent of WithKeyFuncs. If any component
// KeyFunc returns an error, the joined key returns that error.
func JoinKeys(fns ...KeyFunc) KeyFunc {
return func(r *http.Request) (string, error) {
var key strings.Builder
for i := 0; i < len(fns); i++ {
k, err := fns[i](r)
if err != nil {
return "", err
}
key.WriteString(k)
key.WriteRune(':')
}
return key.String(), nil
}
}
+15
View File
@@ -0,0 +1,15 @@
package httprate
import (
"strconv"
"time"
"github.com/zeebo/xxh3"
)
func LimitCounterKey(key string, window time.Time) uint64 {
h := xxh3.New()
h.WriteString(key)
h.WriteString(strconv.FormatInt(window.Unix(), 10))
return h.Sum64()
}
+196
View File
@@ -0,0 +1,196 @@
package httprate
import (
"math"
"net/http"
"strconv"
"sync"
"time"
)
type LimitCounter interface {
Config(requestLimit int, windowLength time.Duration)
Increment(key string, currentWindow time.Time) error
IncrementBy(key string, currentWindow time.Time, amount int) error
Get(key string, currentWindow, previousWindow time.Time) (int, int, error)
}
func NewRateLimiter(requestLimit int, windowLength time.Duration, options ...Option) *RateLimiter {
rl := &RateLimiter{
requestLimit: requestLimit,
windowLength: windowLength,
headers: ResponseHeaders{
Limit: "X-RateLimit-Limit",
Remaining: "X-RateLimit-Remaining",
Increment: "X-RateLimit-Increment",
Reset: "X-RateLimit-Reset",
RetryAfter: "Retry-After",
},
}
for _, opt := range options {
opt(rl)
}
if rl.keyFn == nil {
rl.keyFn = Key("*")
}
if rl.limitCounter == nil {
// Align windows to this limiter's start instant, not the wall clock, so resets
// spread out instead of all snapping to the same instant (e.g. the exact second).
// Safe only in-process; custom counters (e.g. Redis) stay wall-clock-aligned.
start := time.Now().UTC()
rl.windowOffset = start.Sub(start.Truncate(windowLength))
rl.limitCounter = NewLocalLimitCounter(windowLength)
} else {
rl.limitCounter.Config(requestLimit, windowLength)
}
if rl.onRateLimited == nil {
rl.onRateLimited = onRateLimited
}
if rl.onError == nil {
rl.onError = onError
}
return rl
}
type RateLimiter struct {
requestLimit int
windowLength time.Duration
windowOffset time.Duration
keyFn KeyFunc
limitCounter LimitCounter
onRateLimited http.HandlerFunc
onError func(http.ResponseWriter, *http.Request, error)
headers ResponseHeaders
mu sync.Mutex
}
// OnLimit checks the rate limit for the given key and updates the response headers accordingly.
// If the limit is reached, it returns true, indicating that the request should be halted. Otherwise,
// it increments the request count and returns false. This method does not send an HTTP response,
// so the caller must handle the response themselves or use the RespondOnLimit() method instead.
func (l *RateLimiter) OnLimit(w http.ResponseWriter, r *http.Request, key string) bool {
currentWindow := l.currentWindow(time.Now().UTC())
ctx := r.Context()
limit := l.requestLimit
if val := getRequestLimit(ctx); val > 0 {
limit = val
}
setHeader(w, l.headers.Limit, strconv.Itoa(limit))
setHeader(w, l.headers.Reset, strconv.FormatInt(currentWindow.Add(l.windowLength).Unix(), 10))
l.mu.Lock()
_, rateFloat, err := l.calculateRate(key, limit)
if err != nil {
l.mu.Unlock()
l.onError(w, r, err)
return true
}
rate := int(math.Round(rateFloat))
increment := getIncrement(r.Context())
if increment > 1 {
setHeader(w, l.headers.Increment, strconv.Itoa(increment))
}
if rate+increment > limit {
setHeader(w, l.headers.Remaining, strconv.Itoa(limit-rate))
l.mu.Unlock()
setHeader(w, l.headers.RetryAfter, strconv.Itoa(int(l.windowLength.Seconds()))) // RFC 6585
return true
}
err = l.limitCounter.IncrementBy(key, currentWindow, increment)
if err != nil {
l.mu.Unlock()
l.onError(w, r, err)
return true
}
l.mu.Unlock()
setHeader(w, l.headers.Remaining, strconv.Itoa(limit-rate-increment))
return false
}
// RespondOnLimit checks the rate limit for the given key and updates the response headers accordingly.
// If the limit is reached, it automatically sends an HTTP response and returns true, signaling the
// caller to halt further request processing. If the limit is not reached, it increments the request
// count and returns false, allowing the request to proceed.
func (l *RateLimiter) RespondOnLimit(w http.ResponseWriter, r *http.Request, key string) bool {
onLimit := l.OnLimit(w, r, key)
if onLimit {
l.onRateLimited(w, r)
}
return onLimit
}
func (l *RateLimiter) Counter() LimitCounter {
return l.limitCounter
}
func (l *RateLimiter) Status(key string) (bool, float64, error) {
return l.calculateRate(key, l.requestLimit)
}
func (l *RateLimiter) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key, err := l.keyFn(r)
if err != nil {
l.onError(w, r, err)
return
}
if l.RespondOnLimit(w, r, key) {
return
}
next.ServeHTTP(w, r)
})
}
// currentWindow returns the start of the rate-limit window containing t, aligned
// to windowOffset rather than the wall clock. When windowOffset is zero this is a
// plain truncation. The result is always in (t-windowLength, t].
func (l *RateLimiter) currentWindow(t time.Time) time.Time {
return t.Add(-l.windowOffset).Truncate(l.windowLength).Add(l.windowOffset)
}
func (l *RateLimiter) calculateRate(key string, requestLimit int) (bool, float64, error) {
now := time.Now().UTC()
currentWindow := l.currentWindow(now)
previousWindow := currentWindow.Add(-l.windowLength)
currCount, prevCount, err := l.limitCounter.Get(key, currentWindow, previousWindow)
if err != nil {
return false, 0, err
}
diff := now.Sub(currentWindow)
rate := float64(prevCount)*(float64(l.windowLength)-float64(diff))/float64(l.windowLength) + float64(currCount)
if rate > float64(requestLimit) {
return false, rate, nil
}
return true, rate, nil
}
func setHeader(w http.ResponseWriter, key string, value string) {
if key != "" {
w.Header().Set(key, value)
}
}
func onRateLimited(w http.ResponseWriter, r *http.Request) {
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
}
func onError(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusPreconditionRequired)
}
+96
View File
@@ -0,0 +1,96 @@
package httprate
import (
"sync"
"time"
"github.com/zeebo/xxh3"
)
// NewLocalLimitCounter creates an instance of localCounter,
// which is an in-memory implementation of http.LimitCounter.
//
// All methods are guaranteed to always return nil error.
func NewLocalLimitCounter(windowLength time.Duration) *localCounter {
return &localCounter{
windowLength: windowLength,
latestWindow: time.Now().UTC(),
latestCounters: make(map[uint64]int),
previousCounters: make(map[uint64]int),
}
}
var _ LimitCounter = (*localCounter)(nil)
type localCounter struct {
windowLength time.Duration
latestWindow time.Time
latestCounters map[uint64]int
previousCounters map[uint64]int
mu sync.RWMutex
}
func (c *localCounter) IncrementBy(key string, currentWindow time.Time, amount int) error {
c.mu.Lock()
defer c.mu.Unlock()
c.evict(currentWindow)
hkey := limitCounterKey(key)
count, _ := c.latestCounters[hkey]
c.latestCounters[hkey] = count + amount
return nil
}
func (c *localCounter) Get(key string, currentWindow, previousWindow time.Time) (int, int, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if c.latestWindow == currentWindow {
curr, _ := c.latestCounters[limitCounterKey(key)]
prev, _ := c.previousCounters[limitCounterKey(key)]
return curr, prev, nil
}
if c.latestWindow == previousWindow {
prev, _ := c.latestCounters[limitCounterKey(key)]
return 0, prev, nil
}
return 0, 0, nil
}
func (c *localCounter) Config(requestLimit int, windowLength time.Duration) {
c.windowLength = windowLength
c.latestWindow = time.Now().UTC().Truncate(windowLength)
}
func (c *localCounter) Increment(key string, currentWindow time.Time) error {
return c.IncrementBy(key, currentWindow, 1)
}
func (c *localCounter) evict(currentWindow time.Time) {
if c.latestWindow == currentWindow {
return
}
previousWindow := currentWindow.Add(-c.windowLength)
if c.latestWindow == previousWindow {
c.latestWindow = currentWindow
// Shift the windows without map re-allocation.
clear(c.previousCounters)
c.latestCounters, c.previousCounters = c.previousCounters, c.latestCounters
return
}
c.latestWindow = currentWindow
clear(c.previousCounters)
clear(c.latestCounters)
}
func limitCounterKey(key string) uint64 {
return xxh3.HashString(key)
}
+3
View File
@@ -459,6 +459,9 @@ github.com/go-asn1-ber/asn1-ber
## explicit; go 1.24
github.com/go-chi/chi/v5
github.com/go-chi/chi/v5/middleware
# github.com/go-chi/httprate v0.16.1
## explicit; go 1.23.0
github.com/go-chi/httprate
# github.com/go-chi/render v1.0.3
## explicit; go 1.16
github.com/go-chi/render