Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add request to errHandler #48

Merged
merged 4 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ func (c *Client) validateAccessKey(access *proto.AccessKey, origin string) (err
if !access.ValidateOrigin(origin) {
return proto.ErrInvalidOrigin
}
if !access.ValidateService(&c.service) {
if !access.ValidateService(c.service) {
return proto.ErrInvalidService
}
return nil
Expand Down
242 changes: 242 additions & 0 deletions go.work.sum

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ func (h handler) GetDefaultAccessKey(ctx context.Context, projectID uint64) (*pr
return nil, proto.ErrNoDefaultKey
}

func (h handler) CreateAccessKey(ctx context.Context, projectID uint64, displayName string, allowedOrigins []string, allowedServices []*proto.Service) (*proto.AccessKey, error) {
func (h handler) CreateAccessKey(ctx context.Context, projectID uint64, displayName string, allowedOrigins []string, allowedServices []proto.Service) (*proto.AccessKey, error) {
cycle, err := h.store.CycleStore.GetAccessCycle(ctx, projectID, middleware.GetTime(ctx))
if err != nil {
return nil, err
Expand Down Expand Up @@ -367,7 +367,7 @@ func (h handler) RotateAccessKey(ctx context.Context, accessKey string) (*proto.
return newAccess, nil
}

func (h handler) UpdateAccessKey(ctx context.Context, accessKey string, displayName *string, allowedOrigins []string, allowedServices []*proto.Service) (*proto.AccessKey, error) {
func (h handler) UpdateAccessKey(ctx context.Context, accessKey string, displayName *string, allowedOrigins []string, allowedServices []proto.Service) (*proto.AccessKey, error) {
access, err := h.store.AccessKeyStore.FindAccessKey(ctx, accessKey)
if err != nil {
return nil, err
Expand Down
6 changes: 3 additions & 3 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ func TestDefaultKey(t *testing.T) {
proto.GenerateAccessKey(project),
}

service := proto.Ptr(proto.Service_Metadata)
service := proto.Service_Metadata
limit := proto.Limit{
RateLimit: 100,
FreeMax: 5,
Expand All @@ -302,7 +302,7 @@ func TestDefaultKey(t *testing.T) {
err = server.Store.InsertAccessKey(ctx, &proto.AccessKey{Active: true, AccessKey: keys[0], ProjectID: project})
require.NoError(t, err)

client := newQuotaClient(cfg, *service)
client := newQuotaClient(cfg, service)

aq, err := client.FetchKeyQuota(ctx, keys[0], "", now)
require.NoError(t, err)
Expand All @@ -314,7 +314,7 @@ func TestDefaultKey(t *testing.T) {
assert.Equal(t, access, aq.AccessKey)
assert.Equal(t, &limit, aq.Limit)

access, err = server.UpdateAccessKey(ctx, keys[0], proto.Ptr("new name"), nil, []*proto.Service{service})
access, err = server.UpdateAccessKey(ctx, keys[0], proto.Ptr("new name"), nil, []proto.Service{service})
require.NoError(t, err)

aq, err = client.FetchKeyQuota(ctx, keys[0], "", now)
Expand Down
2 changes: 1 addition & 1 deletion mem.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func (m *MemoryStore) ListAccessKeys(ctx context.Context, projectID uint64, acti
if active != nil && *active != v.Active {
continue
}
if service != nil && !v.ValidateService(service) {
if service != nil && !v.ValidateService(*service) {
continue
}
accessKeys = append(accessKeys, proto.Ptr(m.accessKeys[i]))
Expand Down
2 changes: 1 addition & 1 deletion middleware/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/0xsequence/quotacontrol/proto"
)

type ErrHandler func(w http.ResponseWriter, err error)
type ErrHandler func(r *http.Request, w http.ResponseWriter, err error)

// Client is the interface that wraps the basic FetchKeyQuota, GetUsage and SpendQuota methods.
type Client interface {
Expand Down
4 changes: 2 additions & 2 deletions middleware/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ func GetUser[T any](ctx context.Context) (T, bool) {
return v, ok
}

// withService adds the service to the context.
func withService(ctx context.Context, service string) context.Context {
// WithService adds the service to the context.
func WithService(ctx context.Context, service string) context.Context {
return context.WithValue(ctx, ctxKeyService, service)
}

Expand Down
20 changes: 12 additions & 8 deletions middleware/middleware_access.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,32 @@ import (
"github.com/0xsequence/quotacontrol/proto"
)

func defaultErrHandler(r *http.Request, w http.ResponseWriter, err error) {
proto.RespondWithError(w, err)
}

// AccessControl middleware that checks if the session type is allowed to access the endpoint.
// It also sets the compute units on the context if the endpoint requires it.
func AccessControl(acl ServiceConfig[ACL], cost ServiceConfig[int64], defaultCost int64, eh ErrHandler) func(next http.Handler) http.Handler {
if eh == nil {
eh = proto.RespondWithError
eh = defaultErrHandler
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
req := newRequest(r.URL.Path)
if req == nil {
eh(w, proto.ErrUnauthorized.WithCausef("invalid rpc method called"))
eh(r, w, proto.ErrUnauthorized.WithCausef("invalid rpc method called"))
return
}

types, ok := acl.GetConfig(req)
if !ok {
eh(w, proto.ErrUnauthorized.WithCausef("rpc method not found"))
eh(r, w, proto.ErrUnauthorized.WithCausef("rpc method not found"))
return
}

if session := GetSessionType(r.Context()); !types.Includes(session) {
eh(w, proto.ErrUnauthorized)
eh(r, w, proto.ErrUnauthorized)
return
}

Expand All @@ -47,7 +51,7 @@ func AccessControl(acl ServiceConfig[ACL], cost ServiceConfig[int64], defaultCos
// EnsurePermission middleware that checks if the session type has the required permission.
func EnsurePermission(client Client, minPermission proto.UserPermission, eh ErrHandler) func(next http.Handler) http.Handler {
if eh == nil {
eh = proto.RespondWithError
eh = defaultErrHandler
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -61,17 +65,17 @@ func EnsurePermission(client Client, minPermission proto.UserPermission, eh ErrH
// check if we alreayd have a project ID from the JWT
q, ok := GetAccessQuota(ctx)
if !ok || !q.IsJWT() {
eh(w, proto.ErrUnauthorizedUser)
eh(r, w, proto.ErrUnauthorizedUser)
return
}

ok, err := client.CheckPermission(ctx, q.GetProjectID(), minPermission)
if err != nil {
eh(w, proto.ErrUnauthorized.WithCause(err))
eh(r, w, proto.ErrUnauthorized.WithCause(err))
return
}
if !ok {
eh(w, proto.ErrUnauthorizedUser)
eh(r, w, proto.ErrUnauthorizedUser)
return
}

Expand Down
10 changes: 5 additions & 5 deletions middleware/middleware_ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ const (

type RLConfig struct {
Enabled bool `toml:"enabled"`
PublicRate int `toml:"public_rate"`
AccountRate int `toml:"account_rate"`
ServiceRate int `toml:"service_rate"`
PublicRate int `toml:"public_requests_per_minute"`
AccountRate int `toml:"user_requests_per_minute"`
ServiceRate int `toml:"service_requests_per_minute"`
ErrorMsg string `toml:"error_message"`
}

Expand All @@ -56,7 +56,7 @@ func RateLimit(rlCfg RLConfig, redisCfg redis.Config, eh ErrHandler) func(next h
}

if eh == nil {
eh = proto.RespondWithError
eh = defaultErrHandler
}

rlCfg.PublicRate = cmp.Or(rlCfg.PublicRate, DefaultPublicRate)
Expand Down Expand Up @@ -90,7 +90,7 @@ func RateLimit(rlCfg RLConfig, redisCfg redis.Config, eh ErrHandler) func(next h
return httprate.KeyByRealIP(r)
}),
httprate.WithLimitHandler(func(w http.ResponseWriter, r *http.Request) {
eh(w, proto.ErrLimitExceeded.WithMessage(rlCfg.ErrorMsg))
eh(r, w, proto.ErrLimitExceeded.WithMessage(rlCfg.ErrorMsg))
}),
}

Expand Down
2 changes: 1 addition & 1 deletion middleware/middleware_ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func TestRateLimiter(t *testing.T) {
Enabled: true,
PublicRate: 10,
ErrorMsg: _CustomErrorMessage,
}, redis.Config{}, func(w http.ResponseWriter, err error) {
}, redis.Config{}, func(r *http.Request, w http.ResponseWriter, err error) {
w.Header().Set(_TestHeader, _TestHeaderValue)
proto.RespondWithError(w, err)
})
Expand Down
26 changes: 13 additions & 13 deletions middleware/middleware_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ type UserStore interface {

func Session(client Client, auth *jwtauth.JWTAuth, u UserStore, eh ErrHandler, keyFuncs ...KeyFunc) func(next http.Handler) http.Handler {
if eh == nil {
eh = proto.RespondWithError
eh = defaultErrHandler
}
keyFuncs = append([]KeyFunc{KeyFromHeader}, keyFuncs...)
return func(next http.Handler) http.Handler {
Expand All @@ -50,11 +50,11 @@ func Session(client Client, auth *jwtauth.JWTAuth, u UserStore, eh ErrHandler, k
token, err := jwtauth.VerifyRequest(auth, r, jwtauth.TokenFromHeader, jwtauth.TokenFromCookie)
if err != nil {
if errors.Is(err, jwtauth.ErrExpired) {
eh(w, proto.ErrSessionExpired)
eh(r, w, proto.ErrSessionExpired)
return
}
if !errors.Is(err, jwtauth.ErrNoTokenFound) {
eh(w, proto.ErrUnauthorizedUser)
eh(r, w, proto.ErrUnauthorizedUser)
return
}
}
Expand All @@ -64,7 +64,7 @@ func Session(client Client, auth *jwtauth.JWTAuth, u UserStore, eh ErrHandler, k
if token != nil {
claims, err := token.AsMap(r.Context())
if err != nil {
eh(w, err)
eh(r, w, err)
return
}

Expand All @@ -74,7 +74,7 @@ func Session(client Client, auth *jwtauth.JWTAuth, u UserStore, eh ErrHandler, k
projectClaim, _ := claims["project"].(float64)
switch {
case serviceClaim != "":
ctx = withService(ctx, serviceClaim)
ctx = WithService(ctx, serviceClaim)
sessionType = proto.SessionType_Service
case accountClaim != "":
ctx = WithAccount(ctx, accountClaim)
Expand All @@ -83,7 +83,7 @@ func Session(client Client, auth *jwtauth.JWTAuth, u UserStore, eh ErrHandler, k
if u != nil {
user, isAdmin, err := u.GetUser(ctx, accountClaim)
if err != nil {
eh(w, err)
eh(r, w, err)
return
}
if user != nil {
Expand All @@ -104,16 +104,16 @@ func Session(client Client, auth *jwtauth.JWTAuth, u UserStore, eh ErrHandler, k
if projectClaim > 0 {
projectID := uint64(projectClaim)
if quota, err = client.FetchProjectQuota(ctx, projectID, now); err != nil {
eh(w, err)
eh(r, w, err)
return
}
ok, err := client.CheckPermission(ctx, projectID, proto.UserPermission_READ)
if err != nil {
eh(w, err)
eh(r, w, err)
return
}
if !ok {
eh(w, proto.ErrUnauthorizedUser)
eh(r, w, proto.ErrUnauthorizedUser)
return
}
ctx = withProjectID(ctx, projectID)
Expand All @@ -124,20 +124,20 @@ func Session(client Client, auth *jwtauth.JWTAuth, u UserStore, eh ErrHandler, k
if accessKey != "" && sessionType < proto.SessionType_Admin {
projectID, err := proto.GetProjectID(accessKey)
if err != nil {
eh(w, err)
eh(r, w, err)
return
}
if quota != nil && quota.GetProjectID() != projectID {
eh(w, proto.ErrAccessKeyMismatch)
eh(r, w, proto.ErrAccessKeyMismatch)
return
}
q, err := client.FetchKeyQuota(ctx, accessKey, r.Header.Get(HeaderOrigin), now)
if err != nil {
eh(w, err)
eh(r, w, err)
return
}
if q != nil && !q.IsActive() {
eh(w, proto.ErrAccessKeyNotFound)
eh(r, w, proto.ErrAccessKeyNotFound)
return
}
if quota == nil {
Expand Down
12 changes: 6 additions & 6 deletions middleware/middleware_usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const (
// EnsureUsage is a middleware that checks if the quota has enough usage left.
func EnsureUsage(client Client, eh ErrHandler) func(next http.Handler) http.Handler {
if eh == nil {
eh = proto.RespondWithError
eh = defaultErrHandler
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -42,15 +42,15 @@ func EnsureUsage(client Client, eh ErrHandler) func(next http.Handler) http.Hand

usage, err := client.FetchUsage(ctx, quota, GetTime(ctx))
if err != nil {
eh(w, err)
eh(r, w, err)
return
}
w.Header().Set(HeaderQuotaRemaining, strconv.FormatInt(max(quota.Limit.FreeMax-usage, 0), 10))
if overage := max(usage-quota.Limit.FreeMax, 0); overage > 0 {
w.Header().Set(HeaderQuotaOverage, strconv.FormatInt(overage, 10))
}
if usage+cu > quota.Limit.OverMax {
eh(w, proto.ErrLimitExceeded)
eh(r, w, proto.ErrLimitExceeded)
return
}

Expand All @@ -62,7 +62,7 @@ func EnsureUsage(client Client, eh ErrHandler) func(next http.Handler) http.Hand
// SpendUsage is a middleware that spends the usage from the quota.
func SpendUsage(client Client, eh ErrHandler) func(next http.Handler) http.Handler {
if eh == nil {
eh = proto.RespondWithError
eh = defaultErrHandler
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -91,7 +91,7 @@ func SpendUsage(client Client, eh ErrHandler) func(next http.Handler) http.Handl

ok, total, err := client.SpendQuota(ctx, quota, cu, GetTime(ctx))
if err != nil && !errors.Is(err, proto.ErrLimitExceeded) {
eh(w, err)
eh(r, w, err)
return
}

Expand All @@ -101,7 +101,7 @@ func SpendUsage(client Client, eh ErrHandler) func(next http.Handler) http.Handl
}

if errors.Is(err, proto.ErrLimitExceeded) {
eh(w, err)
eh(r, w, err)
return
}

Expand Down
8 changes: 4 additions & 4 deletions proto/clients/quotacontrol.gen.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
/* eslint-disable */
// quota-control v0.1.0 f2a67cbe9155481ee28a125495f9a21f68e04c8b
// quota-control v0.17.1 334a4ae5ccea445a69aa985874a2a7397f94a755
// --
// Code generated by webrpc-gen@v0.18.6 with [email protected] generator. DO NOT EDIT.
// Code generated by webrpc-gen@v0.20.3 with [email protected] generator. DO NOT EDIT.
//
// webrpc-gen -schema=proto.ridl [email protected] -client -out=./clients/quotacontrol.gen.ts

// WebRPC description and code-gen version
export const WebRPCVersion = "v1"

// Schema version of your RIDL schema
export const WebRPCSchemaVersion = "v0.1.0"
export const WebRPCSchemaVersion = "v0.17.1"

// Schema hash generated from your RIDL schema
export const WebRPCSchemaHash = "f2a67cbe9155481ee28a125495f9a21f68e04c8b"
export const WebRPCSchemaHash = "334a4ae5ccea445a69aa985874a2a7397f94a755"

//
// Types
Expand Down
Loading
Loading