Skip to content

Commit

Permalink
update to latest version
Browse files Browse the repository at this point in the history
  • Loading branch information
klaidliadon committed Oct 24, 2024
1 parent 176f0e8 commit 4d1b270
Show file tree
Hide file tree
Showing 18 changed files with 421 additions and 54 deletions.
1 change: 1 addition & 0 deletions .gitignore copy
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
coverage.out
88 changes: 88 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
linters:
# Disable all linters.
disable-all: true
# Enable specific linter
enable:
- errcheck
- gci
- wrapcheck
- ineffassign
- unused

run:
# Number of operating system threads (`GOMAXPROCS`) that can execute golangci-lint simultaneously.
# If it is explicitly set to 0 (i.e. not the default) then golangci-lint will automatically set the value to match Linux container CPU quota.
# Default: the number of logical CPUs in the machine
concurrency: 8
# Timeout for analysis, e.g. 30s, 5m.
# Default: 1m
timeout: 5m
go: '1.22.0'

output:
# Show statistics per linter.
show-stats: true
# Sort results by the order defined in `sort-order`.
sort-results: true
# Order to use when sorting results.
# Require `sort-results` to `true`.
# Possible values: `file`, `linter`, and `severity`.
#
# If the severity values are inside the following list, they are ordered in this order:
# 1. error
# 2. warning
# 3. high
# 4. medium
# 5. low
# Either they are sorted alphabetically.
sort-order:
- linter
- file
- severity

issues:
# Maximum issues count per one linter.
# Set to 0 to disable.
# Default: 50
max-issues-per-linter: 0
# Maximum count of issues with the same text.
# Set to 0 to disable.
# Default: 3
max-same-issues: 0
exclude-rules:
- linters:
- lll
source: "^//go:generate "
exclude-dirs:
- "tools"
exclude-files:
- ".*\\.gen\\.go$"
- ".*\\.ridl$"

linters-settings:
errcheck:
# List of functions to exclude from checking, where each entry is a single function to exclude.
# See https://github.com/kisielk/errcheck#excluding-functions for details.
exclude-functions:
- (net/http.ResponseWriter).Write

gci:
# Section configuration to compare against.
# Section names are case-insensitive and may contain parameters in ().
# The default order of sections is `standard > default > custom > blank > dot > alias > localmodule`,
# If `custom-order` is `true`, it follows the order of `sections` option.
# Default: ["standard", "default"]
sections:
- standard # Standard section: captures all standard packages.
- default # Default section: contains all imports that could not be matched to another section type.
- prefix(github.com/0xsequence/authcontrol) # Custom section: groups all imports with the specified Prefix.
# Skip generated files.
# Default: true
skip-generated: true
# Enable custom order of sections.
# If `true`, make the section order the same as the order of `sections`.
# Default: false
custom-order: true
# Drops lexical ordering for custom sections.
# Default: false
no-lex-order: false
36 changes: 26 additions & 10 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
GO_TEST = $(shell if ! command -v gotest &> /dev/null; then echo "go test"; else echo "gotest"; fi)
TEST_FLAGS ?= -p 8 -failfast -race -shuffle on

.PHONY: build
build:
go build ./...
all:
@echo "make <cmd>:"
@echo ""
@echo "commands:"
@awk -F'[ :]' '/^#+/ {comment=$$0; gsub(/^#+[ ]*/, "", comment)} !/^(_|all:)/ && /^([A-Za-z_-]+):/ && !seen[$$1]++ {printf " %-24s %s\n", $$1, (comment ? "- " comment : ""); comment=""} !/^#+/ {comment=""}' Makefile

.PHONY: proto
proto:
go generate ./proto
test-clean:
go clean -testcache

test: test-clean
go test -run=$(TEST) $(TEST_FLAGS) -json ./... | tparse --all --follow

test-rerun: test-clean
go run github.com/goware/rerun/cmd/rerun -watch ./ -run 'make test'

