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

feat: rpc auth in path #16

Merged
merged 5 commits into from
May 29, 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
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
Loading