Repository navigation
fix(portal): lock token refresh + lint shell scripts in CI - #201
Conversation
… refresh Closes #199. The helper read the cache, exchanged the refresh token, and wrote the result with no mutual exclusion. Portal refresh tokens are single-use and rotating and mcp-remote also refreshes on launch, so two callers racing on one cache meant the loser got HTTP 400 invalid_grant and printed "the cached refresh token was already spent; re-run the consent flow" -- instructing the operator to re-consent for what is really a local concurrency bug. A process that read the pair before another rotated it could also leave a spent refresh token on disk paired with a still-valid access token, which is the exact cache state found at the start of the 2026-10-19 session. Changes: - advisory exclusive flock on <token-path>.lock around the whole read/exchange/write cycle; released in a finally block - re-read the cache INSIDE the lock, because another process may have rotated the pair between the first read and lock acquisition - --refresh-if-expiring SECONDS: no-op unless the access token expires within the threshold. Every refresh consumes a rotation, so an unconditional refresh from a scheduled caller needlessly widens the race window. - reject a negative --refresh-if-expiring with exit 2 - lock file is created 0600 and never unlinked, since removing it while another process holds it reopens the race the lock exists to close - platforms without fcntl skip the lock; the atomic write remains the only protection there Validation against a mock endpoint implementing single-use rotation with a 200ms window, seeded with an expired access token, 4 concurrent callers: - before: 2 of 4 failed with the misleading invalid_grant message - after, --refresh-if-expiring 600: 1 rotation, 3 no-ops, 0 failures - after, unconditional: 4 sequential rotations, 0 failures - lock file mode 0600, no temp residue, raced cache still authenticates - ruff check/format clean, py_compile clean, --check and argument validation exit codes as documented tx-agent: jcode tx-task: #199 tx-validated: test tx-scope: scripts/refresh-portal-token.py tx-intent: Remove the spurious invalid_grant and spent-token races from token refresh
Closes #200. scripts/ holds 73 bash files and no CI job linted them, so shellcheck findings could only ever arrive from third-party review bots. On PR #172 exactly that happened: bots reported shellcheck issues while every native gate ignored the file. Added as a step in the existing `quality` job rather than a new job, because hosted runners are capped at $0 (the macOS leg was already removed for that reason) and the single self-hosted runner already serialises every job with all open PRs queued behind it. Design: - lint only the scripts CHANGED in the current change set. A full scan costs roughly 5s per file, which is minutes on that runner. - gate at -S error only. The tree has 0 error-level findings and 50 pre-existing warning-level ones, so error-only is green today and still catches real breakage; warnings are reported informationally. - if shellcheck is missing, attempt install, then degrade to a ::warning:: annotation instead of blocking every PR on runner provisioning. Validation: bad probe (missing `then`) exits 1 with SC1049/SC1073/SC1050/ SC1072; clean probe and the merged scripts/test-portal-bridge.sh exit 0; workflow YAML parses and the step lands in the quality job. tx-agent: jcode tx-task: #200 tx-validated: lint tx-scope: .github/workflows/ci.yml tx-intent: Give shell scripts a native CI gate instead of relying on review bots
Thanks for using CodeAnt! 🎉We're free for open-source projects. if you're enjoying it, help us grow by sharing. Share on X · |
|
Caution Review failedThe pull request is closed. 📝 Summary
Merge Risk:
|
| """ | ||
| if fcntl is None: | ||
| return None | ||
| fd = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600) |
There was a problem hiding this comment.
WARNING: Lock file mode is only applied on creation
os.open(..., os.O_CREAT | os.O_RDWR, 0o600) only sets permissions when the file is first created. If .lock already exists with broader permissions (e.g. from an older version or a different umask), the mode is left as-is, so the 0600 guarantee claimed in the docstring is not enforced. Consider an os.chmod(lock_path, 0o600) (or fchmod on the fd) after open to guarantee owner-only access regardless of pre-existing state.
Code Review SummaryStatus: 1 Issue Found | Recommendation: Address before merge Overview
Issue Details (click to expand)WARNING
Files Reviewed (2 files)
Fix these issues in Kilo Cloud Reviewed by free · Input: 153.7K · Output: 2.5K · Cached: 206.3K |
|
…pying (#205) * ci(scripts): install shellcheck portably so the lint gate actually enforces The shell-lint step added in #201 never enforced anything. Its first run on master (2026-10-28, run 40640134851) logged: ::warning::shellcheck is unavailable on this runner; shell lint skipped. The step tried `apt-get`, but the self-hosted runner is a Linux box with no apt-get, so the install branch did nothing and the gate degraded to a warning. A green-looking step that lints nothing is worse than no step. Install a pinned static x86_64 shellcheck instead, verifying the SHA256 before installing, with apt kept as a fallback for runners that do have a package manager. curl or wget are both accepted since the runner has curl but a slim container may not. Validation in a clean debian:bookworm-slim container with no shellcheck preinstalled, running the step body under the same flags CI uses (`bash -e -o pipefail`): - shellcheck v0.10.0 installed, sha256 verified - clean changed script -> EXIT 0 - broken changed script (missing `then`) -> EXIT 1 with SC1049/SC1073/SC1050/SC1072 - a helper file without a shebang was also caught as SC2148, confirming the gate reports rather than merely runs actionlint on the modified ci.yml reports the same 12 pre-existing findings as master and none in the edited range. tx-agent: jcode tx-task: #200 tx-validated: test tx-scope: .github/workflows/ci.yml tx-intent: Make the shell lint gate actually enforce instead of silently skipping * ci(scripts): create the install dir before copying shellcheck into it The first portable-install version ordered the steps wrongly: the `cp` into ${HOME}/.local/bin ran before `mkdir -p ${HOME}/.local/bin`, so on a runner where /usr/local/bin is not writable the copy failed with cp: cannot create regular file '/home/kcode-run/.local/bin/shellcheck': No such file or directory and the step exited 1. Observed live on PR #204, run 122686981010. Create the directory first, and make the fallbacks explicit rather than relying on `||` chains: try /usr/local/bin, else copy into ${HOME}/.local/bin, and ensure the file is executable. Validation in a debian:bookworm-slim container running as a NON-ROOT user, so /usr/local/bin is not writable, under the CI's own flags (bash -e -o pipefail): - installed shellcheck v0.10.0 (sha256 verified), EXIT 0 on a clean change set - a broken changed script -> EXIT 1 with SC1049/SC1073/SC1050/SC1072 tx-agent: jcode tx-task: #200 tx-validated: test tx-scope: .github/workflows/ci.yml tx-intent: Fix the install-order bug that broke the shellcheck install on the runner
User description
Closes #199
Closes #200
Two related hygiene fixes found while validating the XJ-03 bridge: a concurrency bug in the token helper that was merged in #138, and the missing CI gate that let shell issues go unnoticed.
1. Token refresh raced with
mcp-remote(#199)scripts/refresh-portal-token.pyread the cache, exchanged the refresh token, and wrote the result with no mutual exclusion. Portal refresh tokens are single-use and rotating, andmcp-remoterefreshes on launch, so two callers on one cache meant the loser gotHTTP 400 invalid_grantand printed:That instructs the operator to re-consent for what is actually a local concurrency bug. Worse, a process that read the pair before another rotated it could leave a spent refresh token on disk paired with a still-valid access token — precisely the cache state found at the start of the 2026-10-19 session.
Reproduction
Mock endpoint implementing single-use rotation with a 200 ms window, seeded with an expired access token and
RT-1, 4 concurrent callers:invalid_grant--refresh-if-expiring 600Change
flockon<token-path>.lockaround the whole read/exchange/write cycle--refresh-if-expiring SECONDSso scheduled callers are a no-op unless the token is genuinely near expiry (every refresh consumes a rotation)0600, never unlinked (removing it while held reopens the race)fcntlskip the lock; the atomic write remains2. No CI gate linted the 73 shell scripts (#200)
scripts/holds 73 bash files and nothing in CI ranshellcheck/shfmt. That is why shellcheck findings on #172 could only arrive from review bots.Added as a step in the existing
qualityjob, not a new job: hosted runners are capped at$0(the macOS leg was already removed for that) and the single self-hosted runner already serialises every job with all open PRs queued behind it.-S erroronly: the tree has 0 error-level and 50 pre-existing warning-level findings, so it is green today and still catches real breakage; warnings are reported informationallyshellcheckis missing, attempts install then degrades to a::warning::annotation rather than blocking on runner provisioningValidation
ruff check/ruff format --check/py_compile--check/ negative--refresh-if-expiringthen→ exit 1 (SC1049/SC1073/SC1050/SC1072)scripts/test-portal-bridge.sh→ exit 0qualityScope
Two files, no Rust or build inputs, so build outcomes are unaffected.
Note on runner capacity
CI on this repo is single-runner bound, so these checks may sit queued. Neither change can be invalidated by the Rust gates (
Formatiscargo fmt,Quality Guardrailsiscargo check/clippy).CodeAnt-AI Description
Prevent token refresh races and catch shell errors in CI
What Changed
Impact
✅ Fewer failed token refreshes✅ Fewer unnecessary token rotations✅ Shell errors caught before merge💡 Usage Guide
Checking Your Pull Request
Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.
Talking to CodeAnt AI
Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:
This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.
Example
Preserve Org Learnings with CodeAnt
You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:
This helps CodeAnt AI learn and adapt to your team's coding style and standards.
Example
Retrigger review
Ask CodeAnt AI to review the PR again, by typing:
Check Your Repository Health
To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.