test-coverage:
go test -run=$(TEST) $(TEST_FLAGS) -cover -coverprofile=coverage.out -json ./... | tparse --all --follow

test-coverage-inspect: test-coverage
go tool cover -html=coverage.out

generate:
go generate -x ./...

lint:
golangci-lint run ./... --fix -c .golangci.yml

.PHONY: test
test:
go clean -testcache && $(GO_TEST) -v -p=1 ./...
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ module github.com/0xsequence/quotacontrol

go 1.23.2

replace github.com/0xsequence/authcontrol => ../authcontrol

require (
github.com/0xsequence/authcontrol v0.0.0-20241023152638-fd04748438df
github.com/0xsequence/authcontrol v0.0.0-20241024085703-b794f2b62444
github.com/0xsequence/go-sequence v0.43.0
github.com/alicebob/miniredis/v2 v2.33.0
github.com/go-chi/chi/v5 v5.1.0
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
github.com/0xsequence/authcontrol v0.0.0-20241023152638-fd04748438df h1:yCtCVbfXPmal2Kygm+KxnIw+xZ1a+YjTumAuQtkl418=
github.com/0xsequence/authcontrol v0.0.0-20241023152638-fd04748438df/go.mod h1:K1IlgXPaMZp7f+ZalS9vGax7f74Pwkd3wJjYN4QhyYA=
github.com/0xsequence/ethkit v1.28.0 h1:11p4UXXvYnixQk01+qmAcOF71N9DlSeMcEMbaCPtjaY=
github.com/0xsequence/ethkit v1.28.0/go.mod h1:rv0FAIyEyN0hhwGefbduAz4ujmyjyJXhCd6a0/yF3tk=
github.com/0xsequence/go-sequence v0.43.0 h1:PErMuTg4PeaamJutEJ6tAjrFBA8z0t6lvT9LOVC5RMs=
Expand Down
62 changes: 41 additions & 21 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,13 @@ func TestMiddlewareUseAccessKey(t *testing.T) {

counter := spendingCounter(0)

options := &authcontrol.Options{
KeyFuncs: []authcontrol.KeyFunc{middleware.KeyFromHeader},
}

r := chi.NewRouter()
r.Use(
authcontrol.Session(auth, nil, middleware.DefaultErrorHandler, middleware.KeyFromHeader),
authcontrol.Session(auth, options),
middleware.VerifyQuota(client, nil),
addCost(_credits*2).Middleware,
addCost(_credits*-1).Middleware,
Expand Down Expand Up @@ -361,8 +365,11 @@ func TestJWT(t *testing.T) {

r := chi.NewRouter()

options := &authcontrol.Options{
KeyFuncs: []authcontrol.KeyFunc{middleware.KeyFromHeader},
}
r.Use(
authcontrol.Session(auth, nil, nil, middleware.KeyFromHeader),
authcontrol.Session(auth, options),
middleware.VerifyQuota(client, nil),
middleware.EnsureUsage(client, nil),
middleware.SpendUsage(client, nil),
Expand Down Expand Up @@ -437,8 +444,11 @@ func TestJWTAccess(t *testing.T) {
client := newQuotaClient(cfg, service)

r := chi.NewRouter()
options := &authcontrol.Options{
KeyFuncs: []authcontrol.KeyFunc{middleware.KeyFromHeader},
}
r.Use(
authcontrol.Session(auth, nil, nil, middleware.KeyFromHeader),
authcontrol.Session(auth, options),
middleware.VerifyQuota(client, nil),
middleware.RateLimit(cfg.RateLimiter, cfg.Redis, nil),
middleware.EnsurePermission(client, UserPermission_READ_WRITE, nil),
Expand Down Expand Up @@ -542,9 +552,14 @@ func TestSession(t *testing.T) {
t.Cleanup(cleanup)
client := newQuotaClient(cfg, Service)

options := &authcontrol.Options{
KeyFuncs: []authcontrol.KeyFunc{middleware.KeyFromHeader},
UserStore: server.Store,
}

r := chi.NewRouter()
r.Use(
authcontrol.Session(auth, server.Store, nil, middleware.KeyFromHeader),
authcontrol.Session(auth, options),
middleware.VerifyQuota(client, nil),
authcontrol.AccessControl(ACL, nil),
middleware.RateLimit(cfg.RateLimiter, cfg.Redis, nil),
Expand All @@ -562,16 +577,16 @@ func TestSession(t *testing.T) {
AccessKey string
Session proto.SessionType
}{
// {Session: proto.SessionType_Public},
// {Session: proto.SessionType_Wallet},
{Session: proto.SessionType_Public},
{Session: proto.SessionType_Wallet},
{Session: proto.SessionType_AccessKey, AccessKey: AccessKey},
// {Session: proto.SessionType_Project},
// {Session: proto.SessionType_Project, AccessKey: AccessKey},
// {Session: proto.SessionType_User},
// {Session: proto.SessionType_Admin},
// {Session: proto.SessionType_Admin, AccessKey: AccessKey},
// {Session: proto.SessionType_Service},
// {Session: proto.SessionType_Service, AccessKey: AccessKey},
{Session: proto.SessionType_Project},
{Session: proto.SessionType_Project, AccessKey: AccessKey},
{Session: proto.SessionType_User},
{Session: proto.SessionType_Admin},
{Session: proto.SessionType_Admin, AccessKey: AccessKey},
{Session: proto.SessionType_Service},
{Session: proto.SessionType_Service, AccessKey: AccessKey},
}

var (
Expand Down Expand Up @@ -639,9 +654,14 @@ func TestSessionDisabled(t *testing.T) {
t.Cleanup(cleanup)
client := newQuotaClient(cfg, Service)

options := &authcontrol.Options{
KeyFuncs: []authcontrol.KeyFunc{middleware.KeyFromHeader},
UserStore: server.Store,
}

r := chi.NewRouter()
r.Use(
authcontrol.Session(auth, server.Store, nil, middleware.KeyFromHeader),
authcontrol.Session(auth, options),
middleware.VerifyQuota(client, nil),
middleware.RateLimit(cfg.RateLimiter, cfg.Redis, nil),
authcontrol.AccessControl(ACL, nil),
Expand All @@ -659,16 +679,16 @@ func TestSessionDisabled(t *testing.T) {
AccessKey string
Session proto.SessionType
}{
{Session: proto.SessionType_Public},
{Session: proto.SessionType_Wallet},
// {Session: proto.SessionType_Public},
// {Session: proto.SessionType_Wallet},
{Session: proto.SessionType_AccessKey, AccessKey: AccessKey},
{Session: proto.SessionType_Project},
{Session: proto.SessionType_Project, AccessKey: AccessKey},
{Session: proto.SessionType_User},
{Session: proto.SessionType_Admin},
{Session: proto.SessionType_Admin, AccessKey: AccessKey},
{Session: proto.SessionType_Service},
{Session: proto.SessionType_Service, AccessKey: AccessKey},
// {Session: proto.SessionType_User},
// {Session: proto.SessionType_Admin},
// {Session: proto.SessionType_Admin, AccessKey: AccessKey},
// {Session: proto.SessionType_Service},
// {Session: proto.SessionType_Service, AccessKey: AccessKey},
}

var (
Expand Down
2 changes: 1 addition & 1 deletion middleware/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const (
HeaderOrigin = "Origin"
)

func DefaultErrorHandler(r *http.Request, w http.ResponseWriter, err error) {
func errHandler(r *http.Request, w http.ResponseWriter, err error) {
rpcErr, ok := err.(proto.WebRPCError)
if !ok {
rpcErr = proto.ErrWebrpcEndpoint.WithCause(err)
Expand Down
2 changes: 1 addition & 1 deletion middleware/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func GetAccessQuota(ctx context.Context) (*proto.AccessQuota, bool) {
// GetProjectID returns the projectID and if its active from the context.
// In case its not set, it will return 0.
func GetProjectID(ctx context.Context) (uint64, bool) {
if v, ok := authcontrol.GetProjectID(ctx); ok {
if v, ok := authcontrol.GetProject(ctx); ok {
return v, true
}
if q, ok := GetAccessQuota(ctx); ok {
Expand Down
6 changes: 3 additions & 3 deletions middleware/middleware_cost.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import (
"github.com/0xsequence/authcontrol"
)

// SetCost
func SetCost(defaultCost int64, cost authcontrol.Config[int64]) func(next http.Handler) http.Handler {
// SetCost middleware that sets the cost of the request.
func SetCost(base int64, cost authcontrol.Config[int64]) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
credits := defaultCost
credits := base
if v, ok := cost.Get(authcontrol.ParseRequest(r.URL.Path)); ok {
credits = v
}
Expand Down
2 changes: 1 addition & 1 deletion middleware/middleware_permission.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
// EnsurePermission middleware that checks if the session type has the required permission.
func EnsurePermission(client Client, minPermission proto.UserPermission, eh authcontrol.ErrHandler) func(next http.Handler) http.Handler {
if eh == nil {
eh = DefaultErrorHandler
eh = errHandler
}

return func(next http.Handler) http.Handler {
Expand Down
4 changes: 2 additions & 2 deletions middleware/middleware_quota.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

func VerifyQuota(client Client, eh authcontrol.ErrHandler) func(next http.Handler) http.Handler {
if eh == nil {
eh = DefaultErrorHandler
eh = errHandler
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -25,7 +25,7 @@ func VerifyQuota(client Client, eh authcontrol.ErrHandler) func(next http.Handle
)

if session == proto.SessionType_Project {
id, ok := authcontrol.GetProjectID(ctx)
id, ok := authcontrol.GetProject(ctx)
if !ok {
eh(r, w, proto.ErrUnauthorizedUser)
return
Expand Down
5 changes: 4 additions & 1 deletion middleware/middleware_ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func RateLimit(rlCfg RLConfig, redisCfg redis.Config, eh authcontrol.ErrHandler)
}

if eh == nil {
eh = DefaultErrorHandler
eh = errHandler
}

rlCfg.PublicRate = cmp.Or(rlCfg.PublicRate, DefaultPublicRate)
Expand Down Expand Up @@ -97,6 +97,9 @@ func RateLimit(rlCfg RLConfig, redisCfg redis.Config, eh authcontrol.ErrHandler)
if _, ok := authcontrol.GetService(ctx); ok {
return "", nil
}
if project, ok := GetProjectID(ctx); ok {
return ProjectRateKey(project), nil
}
if q, ok := GetAccessQuota(ctx); ok {
return ProjectRateKey(q.GetProjectID()), nil
}
Expand Down
4 changes: 2 additions & 2 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 authcontrol.ErrHandler) func(next http.Handler) http.Handler {
if eh == nil {
eh = DefaultErrorHandler
eh = errHandler
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -67,7 +67,7 @@ func EnsureUsage(client Client, eh authcontrol.ErrHandler) func(next http.Handle
// SpendUsage is a middleware that spends the usage from the quota.
func SpendUsage(client Client, eh authcontrol.ErrHandler) func(next http.Handler) http.Handler {
if eh == nil {
eh = DefaultErrorHandler
eh = errHandler
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
2 changes: 1 addition & 1 deletion proto/clients/quotacontrol.gen.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable */
// quota-control v0.17.1 a2ce8bcc50f161d979807c81b845604fc760d18a
// --
// Code generated by webrpc-gen@v0.20.3 with [email protected] generator. DO NOT EDIT.
// Code generated by webrpc-gen@v0.21.0 with [email protected] generator. DO NOT EDIT.
//
// webrpc-gen -schema=proto.ridl [email protected] -client -out=./clients/quotacontrol.gen.ts

Expand Down
2 changes: 1 addition & 1 deletion proto/proto.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 4d1b270

Please sign in to comment.