Repository navigation
refactor: consolidate file locking - #2856
Conversation
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
|
💥 This pull request now has conflicts. Could you fix it Erik Osterman (Cloud Posse) (@osterman)? 🙏 |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe PR replaces custom ChangesShared file-lock migration
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (10)
pkg/auth/cloud/gcp/files.go (1)
305-321: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe cleanup lock does not exclude concurrent writers, and it leaves a lock file behind.
Two small points, both non-blocking:
lockTargetis a synthetic path, so its lock is disjoint from the locks thatWriteADCFile,WritePropertiesFile, andWriteAccessTokenFiletake on their own file paths. Cleanup and a concurrent write are therefore not mutually exclusive. The outcome is still benign, because deletion is the intended result.cache.NewFileLockcreates<identity>.cleanup.lockinsideproviderDir, and cleanup never removes it. One stale file remains per cleaned identity, soproviderDirnever becomes empty.If either matters for your directory-emptiness checks, add a best-effort removal of the lock file after the callback returns.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/cloud/gcp/files.go` around lines 305 - 321, Update the cleanup flow around withFileLock so it uses the same lock coordination as WriteADCFile, WritePropertiesFile, and WriteAccessTokenFile, and best-effort removes the generated cleanup lock file after the callback completes. Preserve the existing cleanup error aggregation and return behavior while ensuring the lock artifact does not remain in providerDir.pkg/auth/providers/azure/device_code_cache.go (1)
567-578: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueName the timeout constant.
The
10*time.Secondvalue is a magic number here, while the sibling helpers inpkg/auth/cloud/aws/files.goandpkg/auth/cloud/azure/files.gouse afileLockTimeoutconstant. Declare a package-level constant in this package for the same value. Purely cosmetic; take it or leave it.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/providers/azure/device_code_cache.go` around lines 567 - 578, Replace the magic 10*time.Second value in withAzureFileLock with a package-level fileLockTimeout constant set to the same duration, matching the sibling helpers’ naming and usage.pkg/auth/cloud/azure/msal_cache.go (1)
54-69: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueThe MSAL context is checked but not propagated.
Line 50 checks
ctx.Err(), thenwithFileLockbuilds a fresh background context with its own timeout. If the MSAL caller cancels while the lock is contended,Replacestill blocks for the fullfileLockTimeout. IfwithFileLockgains a context parameter, passctxhere. Optional, and it pairs with the same note onpkg/auth/cloud/aws/files.go.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/cloud/azure/msal_cache.go` around lines 54 - 69, Update the cache replacement flow around withFileLock in Replace to accept and propagate the caller’s ctx instead of creating an independent background context, so cancellation while waiting for the file lock stops the operation promptly. Preserve the existing read, unmarshal, and error-handling behavior inside the lock callback.pkg/auth/cloud/aws/files.go (1)
70-81: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider accepting a
context.Contextparameter.
withFileLockalways creates a fresh background context. Callers such asDeleteIdentity(line 644) already hold actx, so caller cancellation cannot abort lock acquisition. Passing the caller context keeps cancellation working and matches the guideline thatcontext.Contextis for cancellation and deadlines.♻️ Proposed signature change
-func withFileLock(path string, fn func() error) error { - ctx, cancel := context.WithTimeout(context.Background(), fileLockTimeout) +func withFileLock(ctx context.Context, path string, fn func() error) error { + ctx, cancel := context.WithTimeout(ctx, fileLockTimeout) defer cancel()This one is optional; the current form is safe.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/cloud/aws/files.go` around lines 70 - 81, Update withFileLock to accept a caller-provided context.Context and derive the existing timeout context from it instead of context.Background(). Pass the relevant caller context, such as DeleteIdentity’s ctx, through every withFileLock call while preserving the timeout and error-wrapping behavior.Source: Coding guidelines
pkg/auth/cloud/azure/files.go (1)
153-169: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueConsider a shared read lock here.
LoadCredentialsperforms a read only, but it takes the exclusive lock. Concurrent reads across processes now serialize. The cache lock layer in this stack adds a shared-lock API, so this call site is a natural fit for it. Not a blocker; the current form is correct.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/cloud/azure/files.go` around lines 153 - 169, Update LoadCredentials to use the cache lock layer’s shared/read-lock API around the read-only credential loading callback instead of withFileLock’s exclusive lock. Preserve the existing file reading, JSON unmarshalling, logging, and error propagation behavior.pkg/cache/file_cache_test.go (1)
46-51: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLet the mock represent contention without an error.
The production API has a distinct
(false, nil)result. This mock only returnsfalsewhenwithRLockErris set and otherwise always invokesfn. Add a separate acquisition-status field that defaults totrue, then add coverage for(false, nil).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/cache/file_cache_test.go` around lines 46 - 51, Update mockFileLock.TryWithRLock to use a separate acquisition-status field that defaults to true, returning false with a nil error when configured to simulate contention and invoking fn only when the lock is acquired. Add test coverage for the (false, nil) result while preserving existing error behavior through withRLockErr.Source: Coding guidelines
pkg/cache/filelock_unix_test.go (1)
212-230: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCover the complete
TryWithRLockresult matrix.This test covers only
(false, nil)under contention. Add or retain table-driven cases for successful Unix acquisition, callback-error propagation, and acquisition errors. The Windows test covers only the no-op success path.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/cache/filelock_unix_test.go` around lines 212 - 230, Expand TestTryWithRLock_SkipsContendedRead into table-driven coverage for the complete TryWithRLock result matrix: successful Unix acquisition, callback-error propagation, contention returning (false, nil), and acquisition errors. Assert acquired status, callback execution, and returned errors for each case, and retain the existing contention behavior; also add equivalent Windows coverage beyond the current no-op success path if supported by the test structure.Source: Coding guidelines
pkg/provisioner/workdir/metadata_lock_unix.go (1)
23-24: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueName the timeout.
500*time.Millisecondis a magic value on the write path. A named package constant such asmetadataLockTimeoutdocuments the intent and keeps the Unix and Windows implementations aligned. Also confirm 500 ms matches the previous flock polling budget, because a shorter budget turns contention into a hard error for callers.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/provisioner/workdir/metadata_lock_unix.go` around lines 23 - 24, Replace the inline 500*time.Millisecond timeout in the metadata lock write path with a named package constant such as metadataLockTimeout, and use that constant in both Unix and Windows implementations. Verify the constant remains 500 milliseconds so it preserves the previous flock polling budget and existing contention behavior.pkg/component/helm/repository.go (2)
47-87: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLock scope and path handling look right.
The call uses
cache.NewFileLockAtPathwith the existingrepositoryLockPathhelper, so the lock path stays<repoFile without ext>.lockand no second.locksuffix is appended. All read-modify-write work now runs inside the lock, which closes the earlier gap between load and write.One optional cleanup: the callback body is the bulk of the function. Extracting it into a named helper such as
updateRepositories(settings, repoFile, repositories)would keepsetupHelmRepositoriesa short, linear pipeline.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/component/helm/repository.go` around lines 47 - 87, Optionally extract the lock callback body from setupHelmRepositories into a named helper such as updateRepositories(settings, repoFile, repositories), preserving the existing load, repository update, index download, and write behavior. Keep setupHelmRepositories focused on context creation, lock acquisition, and error handling.
43-45: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winTighten the directory permissions.
os.ModePermrequests 0777. The Helm repository file written at Line 77 can holdUsernameandPasswordvalues fromrepo.Entry, so the parent directory should not be world-writable. Use 0o700 (or 0o755 if other tools must read it). The!os.IsExist(err)guard is also redundant, becauseos.MkdirAllreturns nil when the directory already exists.🔒 Suggested change
- if err := os.MkdirAll(filepath.Dir(repoFile), os.ModePerm); err != nil && !os.IsExist(err) { + if err := os.MkdirAll(filepath.Dir(repoFile), repositoryDirPerm); err != nil { return err }Declare
repositoryDirPermnext to the existingrepositoryFilePermconstant.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/component/helm/repository.go` around lines 43 - 45, In the repository directory creation logic, replace os.ModePerm with a dedicated repositoryDirPerm constant declared beside repositoryFilePerm, using 0o700 (or 0o755 when shared read access is required). Simplify the MkdirAll error handling by removing the redundant os.IsExist guard while preserving error returns from MkdirAll.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/auth/cloud/azure/setup.go`:
- Around line 628-634: Widen each Azure profile read-modify-write critical
section so the lock callback owns the complete operation: in
pkg/auth/cloud/azure/setup.go lines 628-634, move the read,
UpdateSubscriptionsInProfile merge, and marshal inside withFileLock; apply the
same change to the entry merge loop and marshal at lines 753-759; in
pkg/auth/providers/azure/device_code_cache.go lines 534-541, move the read,
UpdateSubscriptionsInProfile merge, and marshal inside withAzureFileLock. Use
the AWS WriteCredentials flow as the model, with only the final write and
logging remaining after the callback as appropriate.
In `@pkg/auth/cloud/docker/config.go`:
- Around line 137-145: Update ConfigManager.withConfigLock to use a context with
a finite deadline instead of context.Background when calling WithLockContext,
ensuring WriteAuth and RemoveAuth cannot wait indefinitely on a stale or
long-held lock. Preserve existing ErrCacheLocked wrapping and error propagation,
including converting a background timeout into the established lock error where
appropriate.
In `@pkg/auth/providers/azure/device_code_cache.go`:
- Around line 557-562: Update the error handling around withAzureFileLock in the
device-code cache write path so failures from both lock acquisition and
os.WriteFile are reported accurately. Replace the lock-specific log message with
a generic cache-write failure message, or distinguish
azureCloud.ErrFileLockTimeout before logging, while preserving the existing
return-false behavior.
In `@pkg/provisioner/workdir/metadata_lock_unix.go`:
- Around line 65-71: Update the error handling around TryWithRLock to check
acquired before interpreting err: when the lock was acquired, return the
callback error unchanged, preserving the precise errors built by the read and
unmarshal paths; only wrap err with the read-lock acquisition explanation and
ErrWorkdirMetadata when acquired is false.
---
Nitpick comments:
In `@pkg/auth/cloud/aws/files.go`:
- Around line 70-81: Update withFileLock to accept a caller-provided
context.Context and derive the existing timeout context from it instead of
context.Background(). Pass the relevant caller context, such as DeleteIdentity’s
ctx, through every withFileLock call while preserving the timeout and
error-wrapping behavior.
In `@pkg/auth/cloud/azure/files.go`:
- Around line 153-169: Update LoadCredentials to use the cache lock layer’s
shared/read-lock API around the read-only credential loading callback instead of
withFileLock’s exclusive lock. Preserve the existing file reading, JSON
unmarshalling, logging, and error propagation behavior.
In `@pkg/auth/cloud/azure/msal_cache.go`:
- Around line 54-69: Update the cache replacement flow around withFileLock in
Replace to accept and propagate the caller’s ctx instead of creating an
independent background context, so cancellation while waiting for the file lock
stops the operation promptly. Preserve the existing read, unmarshal, and
error-handling behavior inside the lock callback.
In `@pkg/auth/cloud/gcp/files.go`:
- Around line 305-321: Update the cleanup flow around withFileLock so it uses
the same lock coordination as WriteADCFile, WritePropertiesFile, and
WriteAccessTokenFile, and best-effort removes the generated cleanup lock file
after the callback completes. Preserve the existing cleanup error aggregation
and return behavior while ensuring the lock artifact does not remain in
providerDir.
In `@pkg/auth/providers/azure/device_code_cache.go`:
- Around line 567-578: Replace the magic 10*time.Second value in
withAzureFileLock with a package-level fileLockTimeout constant set to the same
duration, matching the sibling helpers’ naming and usage.
In `@pkg/cache/file_cache_test.go`:
- Around line 46-51: Update mockFileLock.TryWithRLock to use a separate
acquisition-status field that defaults to true, returning false with a nil error
when configured to simulate contention and invoking fn only when the lock is
acquired. Add test coverage for the (false, nil) result while preserving
existing error behavior through withRLockErr.
In `@pkg/cache/filelock_unix_test.go`:
- Around line 212-230: Expand TestTryWithRLock_SkipsContendedRead into
table-driven coverage for the complete TryWithRLock result matrix: successful
Unix acquisition, callback-error propagation, contention returning (false, nil),
and acquisition errors. Assert acquired status, callback execution, and returned
errors for each case, and retain the existing contention behavior; also add
equivalent Windows coverage beyond the current no-op success path if supported
by the test structure.
In `@pkg/component/helm/repository.go`:
- Around line 47-87: Optionally extract the lock callback body from
setupHelmRepositories into a named helper such as updateRepositories(settings,
repoFile, repositories), preserving the existing load, repository update, index
download, and write behavior. Keep setupHelmRepositories focused on context
creation, lock acquisition, and error handling.
- Around line 43-45: In the repository directory creation logic, replace
os.ModePerm with a dedicated repositoryDirPerm constant declared beside
repositoryFilePerm, using 0o700 (or 0o755 when shared read access is required).
Simplify the MkdirAll error handling by removing the redundant os.IsExist guard
while preserving error returns from MkdirAll.
In `@pkg/provisioner/workdir/metadata_lock_unix.go`:
- Around line 23-24: Replace the inline 500*time.Millisecond timeout in the
metadata lock write path with a named package constant such as
metadataLockTimeout, and use that constant in both Unix and Windows
implementations. Verify the constant remains 500 milliseconds so it preserves
the previous flock polling budget and existing contention behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 9450e2c3-95b1-4ca7-8ca9-8e5a5af19bbd
📒 Files selected for processing (15)
pkg/auth/cloud/aws/files.gopkg/auth/cloud/azure/files.gopkg/auth/cloud/azure/msal_cache.gopkg/auth/cloud/azure/setup.gopkg/auth/cloud/docker/config.gopkg/auth/cloud/gcp/files.gopkg/auth/providers/azure/device_code_cache.gopkg/cache/file_cache_test.gopkg/cache/filelock.gopkg/cache/filelock_unix.gopkg/cache/filelock_unix_test.gopkg/cache/filelock_windows.gopkg/cache/filelock_windows_test.gopkg/component/helm/repository.gopkg/provisioner/workdir/metadata_lock_unix.go
Dependency Review✅ No vulnerabilities or license issues found.Scanned FilesNone |
|
Warning Release Documentation RequiredThis PR is labeled
|
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #2856 +/- ##
==========================================
+ Coverage 82.62% 82.75% +0.12%
==========================================
Files 1860 1860
Lines 180353 180240 -113
==========================================
+ Hits 149025 149159 +134
+ Misses 23445 23295 -150
+ Partials 7883 7786 -97
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
The file-locking consolidation refactor introduced new lock-wrapper helpers (withFileLock, withConfigLock, withAzureFileLock, withMetadataFileLockUnix, TryWithRLock) across aws/azure/gcp/docker auth, helm repositories, and workdir metadata, but none of their lock-failure branches were exercised, dropping PR patch coverage to 68% against the 85% gate. Add deterministic, fast lock-denial tests (unlockable lock paths, no real timeouts) for each wrapper's error path. Co-Authored-By: Claude Sonnet 5 <[email protected]>
pkg/cache/filelock_windows.go intentionally always executes fn() and never returns ErrCacheLocked (native Windows locks previously caused cache-operation timeouts). The lock-denial tests added for the file locking consolidation assumed a real lock attempt, so they failed CI on windows: TestWithFileLock_WrapsErrCacheLocked (aws), TestConfigManager_WithConfigLock_WrapsErrCacheLocked (docker), and TestWithAzureFileLock_WrapsErrCacheLocked / TestDeviceCodeProvider_updateAzureProfile_LockFailure (providers/azure). Skip them on windows, matching the pattern already used in the gcp, helm, and azure/files sibling tests. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Widens lock-timeout coverage (docker config, AWS/Azure ctx propagation), adds a shared read-lock path for Azure credential loads, fixes a leaked GCP cleanup lock file, replaces magic lock-timeout literals with named constants, and extracts a helm repository-update helper for testability. Adds targeted failure-injection tests across the touched packages to close the Codecov patch-coverage gap (76.13% -> 85.57%). Co-Authored-By: Claude Sonnet 5 <[email protected]>
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (6)
pkg/cache/filelock_unix_test.go (1)
260-268: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe "lock acquisition error" case depends on 1ms timing.
TryWithRLockuses a 1ms context. It returns(false, cacheLockError(err))only whenctx.Err()is still nil after the failed open. If the 1ms budget expires first on a loaded CI machine, the same case returns(false, nil)and theErrCacheLockedassertion fails. The ENOENT open is normally far faster than 1ms, so this is a narrow flake window, not a current defect. If flakes appear, consider asserting the union of both allowed outcomes for this case only.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/cache/filelock_unix_test.go` around lines 260 - 268, The “lock acquisition error” test is timing-sensitive because TryWithRLock may return either ErrCacheLocked or nil when its 1ms context expires. Update this test case’s assertion to accept both outcomes while preserving wantAcquired=false and wantExecuted=false, without changing other lock behavior tests.pkg/auth/cloud/aws/files.go (1)
221-221: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffThe write paths still pass
context.Background()while removal paths now thread the caller context.
RemoveConfigProfileandRemoveCredentialsProfileacceptctxand forward it, so a cancelled command aborts a contended removal.WriteCredentialsandWriteConfigkeepcontext.Background(), so a cancelled command still waits the fullfileLockTimeouton a contended write. That asymmetry is not a bug today, but it makes the locking contract uneven across the same file manager. Threadingctxthrough the two write methods would need signature changes at their callers, so it fits a follow-up.Also applies to: 315-315
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/cloud/aws/files.go` at line 221, Update the write paths in WriteCredentials and WriteConfig to accept caller-provided context and pass it to withFileLock instead of using context.Background(). Propagate the signature changes through all callers so cancelled commands can abort contended writes consistently with RemoveConfigProfile and RemoveCredentialsProfile.pkg/auth/cloud/docker/config_test.go (1)
309-315: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider extracting the Windows and root skip pair into a helper.
This same two-check pattern appears as
skipIfCannotDenyDirWriteinpkg/auth/cloud/gcp/files_test.go,pkg/auth/cloud/azure/setup_test.go, andpkg/auth/providers/azure/device_code_cache_test.go. A local helper in this package keeps the intent in one place if more permission tests land here. Test helpers are not importable across packages, so a small per-package copy is the expected shape.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/cloud/docker/config_test.go` around lines 309 - 315, The permission-test setup in TestConfigManager_SaveConfig_WriteFailure should be extracted into a package-local skipIfCannotDenyDirWrite helper, matching the existing helper pattern in the referenced test packages. Replace the duplicated Windows and root checks with a call to this helper, preserving both skip conditions and messages.pkg/auth/cloud/azure/setup_test.go (1)
25-33: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThis package now has two helpers for the same job.
skipIfCannotDenyDirWritehere usesos.Getuid(), whilerequireLockDeniedinpkg/auth/cloud/azure/msal_cache_test.goLines 175-187 performs the same Windows and root checks withos.Geteuid()plus achmod. Both live in packageazure, so either can call the other. Folding the skip logic into one helper removes the drift. TherequireLockDeniedname also reads like a testifyrequireassertion, while it actually skips.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/cloud/azure/setup_test.go` around lines 25 - 33, Consolidate the duplicate Windows/root permission-skip logic by reusing a single helper between skipIfCannotDenyDirWrite and requireLockDenied, and remove the redundant helper implementation. Rename requireLockDenied to a skip-oriented name if it remains the shared helper, preserving its existing effective-UID and chmod behavior and updating all callers.pkg/auth/cloud/gcp/files_test.go (1)
497-499: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe Windows skip message no longer matches every caller.
skipIfCannotDenyDirWritenow guards write-permission tests such asTestWriteADCFile_WriteFailure_WrapsSentinel, where the reason is that Windows does not enforce directory write bits, not that file locking is a no-op. The sibling helper inpkg/auth/cloud/azure/setup_test.gouses the accurate wording. Aligning the message keeps skip output honest.✏️ Proposed message tweak
if runtime.GOOS == "windows" { - t.Skip("Windows file locking is a no-op fallback and never returns ErrCacheLocked") + t.Skip("directory write-permission bits are not enforced the same way on Windows") }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/cloud/gcp/files_test.go` around lines 497 - 499, Update the Windows skip message in skipIfCannotDenyDirWrite to accurately describe that Windows does not enforce directory write permissions, rather than referring only to file locking or ErrCacheLocked; preserve the existing skip condition and behavior.pkg/auth/cloud/azure/files_test.go (1)
588-605: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThis read-lock test depends on the 1ms fallback window.
cache.WithRLockruns the callback without a lock when the acquire error isErrAcquireand its 1ms context has already expired (pkg/cache/filelock_unix.goLines 49-61). The test relies on the ENOENT open finishing inside that 1ms so the hard-error path is taken. If a loaded runner expires the context first,withFileRLockreturns nil andexecutedbecomes true, flipping both assertions.The window is small, so this is not a defect today. Flag it here because the same shape appears in
pkg/cache/filelock_unix_test.go. If flakes show up, the deterministic alternative is to make the lock path unopenable for a reason that cannot race, such as an unsearchable parent directory.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/cloud/azure/files_test.go` around lines 588 - 605, Make TestWithFileRLock_WrapsErrCacheLocked deterministic by replacing the nonexistent-subdirectory setup with a lock path under an unsearchable parent directory, avoiding reliance on the 1ms acquisition window. Preserve the assertions that withFileRLock returns ErrFileLockTimeout and does not execute the callback, and apply the same pattern to the corresponding file-lock test if applicable.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/auth/cloud/aws/files_test.go`:
- Around line 1108-1111: Guard permission-based failure tests against
environments where permission bits are ineffective: in
pkg/auth/cloud/aws/files_test.go, add a package-local skipIfCannotDenyDirWrite
helper and call it from all six permission-based tests at lines 1108, 1134,
1187, 1209, 1233, and 1254, replacing their Windows-only skips. In
pkg/component/helm/repository_test.go lines 122-131 and 256-271, add an
os.Getuid() == 0 skip alongside the existing Windows checks so root does not
proceed with the lock-file or repositories.yaml permission tests.
In `@pkg/auth/cloud/azure/files.go`:
- Around line 127-145: Update WriteCredentials to replace the truncating
os.WriteFile call with the existing atomic file-writing helper, such as
WriteFileAtomic, while preserving PermissionRW and existing error wrapping.
Apply the same change to the other credentials-writing path around the
referenced symbol so readers never observe partially written files.
In `@pkg/auth/cloud/azure/msal_cache_test.go`:
- Around line 239-251: Update TestNewMSALCache_RealmIsolatesDefaultPath to use
the existing temporary-home setup pattern from TestNewMSALCache, redirecting the
relevant home-directory environment variables before calling NewMSALCache and
restoring them afterward. Build expectedPath from that temporary home so the
test does not create directories under the real user home.
In `@pkg/auth/cloud/gcp/files.go`:
- Around line 202-211: Replace the file-specific locking around withFileLock and
the other write operations with one persistent per-identity lock target located
outside directories removed by CleanupIdentityFiles. Use that same target in all
three write functions and CleanupIdentityFiles, and preserve the lock file after
WithLockContext returns so concurrent callers cannot bypass mutual exclusion.
Add contention coverage for cleanup racing with each write operation.
---
Nitpick comments:
In `@pkg/auth/cloud/aws/files.go`:
- Line 221: Update the write paths in WriteCredentials and WriteConfig to accept
caller-provided context and pass it to withFileLock instead of using
context.Background(). Propagate the signature changes through all callers so
cancelled commands can abort contended writes consistently with
RemoveConfigProfile and RemoveCredentialsProfile.
In `@pkg/auth/cloud/azure/files_test.go`:
- Around line 588-605: Make TestWithFileRLock_WrapsErrCacheLocked deterministic
by replacing the nonexistent-subdirectory setup with a lock path under an
unsearchable parent directory, avoiding reliance on the 1ms acquisition window.
Preserve the assertions that withFileRLock returns ErrFileLockTimeout and does
not execute the callback, and apply the same pattern to the corresponding
file-lock test if applicable.
In `@pkg/auth/cloud/azure/setup_test.go`:
- Around line 25-33: Consolidate the duplicate Windows/root permission-skip
logic by reusing a single helper between skipIfCannotDenyDirWrite and
requireLockDenied, and remove the redundant helper implementation. Rename
requireLockDenied to a skip-oriented name if it remains the shared helper,
preserving its existing effective-UID and chmod behavior and updating all
callers.
In `@pkg/auth/cloud/docker/config_test.go`:
- Around line 309-315: The permission-test setup in
TestConfigManager_SaveConfig_WriteFailure should be extracted into a
package-local skipIfCannotDenyDirWrite helper, matching the existing helper
pattern in the referenced test packages. Replace the duplicated Windows and root
checks with a call to this helper, preserving both skip conditions and messages.
In `@pkg/auth/cloud/gcp/files_test.go`:
- Around line 497-499: Update the Windows skip message in
skipIfCannotDenyDirWrite to accurately describe that Windows does not enforce
directory write permissions, rather than referring only to file locking or
ErrCacheLocked; preserve the existing skip condition and behavior.
In `@pkg/cache/filelock_unix_test.go`:
- Around line 260-268: The “lock acquisition error” test is timing-sensitive
because TryWithRLock may return either ErrCacheLocked or nil when its 1ms
context expires. Update this test case’s assertion to accept both outcomes while
preserving wantAcquired=false and wantExecuted=false, without changing other
lock behavior tests.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 98e91bea-33f6-4d34-96a3-96bf32d15265
📒 Files selected for processing (24)
pkg/auth/cloud/aws/files.gopkg/auth/cloud/aws/files_test.gopkg/auth/cloud/azure/files.gopkg/auth/cloud/azure/files_test.gopkg/auth/cloud/azure/msal_cache.gopkg/auth/cloud/azure/msal_cache_test.gopkg/auth/cloud/azure/setup.gopkg/auth/cloud/azure/setup_test.gopkg/auth/cloud/docker/config.gopkg/auth/cloud/docker/config_test.gopkg/auth/cloud/gcp/files.gopkg/auth/cloud/gcp/files_test.gopkg/auth/providers/azure/device_code_cache.gopkg/auth/providers/azure/device_code_cache_test.gopkg/cache/file_cache_test.gopkg/cache/filelock.gopkg/cache/filelock_unix.gopkg/cache/filelock_unix_test.gopkg/cache/filelock_windows.gopkg/cache/filelock_windows_test.gopkg/component/helm/repository.gopkg/component/helm/repository_test.gopkg/provisioner/workdir/metadata_lock_unix.gopkg/provisioner/workdir/metadata_lock_unix_test.go
🚧 Files skipped from review as they are similar to previous changes (11)
- pkg/cache/filelock_windows_test.go
- pkg/auth/cloud/azure/msal_cache.go
- pkg/cache/filelock.go
- pkg/cache/file_cache_test.go
- pkg/auth/cloud/docker/config.go
- pkg/cache/filelock_unix.go
- pkg/auth/providers/azure/device_code_cache.go
- pkg/cache/filelock_windows.go
- pkg/provisioner/workdir/metadata_lock_unix.go
- pkg/component/helm/repository.go
- pkg/auth/cloud/azure/setup.go
…-safe tests Addresses a second round of CodeRabbit review findings on the file-locking PR: GCP write helpers and CleanupIdentityFiles now share a single persistent per-identity lock (previously each locked a different path, so cleanup could race a concurrent write and delete a directory out from under it -- also reverts the prior fix that removed the lock file after use, which itself introduced an unlink race for waiters). Azure credential writes now use an atomic write so a best-effort concurrent read never observes a truncated file. Permission-based failure-injection tests in aws/files_test.go and helm/repository_test.go gain a root-uid guard, matching the pattern already used in the azure/gcp test packages. A realm-isolation test no longer creates directories under the real user home. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…g' into osterman/consolidate-file-locking
Bump fast-uri (transitive, via the pnpm.overrides entry) from 3.1.4 to 3.1.5, patching GHSA-7p8r-x3mc-p8w7 (CVE-2026-18446): a host-confusion parsing bug where fast-uri and Node's WHATWG URL disagree on the host extracted from a backslash-authority reference, which can defeat host-based allowlist/SSRF checks built on fast-uri. Verified the website still builds after the bump. Co-Authored-By: Claude Sonnet 5 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
pkg/auth/cloud/gcp/files_test.go (1)
514-524: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTable-drive the repeated lock-failure writer cases.
The three writer cases repeat the same permission and provider-directory setup. Use a table with the path initializer, operation, and expected sentinel. Keep
TestCleanupIdentityFiles_LockFailure_WrapsErrorseparate because it checks a different error contract.Verify that each table entry preserves its operation-specific sentinel assertion. As per coding guidelines, “Use table-driven tests for testing multiple scenarios in Go.”
Also applies to: 543-550, 566-573
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/cloud/gcp/files_test.go` around lines 514 - 524, Convert the three repeated writer lock-failure test cases into a table-driven test with entries for the path initializer, write operation, and expected sentinel error. Apply the shared provider-directory permission setup and execute each case through the table, preserving each operation-specific sentinel assertion. Keep TestCleanupIdentityFiles_LockFailure_WrapsError separate because it validates a different error contract.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/auth/cloud/gcp/files.go`:
- Around line 215-220: Update WriteADCFile, WritePropertiesFile, and
WriteAccessTokenFile in pkg/auth/cloud/gcp/files.go (anchor lines 215-220;
sibling lines 245-250 and 298-303) so each creates or resolves its parent
credential directory inside the withFileLock callback, after acquiring the
shared identity lock. Ensure transient missing-parent errors are handled before
returning the corresponding ErrWrite*File error, while preserving the existing
write behavior.
In `@pkg/component/helm/repository_test.go`:
- Around line 21-33: Update skipIfCannotDenyDirWrite to check os.Geteuid() == 0
instead of os.Getuid() == 0, and replace the duplicated Windows/root permission
checks in TestSetupHelmRepositories_LockUnavailable with a call to this shared
helper.
---
Nitpick comments:
In `@pkg/auth/cloud/gcp/files_test.go`:
- Around line 514-524: Convert the three repeated writer lock-failure test cases
into a table-driven test with entries for the path initializer, write operation,
and expected sentinel error. Apply the shared provider-directory permission
setup and execute each case through the table, preserving each
operation-specific sentinel assertion. Keep
TestCleanupIdentityFiles_LockFailure_WrapsError separate because it validates a
different error contract.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 9df5147b-19b0-4273-9c18-0031826b7f22
📒 Files selected for processing (6)
pkg/auth/cloud/aws/files_test.gopkg/auth/cloud/azure/files.gopkg/auth/cloud/azure/msal_cache_test.gopkg/auth/cloud/gcp/files.gopkg/auth/cloud/gcp/files_test.gopkg/component/helm/repository_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
- pkg/auth/cloud/azure/files.go
- pkg/auth/cloud/aws/files_test.go
- pkg/auth/cloud/azure/msal_cache_test.go
…ot skip GCP's WriteADCFile/WritePropertiesFile/WriteAccessTokenFile resolved their credential paths (which create the parent identity directory) before acquiring the shared identity lock added in the prior commit, leaving a window where a concurrent CleanupIdentityFiles could remove that directory between creation and the write. Path resolution now happens inside the lock callback so directory creation and the write are atomic with respect to cleanup. Also switches the shared skipIfCannotDenyDirWrite test helper (and one remaining duplicated inline check) from os.Getuid() to os.Geteuid(): permission checks are gated on the effective UID, not the real one. Co-Authored-By: Claude Sonnet 5 <[email protected]>
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
TryWithRLock (and its WithRLock sibling) gave the shared-lock attempt only 1ms before giving up. That's tight enough that ordinary scheduling/IO jitter on a loaded CI runner -- not actual lock contention -- could miss the deadline, and loadMetadataWithReadLockUnix treats a missed deadline identically to "another process holds the lock": it silently returns nil, nil. DefaultWorkdirManager.ListWorkdirs then drops that workdir from the listing entirely, which is what caused TestDefaultWorkdirManager_ListWorkdirs to intermittently fail in CI (#2856 introduced the 1ms budget). Bump the internal timeout to 50ms, comfortably above filelock's 10ms retry interval, so a fast writer's exclusive lock also has a real chance to clear within budget while still failing far faster than the 500ms/2s timeouts used for actual blocking waits elsewhere in these packages. Co-Authored-By: Claude Sonnet 5 <[email protected]>
|
These changes were released in v1.225.0. |
* feat(toolchain): support Aqua github_archive package type Adds the github_archive package type to the Aqua-compatible toolchain registry, matching upstream aquaproj/aqua behavior. Resolves the URL as https://github.com/{owner}/{repo}/archive/refs/tags/{version}.tar.gz and mirrors aqua's GetFormat() by hardcoding tar.gz (Asset, URL, Format, and FormatOverrides are ignored for this type). Files[].src supports the documented {{trimV .Version}}/path idiom via existing template expansion. Unblocks Aqua registry entries for tools shipped as repository archives (adr-tools, tfenv, tgswitch, etc.) without registry-level workarounds. Co-Authored-By: Claude Opus 4.7 <[email protected]> * style(toolchain): reformat ar.ListAll calls per gofumpt CI's gofumpt flagged three pre-existing ar.ListAll(ctx, ...) call sites in aqua_test.go that the local hook had been missing. Apply the suggested fix so the file passes the CI pre-commit step. Co-Authored-By: Claude Opus 4.7 <[email protected]> * Address aqua github archive review comments * feat(toolchain): support Aqua github_content package type Adds the github_content package type to the Aqua-compatible toolchain registry, matching upstream aquaproj/aqua behavior. Resolves the URL as https://raw.githubusercontent.com/{owner}/{repo}/{version}/{path} for single-file downloads from a GitHub repo at a tag. The Asset, URL, Format, and FormatOverrides fields are intentionally ignored; the new Path field on the Tool struct holds the file path inside the repo. Field plumbing extends through AquaPackage -> Tool conversion, version override application, and resetByPkgType (which now also clears Path when switching away from github_content). New pure helpers (validateGitHubContentFields, formatGitHubContentURL) split validation from formatting for trivial unit testing without an Installer instance. Unblocks Aqua registry entries for tools shipped as a single raw file (kubens, kubectx, and many one-file shell-script projects) without registry-level workarounds. The remaining unsupported Aqua types (go_install, go_build_install, cargo) require invoking a language toolchain at install time rather than downloading an artifact and are deferred to a follow-up issue. Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(toolchain): validate github_content Path and correct unsupported-type doc Reject absolute or ..-traversal Path values for github_content tools, and stop recommending the also-unsupported go_install as an alternative to go_build_install in the toolchain docs. Addresses CodeRabbit review on #2416. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs(toolchain): don't describe github_archive as a pre-built release github_archive downloads GitHub's auto-generated source tarball, not a compiled binary, so it doesn't belong alongside github_release/http as a pre-built alternative to go_build_install. Addresses CodeRabbit follow-up review on #2416. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs(toolchain): list format_overrides as ignored, fix comment periods Blog post said only asset/url/format are ignored for github_archive, but the code doc comments also ignore format_overrides -- make the two match. Also adds trailing periods to two floating section-banner comments in aqua_test.go per the godot comment-style convention. Addresses CodeRabbit follow-up review on #2416. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(workdir): widen try-read-lock timeout to stop spurious CI drops TryWithRLock (and its WithRLock sibling) gave the shared-lock attempt only 1ms before giving up. That's tight enough that ordinary scheduling/IO jitter on a loaded CI runner -- not actual lock contention -- could miss the deadline, and loadMetadataWithReadLockUnix treats a missed deadline identically to "another process holds the lock": it silently returns nil, nil. DefaultWorkdirManager.ListWorkdirs then drops that workdir from the listing entirely, which is what caused TestDefaultWorkdirManager_ListWorkdirs to intermittently fail in CI (#2856 introduced the 1ms budget). Bump the internal timeout to 50ms, comfortably above filelock's 10ms retry interval, so a fast writer's exclusive lock also has a real chance to clear within budget while still failing far faster than the 500ms/2s timeouts used for actual blocking waits elsewhere in these packages. Co-Authored-By: Claude Sonnet 5 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]> Co-authored-by: Andriy Knysh <[email protected]>
what
pkg/cache.FileLock, covering cloud configuration, Helm repositories, and workdir metadata.why
gofrs/flockacquisition and release logic.references
Summary by CodeRabbit
Bug Fixes
New Features