-
Notifications
You must be signed in to change notification settings - Fork 445
feat(gnofaucet): Github middleware with cooldown #3808
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
Merged
zivkovicmilos
merged 35 commits into
gnolang:master
from
Villaquiranm:feat/gh-middleware-with-cooldown
Apr 11, 2025
Merged
Changes from all commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
c8a8456
feat: faucet github middleware with coolDown
Villaquiranm dd50e7b
add max balance middleware and tests
b054763
apply lint
118c08b
Merge branch 'master' into feat/gh-middleware-with-cooldown
Villaquiranm 07f6145
generalize cooldown limiter
ab43999
Merge branch 'master' into feat/gh-middleware-with-cooldown
Villaquiranm 962ac2c
add some comments :)
e59b6a7
Update contribs/gnofaucet/gh.go
Villaquiranm a55637c
Update contribs/gnofaucet/serve.go
Villaquiranm 6e9727a
add badger as database
62d710a
fix lint
6bab9b2
Merge branch 'master' into feat/gh-middleware-with-cooldown
Villaquiranm 32d6d24
Update contribs/gnofaucet/cooldown.go
Villaquiranm bbd82c0
Update contribs/gnofaucet/cooldown.go
Villaquiranm 64534bd
Update contribs/gnofaucet/cooldown.go
Villaquiranm dede43c
fix comments :)
022e923
return error on cooldown limiter
373f6e0
Merge branch 'master' into feat/gh-middleware-with-cooldown
Villaquiranm e5a461d
oups typo
439b1b7
Merge branch 'master' into feat/gh-middleware-with-cooldown
Villaquiranm 5a1dd62
change badger -> redis
72c7f4d
fixes
f984a7b
separate cmd for github and captcha
28182f6
remove check balance on account
703b16f
implement total claimable limit
426919a
improve tests
300b7f4
Merge branch 'master' into feat/gh-middleware-with-cooldown
Villaquiranm 909ad71
fix lint
82c3600
fix comments
Villaquiranm cb07372
separate test in different files
Villaquiranm a4b8827
update Readme
Villaquiranm 1415777
document redis ?
Villaquiranm 3ba49d9
take ugnots from string
Villaquiranm c9f2535
fix test and change default listen address
Villaquiranm 360317f
Merge branch 'master' into feat/gh-middleware-with-cooldown
Villaquiranm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # required | ||
| # These credentials are obtained when registering an application on GitHub at: | ||
| # https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authenticating-to-the-rest-api-with-an-oauth-app#registering-your-app | ||
| GH_CLIENT_SECRET= | ||
|
|
||
| # Redis credentials | ||
| # We use Redis for keeping a record across several instances of the faucet usage for each user | ||
| # Each user is identified by their GitHub login, and each time they claim tokens, the current total claimed amount is stored | ||
| # REDIS_ADDR: The address of the Redis server, e.g. "localhost:6379" | ||
| # REDIS_USER: The Redis username | ||
| # REDIS_PASSWORD: The Redis user's password | ||
| # For more information on how to set up Redis, see https://redis.io | ||
| REDIS_ADDR= | ||
| REDIS_USER= | ||
| REDIS_PASSWORD= | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "flag" | ||
| "fmt" | ||
|
|
||
| "github.com/gnolang/gno/tm2/pkg/commands" | ||
| ) | ||
|
|
||
| type captchaCfg struct { | ||
| rootCfg *serveCfg | ||
| captchaSecret string | ||
| } | ||
|
|
||
| var errCaptchaMissing = fmt.Errorf("captcha secret is required") | ||
|
|
||
| func (c *captchaCfg) RegisterFlags(fs *flag.FlagSet) { | ||
| fs.StringVar( | ||
| &c.captchaSecret, | ||
| "captcha-secret", | ||
| "", | ||
| "recaptcha secret key (if empty, captcha are disabled)", | ||
| ) | ||
| } | ||
|
|
||
| func newCaptchaCmd(rootCfg *serveCfg) *commands.Command { | ||
| cfg := &captchaCfg{ | ||
| rootCfg: rootCfg, | ||
| } | ||
|
|
||
| return commands.NewCommand( | ||
| commands.Metadata{ | ||
| Name: "captcha", | ||
| ShortUsage: "captcha [flags]", | ||
| LongHelp: "applies captcha middleware to the gno.land faucet", | ||
| }, | ||
| cfg, | ||
| func(ctx context.Context, args []string) error { | ||
| return execCaptcha(ctx, cfg, commands.NewDefaultIO()) | ||
| }, | ||
| ) | ||
| } | ||
|
|
||
| func execCaptcha(ctx context.Context, cfg *captchaCfg, io commands.IO) error { | ||
| if cfg.captchaSecret == "" { | ||
| return errCaptchaMissing | ||
| } | ||
|
|
||
| return serveFaucet(ctx, cfg.rootCfg, io, getCaptchaMiddleware(cfg.captchaSecret)) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestServeCapcha(t *testing.T) { | ||
| t.Run("Serve captcha without captcha-secret", func(t *testing.T) { | ||
| cmd := newServeCmd() | ||
| args := []string{ | ||
| "captcha", | ||
| } | ||
|
|
||
| // Run the command | ||
| cmdErr := cmd.ParseAndRun(context.Background(), args) | ||
| assert.ErrorIs(t, cmdErr, errCaptchaMissing) | ||
| }) | ||
|
|
||
| t.Run("Serve captcha without chain-id", func(t *testing.T) { | ||
| cmd := newServeCmd() | ||
| args := []string{ | ||
| "captcha", | ||
| "--captcha-secret", | ||
| "dummy-secret", | ||
| } | ||
|
|
||
| // Run the command | ||
| cmdErr := cmd.ParseAndRun(context.Background(), args) | ||
| assert.ErrorContains(t, cmdErr, "invalid chain ID") | ||
| }) | ||
|
|
||
| t.Run("Serve captcha with invalid mnemonic", func(t *testing.T) { | ||
| cmd := newServeCmd() | ||
| args := []string{ | ||
| "captcha", | ||
| "--captcha-secret", | ||
| "dummy-secret", | ||
| "--chain-id", | ||
| "dev", | ||
| } | ||
|
|
||
| // Run the command | ||
| cmdErr := cmd.ParseAndRun(context.Background(), args) | ||
| assert.ErrorContains(t, cmdErr, "invalid mnemonic") | ||
| }) | ||
|
|
||
| t.Run("Serve captcha OK", func(t *testing.T) { | ||
| cmd := newServeCmd() | ||
| args := []string{ | ||
| "captcha", | ||
| "--captcha-secret", | ||
| "dummy-secret", | ||
| "--chain-id", | ||
| "dev", | ||
| "--mnemonic", | ||
| defaultAccount_Seed, | ||
| } | ||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| go func() { | ||
| time.Sleep(time.Millisecond * 100) | ||
| cancel() | ||
| }() | ||
| // Run the command | ||
| cmdErr := cmd.ParseAndRun(ctx, args) | ||
| require.NoError(t, cmdErr) | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "time" | ||
|
|
||
| "github.com/pkg/errors" | ||
| "github.com/redis/go-redis/v9" | ||
| ) | ||
|
|
||
| // CooldownLimiter limits a specific user to one claim per cooldown period | ||
| // this limiter keeps track of which keys are on cooldown using a badger database (written to a local file) | ||
| type CooldownLimiter struct { | ||
| redis *redis.Client | ||
| cooldownTime time.Duration | ||
| maxlifeTimeAmount *int64 | ||
| } | ||
|
|
||
| // NewCooldownLimiter initializes a Cooldown Limiter with a given duration | ||
| func NewCooldownLimiter(cooldown time.Duration, redis *redis.Client, maxlifeTimeAmount int64) *CooldownLimiter { | ||
| limiter := &CooldownLimiter{ | ||
| redis: redis, | ||
| cooldownTime: cooldown, | ||
| } | ||
| if maxlifeTimeAmount > 0 { | ||
| limiter.maxlifeTimeAmount = &maxlifeTimeAmount | ||
| } | ||
|
|
||
| return limiter | ||
| } | ||
|
|
||
| // CheckCooldown checks if a key can make a claim or if it is still within the cooldown period | ||
| // also checks that the user will not exceed the max lifetime allowed amount | ||
| // Returns true if the key is not on cooldown, and marks the key as on cooldown | ||
| // Returns false if the key is on cooldown or if an error occurs | ||
| func (rl *CooldownLimiter) CheckCooldown(ctx context.Context, key string, amountClaimed int64) (bool, error) { | ||
| claimData, err := rl.getClaimsData(ctx, key) | ||
| if err != nil { | ||
| return false, fmt.Errorf("unable to check if key is on cooldown, %w", err) | ||
| } | ||
| // Deny claim if within cooldown period | ||
| if claimData.LastClaimed.Add(rl.cooldownTime).After(time.Now()) { | ||
| return false, nil | ||
| } | ||
| // check that user will not exceed max lifetime allowed amount | ||
| if rl.maxlifeTimeAmount != nil && claimData.TotalClaimed+amountClaimed > *rl.maxlifeTimeAmount { | ||
| return false, nil | ||
| } | ||
|
|
||
| return true, rl.declareClaimedValue(ctx, key, amountClaimed, claimData) | ||
| } | ||
|
|
||
| func (rl *CooldownLimiter) getClaimsData(ctx context.Context, key string) (*claimData, error) { | ||
| storedData, err := rl.redis.Get(ctx, key).Result() | ||
| if err != nil { | ||
| // Here we return an empty claimData because is the first time the user is making a claim | ||
| // the total amount claimed is 0 and the lastClaimed is the default time value | ||
| if errors.Is(err, redis.Nil) { | ||
| return &claimData{}, nil | ||
| } | ||
| // Any other unexpected error is returned. | ||
| return nil, err | ||
| } | ||
|
|
||
| claimData := &claimData{} | ||
| err = json.Unmarshal([]byte(storedData), claimData) | ||
| return claimData, err | ||
| } | ||
|
|
||
| func (rl *CooldownLimiter) declareClaimedValue(ctx context.Context, key string, amountClaimed int64, currentData *claimData) error { | ||
| currentData.LastClaimed = time.Now() | ||
| currentData.TotalClaimed += amountClaimed | ||
|
|
||
| data, err := json.Marshal(currentData) | ||
| if err != nil { | ||
| return fmt.Errorf("unable to marshal claim data, %w", err) | ||
| } | ||
|
|
||
| return rl.redis.Set(ctx, key, data, 0).Err() | ||
| } | ||
|
|
||
| type claimData struct { | ||
zivkovicmilos marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| LastClaimed time.Time | ||
| TotalClaimed int64 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/alicebob/miniredis/v2" | ||
| "github.com/redis/go-redis/v9" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestCooldownLimiter(t *testing.T) { | ||
| var tenGnots int64 = 10_000_000 | ||
| redisServer := miniredis.RunT(t) | ||
| rdb := redis.NewClient(&redis.Options{ | ||
| Addr: redisServer.Addr(), | ||
| }) | ||
|
|
||
| cooldownDuration := time.Second | ||
| limiter := NewCooldownLimiter(cooldownDuration, rdb, 0) | ||
| ctx := context.Background() | ||
| user := "testUser" | ||
|
|
||
| // First check should be allowed | ||
| allowed, err := limiter.CheckCooldown(ctx, user, tenGnots) | ||
| require.NoError(t, err) | ||
|
|
||
| if !allowed { | ||
| t.Errorf("Expected first CheckCooldown to return true, but got false") | ||
| } | ||
|
|
||
| allowed, err = limiter.CheckCooldown(ctx, user, tenGnots) | ||
| require.NoError(t, err) | ||
| // Second check immediately should be denied | ||
| if allowed { | ||
| t.Errorf("Expected second CheckCooldown to return false, but got true") | ||
| } | ||
|
|
||
| require.Eventually(t, func() bool { | ||
| allowed, err := limiter.CheckCooldown(ctx, user, tenGnots) | ||
| return err == nil && !allowed | ||
| }, 2*cooldownDuration, 10*time.Millisecond, "Expected CheckCooldown to return true after cooldown period") | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.