-
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 6 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,54 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "io" | ||
| "net/http" | ||
|
|
||
| tm2Client "github.com/gnolang/faucet/client/http" | ||
| "github.com/gnolang/gno/tm2/pkg/crypto" | ||
| ) | ||
|
|
||
| func getAccountBalanceMiddleware(tm2Client *tm2Client.Client, maxBalance int64) func(next http.Handler) http.Handler { | ||
| type request struct { | ||
| To string `json:"to"` | ||
| } | ||
| return func(next http.Handler) http.Handler { | ||
| return http.HandlerFunc( | ||
| func(w http.ResponseWriter, r *http.Request) { | ||
| var data request | ||
| body, err := io.ReadAll(r.Body) | ||
| if err != nil { | ||
| http.Error(w, err.Error(), http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| err = json.Unmarshal(body, &data) | ||
| r.Body = io.NopCloser(bytes.NewBuffer(body)) | ||
| balance, err := checkAccountBalance(tm2Client, data.To) | ||
| if err != nil { | ||
| http.Error(w, err.Error(), http.StatusBadRequest) | ||
| return | ||
| } | ||
aeddi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if balance >= maxBalance { | ||
| http.Error(w, "accounts is already topped up", http.StatusBadRequest) | ||
| return | ||
| } | ||
| next.ServeHTTP(w, r) | ||
| }, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| var checkAccountBalance = func(tm2Client *tm2Client.Client, walletAddress string) (int64, error) { | ||
| address, err := crypto.AddressFromString(walletAddress) | ||
| if err != nil { | ||
| return 0, err | ||
| } | ||
| acc, err := tm2Client.GetAccount(address) | ||
| if err != nil { | ||
| return 0, err | ||
| } | ||
| return acc.GetCoins().AmountOf("ugnot"), nil | ||
| } | ||
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,82 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "errors" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| tm2Client "github.com/gnolang/faucet/client/http" | ||
| "github.com/stretchr/testify/assert" | ||
| ) | ||
|
|
||
| func mockedCheckAccountBalance(amount int64, err error) func(tm2Client *tm2Client.Client, walletAddress string) (int64, error) { | ||
| return func(tm2Client *tm2Client.Client, walletAddress string) (int64, error) { | ||
| return amount, err | ||
| } | ||
| } | ||
|
|
||
| func TestGetAccountBalanceMiddleware(t *testing.T) { | ||
| maxBalance := int64(1000) | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| requestBody map[string]string | ||
| expectedStatus int | ||
| expectedBody string | ||
| checkBalanceFunc func(tm2Client *tm2Client.Client, walletAddress string) (int64, error) | ||
| }{ | ||
| { | ||
| name: "Valid address with low balance (should pass)", | ||
| requestBody: map[string]string{"to": "valid_address_low_balance"}, | ||
| expectedStatus: http.StatusOK, | ||
| expectedBody: "next handler reached", | ||
| checkBalanceFunc: mockedCheckAccountBalance(500, nil), | ||
| }, | ||
| { | ||
| name: "Valid address with high balance (should fail)", | ||
| requestBody: map[string]string{"To": "valid_address_high_balance"}, | ||
| expectedStatus: http.StatusBadRequest, | ||
| expectedBody: "accounts is already topped up", | ||
| checkBalanceFunc: mockedCheckAccountBalance(2*maxBalance, nil), | ||
| }, | ||
| { | ||
| name: "Invalid address (should fail)", | ||
| requestBody: map[string]string{"To": "invalid_address"}, | ||
| expectedStatus: http.StatusBadRequest, | ||
| expectedBody: "account not found", | ||
| checkBalanceFunc: mockedCheckAccountBalance(2*maxBalance, errors.New("account not found")), | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| checkAccountBalance = tt.checkBalanceFunc | ||
| // Convert request body to JSON | ||
| reqBody, _ := json.Marshal(tt.requestBody) | ||
|
|
||
| // Create request | ||
| req := httptest.NewRequest(http.MethodPost, "/claim", bytes.NewReader(reqBody)) | ||
| req.Header.Set("Content-Type", "application/json") | ||
|
|
||
| // Create ResponseRecorder | ||
| rr := httptest.NewRecorder() | ||
|
|
||
| // Mock next handler | ||
| nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusOK) | ||
| w.Write([]byte("next handler reached")) | ||
| }) | ||
|
|
||
| // Apply middleware | ||
| handler := getAccountBalanceMiddleware(nil, maxBalance)(nextHandler) | ||
| handler.ServeHTTP(rr, req) | ||
|
|
||
| // Check response | ||
| assert.Equal(t, tt.expectedStatus, rr.Code) | ||
| assert.Contains(t, rr.Body.String(), tt.expectedBody) | ||
| }) | ||
| } | ||
| } |
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,36 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "sync" | ||
| "time" | ||
| ) | ||
|
|
||
| // CooldownLimiter is a Limiter using an in-memory map | ||
aeddi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| type CooldownLimiter struct { | ||
| cooldowns map[string]time.Time | ||
aeddi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| mu sync.Mutex | ||
| cooldownTime time.Duration | ||
| } | ||
|
|
||
| // NewCooldownLimiter initializes a Cooldown Limiter with a given duration | ||
| func NewCooldownLimiter(cooldown time.Duration) *CooldownLimiter { | ||
| return &CooldownLimiter{ | ||
| cooldowns: make(map[string]time.Time), | ||
| cooldownTime: cooldown, | ||
| } | ||
| } | ||
|
|
||
| // CheckCooldown checks if a key has done some action before the cooldown period has passed | ||
| func (rl *CooldownLimiter) CheckCooldown(key string) bool { | ||
| rl.mu.Lock() | ||
| defer rl.mu.Unlock() | ||
|
|
||
| if lastClaim, found := rl.cooldowns[key]; found { | ||
| if time.Since(lastClaim) < rl.cooldownTime { | ||
| return false // Deny claim if within cooldown period | ||
| } | ||
| } | ||
|
|
||
| rl.cooldowns[key] = time.Now() | ||
| return true | ||
| } | ||
aeddi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
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,28 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestCooldownLimiter(t *testing.T) { | ||
| cooldownDuration := time.Second | ||
| limiter := NewCooldownLimiter(cooldownDuration) | ||
| user := "testUser" | ||
|
|
||
| // First check should be allowed | ||
| if !limiter.CheckCooldown(user) { | ||
| t.Errorf("Expected first CheckCooldown to return true, but got false") | ||
| } | ||
|
|
||
| // Second check immediately should be denied | ||
| if limiter.CheckCooldown(user) { | ||
| t.Errorf("Expected second CheckCooldown to return false, but got true") | ||
| } | ||
|
|
||
| require.Eventually(t, func() bool { | ||
| return limiter.CheckCooldown(user) | ||
| }, 2*cooldownDuration, 10*time.Millisecond, "Expected CheckCooldown to return true after cooldown period") | ||
| } |
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,85 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/google/go-github/v64/github" | ||
| ) | ||
|
|
||
| func getGithubMiddleware(clientID, secret string, cooldown time.Duration) func(next http.Handler) http.Handler { | ||
aeddi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| coolDownLimiter := NewCooldownLimiter(cooldown) | ||
| return func(next http.Handler) http.Handler { | ||
| return http.HandlerFunc( | ||
| func(w http.ResponseWriter, r *http.Request) { | ||
| // github Oauth flow is enabled | ||
| if secret == "" || clientID == "" { | ||
zivkovicmilos marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| // Continue with serving the faucet request | ||
| next.ServeHTTP(w, r) | ||
|
|
||
| return | ||
| } | ||
|
|
||
| code := r.URL.Query().Get("code") | ||
| if code == "" { | ||
| http.Error(w, "missing code", http.StatusBadRequest) | ||
| return | ||
| } | ||
aeddi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| user, err := exchangeCodeForUser(r.Context(), secret, clientID, code) | ||
| if err != nil { | ||
| http.Error(w, err.Error(), http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| // Just check if given account have asked for faucet before the cooldown period | ||
| if !coolDownLimiter.CheckCooldown(user.GetLogin()) { | ||
| http.Error(w, "user is on cooldown", http.StatusTooManyRequests) | ||
| return | ||
| } | ||
|
|
||
| // Possibility to have more conditions like accountAge, commits, pullRequest etc | ||
|
|
||
| next.ServeHTTP(w, r) | ||
Villaquiranm marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| }, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| type GitHubTokenResponse struct { | ||
zivkovicmilos marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| AccessToken string `json:"access_token"` | ||
| } | ||
|
|
||
| var exchangeCodeForUser = func(ctx context.Context, secret, clientID, code string) (*github.User, error) { | ||
| url := "https://github.com/login/oauth/access_token" | ||
zivkovicmilos marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| body := fmt.Sprintf("client_id=%s&client_secret=%s&code=%s", clientID, secret, code) | ||
| req, err := http.NewRequest("POST", url, strings.NewReader(body)) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| req.Header.Set("Accept", "application/json") | ||
|
|
||
| client := &http.Client{} | ||
| resp, err := client.Do(req) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| var tokenResponse GitHubTokenResponse | ||
| if err := json.NewDecoder(resp.Body).Decode(&tokenResponse); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if tokenResponse.AccessToken == "" { | ||
| return nil, fmt.Errorf("unable to exchange code for token") | ||
| } | ||
|
|
||
| ghClient := github.NewClient(http.DefaultClient).WithAuthToken(tokenResponse.AccessToken) | ||
| user, _, err := ghClient.Users.Get(ctx, "") | ||
| return user, err | ||
| } | ||
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.