Skip to content

fix: prevent duplicate MFA notifications across concurrent sessions#14

Merged
GeiserX merged 3 commits into
mainfrom
fix/cross-process-lock
Apr 28, 2026
Merged

fix: prevent duplicate MFA notifications across concurrent sessions#14
GeiserX merged 3 commits into
mainfrom
fix/cross-process-lock

Conversation

@GeiserX
Copy link
Copy Markdown
Owner

@GeiserX GeiserX commented Apr 28, 2026

Summary

  • Add atomic cross-process lock (~/.config/cc-aws-keepalive/.auto-login.lock) using O_CREAT|O_EXCL so only one auto-login runs system-wide
  • Proactive (aws-cred-check.mjs): if lock held, silently skips — another session is already handling it
  • Reactive (aws-auth-refresh.mjs): if lock held, polls every 3s waiting for the other session's login to finish, then piggybacks on the refreshed creds
  • Stale locks (>5min) are auto-cleaned
  • Added coverage/ to .gitignore

Problem

Multiple CC sessions hit Bedrock 403 simultaneously → each independently spawned the expect script → multiple MFA notifications (6-7 overnight with just 2 sessions open).

Test plan

  • All 40 unit tests pass (npm test)
  • CI matrix passes
  • Manual: open 2 sessions, let creds expire, verify only 1 notification fires

Summary by CodeRabbit

Release Notes

  • New Features

    • Auto-login now prevents concurrent re-authentication attempts; if authentication is already in progress, requests wait up to 180 seconds for completion before timing out.
  • Chores

    • Updated build configuration to exclude coverage files from version control.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 28, 2026

Warning

Rate limit exceeded

@GeiserX has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 39 minutes and 52 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ee105bd5-3cce-43d5-91f6-e735729cf437

📥 Commits

Reviewing files that changed from the base of the PR and between cca0219 and 57c0aa3.

📒 Files selected for processing (5)
  • .gitignore
  • aws-auth-refresh.mjs
  • aws-cred-check.mjs
  • lib.mjs
  • lib.test.mjs
📝 Walkthrough

Walkthrough

Introduces a cross-process locking mechanism for auto-login using timestamp-based lockfile coordination, replacing the previous filesystem cooldown approach. Updates auto-login initiation in aws-cred-check.mjs and aws-auth-refresh.mjs to acquire and release locks via new functions in lib.mjs. Also excludes the coverage/ directory from version control.

Changes

Cohort / File(s) Summary
Build Configuration
.gitignore
Adds coverage/ directory to excluded paths.
Lock Mechanism
lib.mjs
Introduces tryAcquireAutoLoginLock() and releaseAutoLoginLock() functions managing a centralized lockfile at ~/.config/cc-aws-keepalive/.auto-login.lock with 300-second stale-lock detection and atomic file creation.
Auto-login Flow
aws-cred-check.mjs, aws-auth-refresh.mjs
Replaces filesystem cooldown checks with centralized lock acquisition. aws-cred-check.mjs spawns auto-login only if lock acquired; aws-auth-refresh.mjs implements lock-aware retry logic with 180-second polling window.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly addresses the main change: preventing duplicate MFA notifications through cross-process locking.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/cross-process-lock

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 28, 2026

Codecov Report

❌ Patch coverage is 86.66667% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.53%. Comparing base (8b4ae94) to head (57c0aa3).

Files with missing lines Patch % Lines
lib.mjs 86.66% 4 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##              main      #14      +/-   ##
===========================================
- Coverage   100.00%   97.53%   -2.47%     
===========================================
  Files            2        2              
  Lines          133      162      +29     
  Branches        31       37       +6     
===========================================
+ Hits           133      158      +25     
- Misses           0        4       +4     
Files with missing lines Coverage Δ
lib.mjs 97.14% <86.66%> (-2.86%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@aws-auth-refresh.mjs`:
- Around line 39-48: The wait loop currently only checks getRemaining(config)
which can be null if metadata is missing, causing a timeout even after another
session refreshed credentials; update the loop in aws-auth-refresh.mjs (where
getRemaining, formatTime, execSync, process.exit are used) to perform an STS
fallback when getRemaining(config) is falsy: call AWS STS GetCallerIdentity
(using the existing AWS SDK import or `@aws-sdk/client-sts`) to verify whether
current credentials are valid, and if that call succeeds treat it as a fresh
refresh (log using the same message with formatTime and call process.exit(0));
ensure STS errors are caught/ignored so the loop continues sleeping via
execSync("sleep 3") until timeout.
- Line 47: The code calls execSync("sleep 3") (line uses execSync("sleep 3"))
which is platform-dependent and should be replaced with a Node.js native delay;
change the surrounding function (where execSync is invoked) to be async and
replace the sleep call with an await new Promise(resolve => setTimeout(resolve,
3000)) (or an equivalent native timer) instead of any Atomics.wait busy-wait
approach, ensuring the function signature and callers are updated to handle the
async/await change.

In `@lib.mjs`:
- Around line 117-126: The tryAcquireAutoLoginLock function can fail when the
parent directory of LOCK_FILE doesn't exist; before calling writeFileSync(..., {
flag: "wx" }) ensure the lock directory exists by creating the parent directory
(use the dirname of LOCK_FILE) with recursive=true. Update
tryAcquireAutoLoginLock to create the directory prior to the writeFileSync call
so writeFileSync won't throw ENOENT when the ~/.config/cc-aws-keepalive
directory is missing.
🪄 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

Run ID: 765cf64c-418f-45a3-8752-c1a7650ad5af

📥 Commits

Reviewing files that changed from the base of the PR and between 8b4ae94 and cca0219.

📒 Files selected for processing (4)
  • .gitignore
  • aws-auth-refresh.mjs
  • aws-cred-check.mjs
  • lib.mjs

Comment thread aws-auth-refresh.mjs
Comment thread aws-auth-refresh.mjs Outdated
Comment thread lib.mjs
GeiserX added 2 commits April 28, 2026 10:07
Add atomic cross-process lock so only one auto-login runs system-wide.
Multiple CC sessions hitting 403 simultaneously no longer each spawn
their own expect script — the first acquires the lock, others either
skip (proactive) or poll waiting for fresh creds (reactive).
- Ensure state directory exists before lock creation (ENOENT fix)
- Replace execSync("sleep 3") with Atomics.wait (cross-platform)
- Add STS fallback in wait loop when getRemaining returns null
@GeiserX GeiserX force-pushed the fix/cross-process-lock branch from 430e5e8 to e5d6049 Compare April 28, 2026 08:07
Add 11 new tests covering:
- tryAcquireAutoLoginLock (fresh, held, stale)
- releaseAutoLoginLock (exists, missing)
- sleepSync timing
- loadConfig validation branches (unknown keys, numeric coercion,
  non-numeric string, non-string type, autoLoginMinutes warning)
@GeiserX GeiserX force-pushed the fix/cross-process-lock branch from e5d6049 to 57c0aa3 Compare April 28, 2026 08:10
@GeiserX GeiserX merged commit 73feaa5 into main Apr 28, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant