Skip to content

Commit

Permalink
Merge pull request #16 from sygmaprotocol/mmuftic/rpc-auth-in-path
Browse files Browse the repository at this point in the history
feat: rpc auth in path
  • Loading branch information
MakMuftic authored May 29, 2024
2 parents 09a8f7b + 7281ad5 commit e53c37b
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ Each JSON configuration file for the gateways can specify detailed settings for
## Authentication
Authentication can be enabled using the `--auth` flag. The auth token should be set through environment variables `GATEWAY_PASSWORD`.

Auth token needs to be the last entry in the RPC gateway URL. Example:

`https://sample/rpc-gateway/sepolia/a1b2c3d4e5f7`

### Running the Application
To run the application with authentication:

Expand Down
7 changes: 5 additions & 2 deletions internal/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@ package auth

import (
"net/http"
"strings"
)

func URLTokenAuth(token string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authToken := r.URL.Query().Get("auth_token")
if authToken == "" || authToken != token {
pathParts := strings.Split(r.URL.Path, "/")
if len(pathParts) < 2 || pathParts[len(pathParts)-1] != token {
w.WriteHeader(http.StatusUnauthorized)

return
}
// Remove the token part from the path to forward the request to the next handler
r.URL.Path = strings.Join(pathParts[:len(pathParts)-1], "/")
next.ServeHTTP(w, r)
})
}
Expand Down
13 changes: 9 additions & 4 deletions internal/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"testing"
)

func TestUrlTokenAuth(t *testing.T) {
func TestURLTokenAuth(t *testing.T) {
validToken := "valid_token"
middleware := URLTokenAuth(validToken)

Expand All @@ -17,17 +17,22 @@ func TestUrlTokenAuth(t *testing.T) {
}{
{
name: "Valid token",
url: "/?auth_token=valid_token",
url: "/some/path/valid_token",
expectedStatus: http.StatusOK,
},
{
name: "Valid token",
url: "/some/really/long/path/valid_token",
expectedStatus: http.StatusOK,
},
{
name: "Invalid token",
url: "/?auth_token=invalid_token",
url: "/some/path/invalid_token",
expectedStatus: http.StatusUnauthorized,
},
{
name: "Missing token",
url: "/",
url: "/some/path/",
expectedStatus: http.StatusUnauthorized,
},
}
Expand Down

0 comments on commit e53c37b

Please sign in to comment.