fix(auth): align file auth ids and callback auth directory handling#1921
fix(auth): align file auth ids and callback auth directory handling#1921shenshuoyaoyouguang wants to merge 3 commits intorouter-for-me:mainfrom
Conversation
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request refines the handling of file-based authentication, primarily by standardizing how authentication file IDs are generated and how the effective authentication directory is determined. These changes aim to prevent issues like duplicate authentication records, especially in environments with case-insensitive file systems or mirrored directories. By ensuring consistency in path resolution and ID normalization, the system becomes more robust and predictable, reducing potential support burdens and isolating directory consistency work from broader system changes. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request effectively refactors the authentication file handling logic, centralizing the auth ID normalization into a shared sdkAuth.NormalizeFileAuthID helper and consistently using an "effective auth directory" throughout the codebase. It also introduces a mutex in the management handler to prevent race conditions during hot-reloads, and includes comprehensive new tests. However, a critical path traversal vulnerability was identified in the DownloadAuthFile handler, specifically affecting Windows deployments due to inconsistent path separator validation. It is recommended to apply similar sanitization, like using filepath.Base, as seen in UploadAuthFile and DeleteAuthFile handlers, to mitigate this risk. Additionally, there is a suggestion to improve error visibility for a potential performance issue. Overall, this is a high-quality contribution, but the identified security vulnerability in DownloadAuthFile needs immediate attention.
| return | ||
| } | ||
| full := filepath.Join(h.cfg.AuthDir, name) | ||
| full := filepath.Join(h.effectiveAuthDir(), name) |
There was a problem hiding this comment.
The DownloadAuthFile handler is vulnerable to path traversal on Windows systems. The check strings.Contains(name, string(os.PathSeparator)) only validates against the backslash (\) separator on Windows, but filepath.Join also recognizes the forward slash (/) as a separator. An authenticated attacker can use forward slashes in the name query parameter (e.g., ?name=../../sensitive.json) to bypass the check and read arbitrary .json files outside the intended authentication directory. It is recommended to use filepath.Base(name) to ensure only the filename is used, preventing any directory traversal attempts.
| full := filepath.Join(h.effectiveAuthDir(), name) | |
| full := filepath.Join(h.effectiveAuthDir(), filepath.Base(name)) |
There was a problem hiding this comment.
Fixed in a491a71. DownloadAuthFile now rejects names containing either separator style or drive prefixes through a stricter simple-filename guard, so Windows /-based traversal no longer slips through.
| if err != nil { | ||
| return nil | ||
| } |
There was a problem hiding this comment.
The error from filepath.Walk is silently ignored here. If walking the authDir fails (e.g., due to an incorrect path or permissions), buildAuthDirFileInfoIndex will return nil. The caller then falls back to os.Stat for every auth file, which is a silent performance degradation and can hide configuration issues. I suggest logging this error to aid in debugging.
| if err != nil { | |
| return nil | |
| } | |
| if err != nil { | |
| log.WithError(err).Warnf("failed to build auth dir file index for %s", cleanAuthDir) | |
| return nil | |
| } |
There was a problem hiding this comment.
Fixed in a491a71. I kept the fallback behavior but added explicit warning logs for per-entry walk errors, so auth-dir traversal failures are now observable instead of silently degrading into repeated os.Stat calls.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request is a significant and well-executed refactoring that centralizes authentication ID normalization and aligns auth directory handling across different parts of the application. The introduction of a shared NormalizeFileAuthID helper and the consistent use of an effectiveAuthDir greatly improve code clarity, maintainability, and correctness, especially for Windows and nested path scenarios. The added tests are comprehensive and cover the new logic well. I've included a few suggestions to further enhance robustness and performance.
| if accessManager == nil { | ||
| log.Warn("access manager was nil, creating a default manager") | ||
| accessManager = sdkaccess.NewManager() | ||
| configaccess.Register(&cfg.SDKConfig) | ||
| accessManager.SetProviders(sdkaccess.RegisteredProviders()) | ||
| } |
There was a problem hiding this comment.
Creating a default accessManager here prevents a nil pointer dereference, but it might hide a configuration error where the caller intended to provide a specific manager but failed to do so. This could lead to the server running with incorrect or incomplete access control.
To make such configuration errors explicit and fail fast, consider changing NewServer to return an error if accessManager is nil, rather than creating a default one.
| func (h *Handler) StateMiddleware() gin.HandlerFunc { | ||
| return func(c *gin.Context) { | ||
| h.stateMu.Lock() | ||
| defer h.stateMu.Unlock() | ||
| c.Next() | ||
| } | ||
| } |
There was a problem hiding this comment.
Using a write lock (Lock()) for all requests in this middleware ensures thread safety but serializes all management API calls, which can be a performance bottleneck for concurrent read-only requests. Since stateMu is an RWMutex, you can improve concurrency by using a read lock (RLock()) for read-only methods like GET and HEAD.
This would require ensuring that any functions called by these handlers are free of write side-effects. For example, the lazy initialization in tokenStoreWithBaseDir would need to be made thread-safe if it can be called under a read lock.
func (h *Handler) StateMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
switch c.Request.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
h.stateMu.RLock()
defer h.stateMu.RUnlock()
default:
h.stateMu.Lock()
defer h.stateMu.Unlock()
}
c.Next()
}
}
sdk/auth/file_id.go
Outdated
| if rel, errRel := filepath.Rel(baseDir, id); errRel == nil && rel != "" { | ||
| id = rel | ||
| } |
There was a problem hiding this comment.
The error from filepath.Rel is currently ignored. If filepath.Rel fails, the function falls back to using the original path as the ID, which might be unexpected.
Additionally, if path and baseDir refer to the same file, filepath.Rel returns . which is likely not a desirable auth ID.
Consider handling these cases for more robust and predictable ID generation.
| if rel, errRel := filepath.Rel(baseDir, id); errRel == nil && rel != "" { | |
| id = rel | |
| } | |
| if rel, errRel := filepath.Rel(baseDir, id); errRel == nil && rel != "" && rel != "." { | |
| id = rel | |
| } |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request refactors and standardizes file-based authentication paths and identifiers, introducing NormalizeFileAuthID and effectiveAuthDir for consistency, and includes performance improvements and security hardening against path traversal. However, it introduces a new middleware with an overly broad exclusive lock, posing a DoS risk to the management API. Additionally, fragile OAuth callback logic could lead to a process-crashing panic if malformed authentication files are uploaded. There is also a suggestion regarding the choice of mutex type for concurrency safety.
|
|
||
| // Helper: wait for callback file | ||
| waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-anthropic-%s.oauth", state)) | ||
| waitFile := filepath.Join(h.effectiveAuthDir(), fmt.Sprintf(".oauth-anthropic-%s.oauth", state)) |
There was a problem hiding this comment.
The OAuth callback handling logic is vulnerable to a Denial of Service (DoS) attack via a runtime panic. The waitForFile function (and similar logic in other OAuth flows) ignores the error from json.Unmarshal. If the callback file contains invalid JSON or is empty, the resultMap variable remains nil. Subsequent attempts to access keys in this map (e.g., resultMap["error"] on line 1138) will cause a runtime panic, crashing the entire server process. An attacker with management API access can exploit this by uploading a malformed file to the authentication directory using the UploadAuthFile endpoint with a name that matches the expected OAuth callback pattern (e.g., .oauth-anthropic-<state>.oauth).
| h.stateMu.Lock() | ||
| defer h.stateMu.Unlock() | ||
| c.Next() |
There was a problem hiding this comment.
The StateMiddleware introduced in this PR uses an exclusive lock (h.stateMu.Lock()) that is held for the entire duration of every management API request, including the execution of the handler (c.Next()). This creates a significant Denial of Service (DoS) vector. An authenticated attacker can initiate a slow request (e.g., a large file upload or a request with a slow body stream) to any management endpoint, which will hold the lock and block all other management API requests until the first request completes. This effectively allows a single user to freeze the management interface for all other administrators.
| cfg *config.Config | ||
| configFilePath string | ||
| mu sync.Mutex | ||
| stateMu sync.RWMutex |
There was a problem hiding this comment.
The stateMu is declared as a sync.RWMutex, but it is only ever used with Lock(). There are no calls to RLock(). Using a sync.Mutex would be more idiomatic and slightly more efficient in this case, as it more clearly communicates the intent of exclusive access for all protected operations.
| stateMu sync.RWMutex | |
| stateMu sync.Mutex |
|
Review Navigation: This PR is suitable for priority review. Previous high-risk suggestions regarding DownloadAuthFile path traversal and file auth ID normalization have been addressed. Current CI has passed; remaining items are mainly concurrency read optimizations that do not affect current correctness. |
luispater
left a comment
There was a problem hiding this comment.
Summary:
Thanks for tightening the auth-dir and file-id handling. The overall direction looks good, but I found one blocking correctness issue in the new state-locking model.
Key findings:
- Blocking:
StateMiddleware()only serializes synchronous Gin request handling, but several management OAuth flows continue in background goroutines and still access handler state after the request returns. At the same time, hot reload updates that same state viaSetConfig()andSetAuthManager()in two separate steps. This means the code can still observe mixed runtime state even though the new middleware/comment suggests otherwise. - Non-blocking: nested auth entries are now listed, but single-file management endpoints still reject separator-containing names, and the disk-fallback / delete-all paths are still top-level only. That leaves nested auth handling inconsistent across management paths.
Test plan:
go test ./internal/api/handlers/management ./internal/api ./internal/watcher/synthesizer ./sdk/auth
Summary
Business value
Tests