generated from ethereum-optimism/.github
-
Notifications
You must be signed in to change notification settings - Fork 102
feat(proxyd): add external authentication support and refactor auth handling #228
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
Draft
aayushijain21
wants to merge
33
commits into
ethereum-optimism:main
Choose a base branch
from
aayushijain21:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+84
−24
Draft
Changes from 27 commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
1b11727
feat(proxyd): add external authentication support and refactor auth h…
aayushijain21 23186fb
fix(proxyd): add staticcheck directive to suppress lint warning for c…
aayushijain21 532924c
feat(proxyd): implement stub authentication for testing purposes
aayushijain21 aa9a249
Merge branch 'ethereum-optimism:main' into main
aayushijain21 cc9cff4
feat(proxyd): enhance logging for authentication processes and change…
aayushijain21 0ca4f1a
refactor(proxyd): change log level to info and update logging stateme…
aayushijain21 728028e
refactor(proxyd): improve logging statements for context population a…
aayushijain21 03f63b6
refactor(proxyd): streamline authentication handling and improve logg…
aayushijain21 3a626d8
refactor(proxyd): enhance authentication logging and streamline auth_…
aayushijain21 5423883
refactor: add more debugging logs
aayushijain21 befee13
minor log change
aayushijain21 1053ebb
feat(proxyd): change legacy authentication checks to fail open
aayushijain21 bdd2e05
simplify resolvedAuth map logic
aayushijain21 84892c1
refactor(proxyd): enhance logging in populateContext for better debug…
aayushijain21 3753391
refactor(proxyd): initialize resolvedAuth map and improve logging for…
aayushijain21 75404f9
feat(proxyd): add callback to performAuthCallback
aayushijain21 ab4b5c6
refactor(proxyd): update authorization header format in performAuthCa…
aayushijain21 ebb40bb
refactor(proxyd): performAuthCallback sends request to middleware
aayushijain21 9d00e37
refactor(proxyd): streamline logging in Start and populateContext fun…
aayushijain21 af6a8c6
logging
aayushijain21 d14dd26
remove logs
aayushijain21 32e5557
generalize performAuthCallback
aayushijain21 9ee8d62
add debugging logs
aayushijain21 0c782e3
log
aayushijain21 9daebd9
fix authurl to add token
aayushijain21 57f3093
debugging
aayushijain21 158c5fb
remove logs
aayushijain21 bd71e88
add http client
aayushijain21 2f18883
remove logs
aayushijain21 69b1dda
add httpclient to server
aayushijain21 df4b929
remove other client
aayushijain21 d6a1393
remove fn
aayushijain21 243f165
jsonrpc error
aayushijain21 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
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 |
|---|---|---|
| @@ -1,6 +1,7 @@ | ||
| package proxyd | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "crypto/rand" | ||
| "encoding/hex" | ||
|
|
@@ -50,6 +51,13 @@ const ( | |
|
|
||
| var emptyArrayResponse = json.RawMessage("[]") | ||
|
|
||
| type AuthCallbackRequest struct { | ||
| Headers map[string][]string `json:"headers"` | ||
| Path string `json:"path"` | ||
| Body string `json:"body"` | ||
| RemoteAddr string `json:"remote_addr"` | ||
| } | ||
|
|
||
| type Server struct { | ||
| BackendGroups map[string]*BackendGroup | ||
| wsBackendGroup *BackendGroup | ||
|
|
@@ -100,6 +108,7 @@ func NewServer( | |
| maxBatchSize int, | ||
| limiterFactory limiterFactoryFunc, | ||
| ) (*Server, error) { | ||
|
|
||
| if cache == nil { | ||
| cache = &NoopRPCCache{} | ||
| } | ||
|
|
@@ -614,6 +623,7 @@ func (s *Server) populateContext(w http.ResponseWriter, r *http.Request) context | |
| vars := mux.Vars(r) | ||
| authorization := vars["authorization"] | ||
| xff := r.Header.Get(s.rateLimitHeader) | ||
|
|
||
| if xff == "" { | ||
| ipPort := strings.Split(r.RemoteAddr, ":") | ||
| if len(ipPort) == 2 { | ||
|
|
@@ -628,22 +638,71 @@ func (s *Server) populateContext(w http.ResponseWriter, r *http.Request) context | |
| ctx = context.WithValue(ctx, ContextKeyOpTxProxyAuth, opTxProxyAuth) // nolint:staticcheck | ||
| } | ||
|
|
||
| if len(s.authenticatedPaths) > 0 { | ||
| if authorization == "" || s.authenticatedPaths[authorization] == "" { | ||
| log.Info("blocked unauthorized request", "authorization", authorization) | ||
| httpResponseCodesTotal.WithLabelValues("401").Inc() | ||
| w.WriteHeader(401) | ||
| // Check if we have an external auth URL configured | ||
| authURL, hasExternalAuth := s.authenticatedPaths["auth_url"] | ||
| if hasExternalAuth && authURL != "" { // nolint:staticcheck | ||
| // Use external authentication service | ||
| alias, err := s.performAuthCallback(r, authURL) | ||
| if err != nil || alias == "" { // Check both error and empty alias | ||
| w.WriteHeader(http.StatusUnauthorized) | ||
| return nil | ||
| } | ||
|
|
||
| ctx = context.WithValue(ctx, ContextKeyAuth, alias) // nolint:staticcheck | ||
| } else { | ||
| ctx = context.WithValue(ctx, ContextKeyAuth, s.authenticatedPaths[authorization]) // nolint:staticcheck | ||
| } | ||
| return context.WithValue(ctx, ContextKeyReqID, randStr(10)) // nolint:staticcheck | ||
| } | ||
|
|
||
| return context.WithValue( | ||
| ctx, | ||
| ContextKeyReqID, // nolint:staticcheck | ||
| randStr(10), | ||
| ) | ||
| func (s *Server) performAuthCallback(r *http.Request, authURL string) (string, error) { | ||
| // Get the authorization token from the request | ||
| authorization := mux.Vars(r)["authorization"] | ||
| if authorization == "" { | ||
| return "", fmt.Errorf("missing authorization token") | ||
| } | ||
|
|
||
| // Read the body first | ||
| bodyBytes, err := io.ReadAll(r.Body) | ||
| if err != nil { | ||
| log.Error("performAuthCallback failed to read request body", "err", err) | ||
| return "", fmt.Errorf("failed to read request body: %w", err) | ||
| } | ||
| r.Body.Close() | ||
|
|
||
| // Create new body for original request | ||
| r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) | ||
|
|
||
| // Append the token to the auth URL path | ||
| authURLWithToken := fmt.Sprintf("%s/%s", | ||
| strings.TrimRight(authURL, "/"), | ||
| authorization) | ||
|
|
||
| // Create new request to auth URL with same method, headers and new body copy | ||
| req, err := http.NewRequestWithContext(r.Context(), r.Method, authURLWithToken, | ||
| bytes.NewBuffer(bodyBytes)) | ||
| if err != nil { | ||
| log.Error("performAuthCallback failed to create request", "err", err) | ||
| return "", fmt.Errorf("failed to create auth request: %w", err) | ||
| } | ||
|
|
||
| // Copy original headers | ||
| req.Header = r.Header | ||
|
||
|
|
||
| // Make the request | ||
| client := &http.Client{Timeout: 5 * time.Second} | ||
|
||
| resp, err := client.Do(req) | ||
| if err != nil { | ||
| log.Error("performAuthCallback request failed", "err", err) | ||
| return "", fmt.Errorf("auth callback failed: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| // Only reject if we get a 401 | ||
| if resp.StatusCode == http.StatusUnauthorized { | ||
| return "", fmt.Errorf("unauthorized") | ||
| } | ||
|
|
||
| return authorization, nil | ||
| } | ||
|
|
||
| func randStr(l int) string { | ||
|
|
@@ -801,11 +860,16 @@ func instrumentedHdlr(h http.Handler) http.HandlerFunc { | |
| } | ||
|
|
||
| func GetAuthCtx(ctx context.Context) string { | ||
| if ctx == nil { | ||
| log.Info("GetAuthCtx called with nil context") | ||
| return "none" | ||
| } | ||
| authUser, ok := ctx.Value(ContextKeyAuth).(string) | ||
| if !ok { | ||
| log.Info("GetAuthCtx No auth value found in context") | ||
| return "none" | ||
| } | ||
|
|
||
| log.Info("GetAuthCtx Auth value found in context", "auth", authUser) | ||
| return authUser | ||
| } | ||
|
|
||
|
|
@@ -878,3 +942,15 @@ func createBatchRequest(elems []batchElem) []*RPCReq { | |
| } | ||
| return batch | ||
| } | ||
|
|
||
| // Helper function to get map keys | ||
| func getMapKeys(m map[string]string) []string { | ||
| if m == nil { | ||
| return nil | ||
| } | ||
| keys := make([]string, 0, len(m)) | ||
| for k := range m { | ||
| keys = append(keys, k) | ||
| } | ||
| return keys | ||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
defer r.Body.Close()