-
Notifications
You must be signed in to change notification settings - Fork 0
fix(cli): serialize token refresh across processes #34
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
Open
appleboy
wants to merge
2
commits into
main
Choose a base branch
from
worktree-keyring
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.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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
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 |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/sha256" | ||
| "encoding/hex" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
| "path/filepath" | ||
| "time" | ||
|
|
||
| "github.com/gofrs/flock" | ||
| ) | ||
|
|
||
| const lockRetryInterval = 100 * time.Millisecond | ||
|
|
||
| // lockDirName is the per-user subdirectory used for refresh locks when the | ||
| // token file path is relative (the default and the keyring/auto backends). | ||
| const lockDirName = "authgate-cli" | ||
|
|
||
| // lockTokenStore acquires a cross-process advisory lock scoped to | ||
| // (tokenFile, clientID). It serialises the "load → refresh → save" | ||
| // critical section so concurrent CLI invocations cannot spend the same | ||
| // refresh token twice (which would yield invalid_grant on rotation servers). | ||
| // | ||
| // The returned io.Closer releases the lock on Close (flock.Close is documented | ||
| // as equivalent to Unlock). | ||
| // | ||
| // Lock placement: when tokenFile is an absolute path (an explicit file backend) | ||
| // the lock sits next to it, so distinct stores get distinct locks. When the | ||
| // path is relative — the default, and the case for keyring/auto backends where | ||
| // the token never touches disk — the lock is anchored in a stable, per-user, | ||
| // cwd-independent directory (os.UserCacheDir, falling back to os.TempDir). That | ||
| // way refresh does not require a writable working directory and concurrent runs | ||
| // launched from different directories still serialise. | ||
| func lockTokenStore(ctx context.Context, tokenFile, clientID string) (io.Closer, error) { | ||
| if tokenFile == "" { | ||
| return nil, errors.New("lock: tokenFile is empty") | ||
| } | ||
| if clientID == "" { | ||
| return nil, errors.New("lock: clientID is empty") | ||
| } | ||
|
|
||
| dir := filepath.Dir(tokenFile) | ||
| if !filepath.IsAbs(tokenFile) { | ||
| base, err := os.UserCacheDir() | ||
| if err != nil { | ||
| base = os.TempDir() | ||
| } | ||
| dir = filepath.Join(base, lockDirName) | ||
| } | ||
| if err := os.MkdirAll(dir, 0o700); err != nil { | ||
| return nil, fmt.Errorf("create lock directory %q: %w", dir, err) | ||
| } | ||
|
|
||
| lockPath := filepath.Join(dir, lockFileName(tokenFile, clientID)) | ||
| fl := flock.New(lockPath) | ||
| locked, err := fl.TryLockContext(ctx, lockRetryInterval) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("acquire lock %s: %w", lockPath, err) | ||
| } | ||
| if !locked { | ||
| return nil, fmt.Errorf("could not acquire lock %s", lockPath) | ||
| } | ||
| return fl, nil | ||
| } | ||
|
|
||
| // lockFileName builds a filesystem-safe lock filename for (tokenFile, clientID). | ||
| // The clientID is hashed rather than interpolated directly so that path | ||
| // separators, "..", or characters that are invalid on some platforms can never | ||
| // alter the lock location or produce an unusable name. | ||
| func lockFileName(tokenFile, clientID string) string { | ||
| sum := sha256.Sum256([]byte(clientID)) | ||
| return filepath.Base(tokenFile) + "." + hex.EncodeToString(sum[:8]) + ".lock" | ||
| } | ||
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,88 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "path/filepath" | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| // TestLockTokenStore_AcquireAndRelease verifies a basic acquire → release cycle | ||
| // and that the lock can be re-acquired after the first holder closes it. | ||
| func TestLockTokenStore_AcquireAndRelease(t *testing.T) { | ||
| tokenFile := filepath.Join(t.TempDir(), "tokens.json") | ||
|
|
||
| first, err := lockTokenStore(context.Background(), tokenFile, "client-a") | ||
| if err != nil { | ||
| t.Fatalf("first acquire: %v", err) | ||
| } | ||
| if err := first.Close(); err != nil { | ||
| t.Fatalf("release: %v", err) | ||
| } | ||
|
|
||
| second, err := lockTokenStore(context.Background(), tokenFile, "client-a") | ||
| if err != nil { | ||
| t.Fatalf("re-acquire after release: %v", err) | ||
| } | ||
| if err := second.Close(); err != nil { | ||
| t.Fatalf("second release: %v", err) | ||
| } | ||
| } | ||
|
|
||
| // TestLockTokenStore_RejectsEmptyInputs guards the two preconditions. | ||
| func TestLockTokenStore_RejectsEmptyInputs(t *testing.T) { | ||
| if _, err := lockTokenStore(context.Background(), "", "client"); err == nil { | ||
| t.Error("expected error for empty tokenFile") | ||
| } | ||
| if _, err := lockTokenStore(context.Background(), "tokens.json", ""); err == nil { | ||
| t.Error("expected error for empty clientID") | ||
| } | ||
| } | ||
|
|
||
| // TestLockFileName_SafeForHostileClientID verifies that a clientID containing | ||
| // path separators or "../" segments cannot escape the lock directory or change | ||
| // the directory component of the lock filename. | ||
| func TestLockFileName_SafeForHostileClientID(t *testing.T) { | ||
| hostile := []string{ | ||
| "../../etc/passwd", | ||
| "a/b/c", | ||
| "..", | ||
| `win\path`, | ||
| "plain-client", | ||
| } | ||
| for _, id := range hostile { | ||
| name := lockFileName("tokens.json", id) | ||
| if strings.ContainsAny(name, `/\`) { | ||
| t.Errorf("clientID %q produced a name with a separator: %q", id, name) | ||
| } | ||
| // filepath.Join with the name must stay inside the directory. | ||
| got := filepath.Join("/locks", name) | ||
| if filepath.Dir(got) != "/locks" { | ||
| t.Errorf("clientID %q escaped the lock dir: %q", id, got) | ||
| } | ||
| if !strings.HasSuffix(name, ".lock") { | ||
| t.Errorf("clientID %q produced %q, want a .lock suffix", id, name) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // TestLockTokenStore_RelativePathUsesStableDir verifies that a relative token | ||
| // file path does not place the lock in (and therefore does not require a | ||
| // writable) current working directory — it is anchored under the user cache dir | ||
| // instead. Redirect the cache dir to a temp location so the test does not | ||
| // pollute the real one. | ||
| func TestLockTokenStore_RelativePathUsesStableDir(t *testing.T) { | ||
| cache := t.TempDir() | ||
| t.Setenv("XDG_CACHE_HOME", cache) // Linux | ||
| t.Setenv("HOME", cache) // macOS ($HOME/Library/Caches) and Linux fallback | ||
|
|
||
| closer, err := lockTokenStore(context.Background(), ".authgate-tokens.json", "rel-client") | ||
| if err != nil { | ||
| t.Fatalf("acquire with relative path: %v", err) | ||
| } | ||
| defer closer.Close() | ||
|
|
||
| if leaked, _ := filepath.Glob(".authgate-tokens.json.*.lock"); len(leaked) != 0 { | ||
| t.Errorf("lock leaked into the working directory: %v", leaked) | ||
| } | ||
| } |
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
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.