Skip to content

fix(portal): lock token refresh + lint shell scripts in CI - #201

Merged
KooshaPari merged 3 commits into
masterfrom
fix/portal-token-refresh-locking
Oct 27, 2026
Merged

KooshaPari merged 3 commits into
masterfrom
fix/portal-token-refresh-locking

Conversation

@KooshaPari

@KooshaPari KooshaPari commented Oct 27, 2026 •

Copy link
Copy Markdown
Owner

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.py 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 refreshes on launch, so two callers 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 to mint a new one

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:

Helper Result
before (no lock) 2 succeeded, 2 failed invalid_grant
after, --refresh-if-expiring 600 1 rotation, 3 no-ops, 0 failures
after, unconditional (worst case) 4 sequential rotations, 0 failures

Change

  • advisory exclusive flock on <token-path>.lock around the whole read/exchange/write cycle
  • re-read the cache inside the lock, since another process may have rotated it between the first read and acquisition
  • --refresh-if-expiring SECONDS so scheduled callers are a no-op unless the token is genuinely near expiry (every refresh consumes a rotation)
  • lock file created 0600, never unlinked (removing it while held reopens the race)
  • platforms without fcntl skip the lock; the atomic write remains

2. No CI gate linted the 73 shell scripts (#200)

scripts/ holds 73 bash files and nothing in CI ran shellcheck/shfmt. That is why shellcheck findings on #172 could only arrive from review bots.

Added as a step in the existing quality job, 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.

  • lints only scripts changed in the change set (a full scan is ~5s/file, minutes on that runner)
  • gates at -S error only: 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 informationally
  • if shellcheck is missing, attempts install then degrades to a ::warning:: annotation rather than blocking on runner provisioning

Validation

Check Result
4-way race, mock rotation server before: 2 failures; after: 0 failures (both modes)
raced cache integrity mode 0600, lock 0600, no temp residue, still authenticates
ruff check / ruff format --check / py_compile clean
--check / negative --refresh-if-expiring exit 0 / exit 2 as documented
shellcheck gate has teeth probe missing then → exit 1 (SC1049/SC1073/SC1050/SC1072)
shellcheck gate on clean files merged scripts/test-portal-bridge.sh → exit 0
workflow YAML parses; step present in quality

Scope

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 (Format is cargo fmt, Quality Guardrails is cargo check/clippy).


CodeAnt-AI Description

Prevent token refresh races and catch shell errors in CI

What Changed

  • Concurrent refreshes now run one at a time and re-check the latest token cache, avoiding failures from using a refresh token that another process has already consumed.
  • Scheduled refreshes can skip tokens that are not close to expiring, avoiding unnecessary token rotations.
  • CI checks changed shell scripts for errors; warnings are informational, and linting is skipped with a warning if ShellCheck is unavailable.

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:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

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:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

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.

… 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
Copilot AI balanced review requested due to automatic review settings October 27, 2026 05:51
@codeant-ai

codeant-ai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

CodeAnt  CodeAnt Review Status

✅  Review completed

Status Commit Started (UTC) Finished (UTC)
✅  Incremental review completed 1ccdc46 Oct 27, 2026 · 08:15 08:16
✅  Reviewed your PR e3c8cf9 Oct 27, 2026 · 05:51 05:59

@codeant-ai

codeant-ai Bot commented Oct 27, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Caution

Review failed

The pull request is closed.

📝 Summary

Summary

  • Serialize portal-token refreshes with an advisory exclusive lock on <token-path>.lock. Re-read the cache after acquiring the lock, and check --refresh-if-expiring SECONDS again before exchanging the token. Locking is skipped when fcntl is unavailable.
  • Add --refresh-if-expiring SECONDS to avoid rotating a token that remains valid beyond the specified threshold. Reject negative thresholds.
  • Add changed-shell-script linting to the existing quality job. The step uses ShellCheck error severity as the gate and reports warning findings without failing. If ShellCheck is unavailable, it attempts installation and then warns and skips if installation does not make it available.

Validation

The supplied PR context reports successful four-caller mock tests for conditional and unconditional refresh, and reports that the malformed ShellCheck probe fails while clean scripts pass. Test output was not independently available in the inspected source.

The PR adds conditional, serialized portal-token refresh and adds ShellCheck to the CI quality job for changed shell scripts.

Changes: Portal token refresh

Layer / File(s) Summary
Refresh options and locking
scripts/refresh-portal-token.py
The script adds --refresh-if-expiring, expiry calculation, and advisory-lock helpers. Negative thresholds return exit code 2.
Locked cache refresh
scripts/refresh-portal-token.py
The script re-reads the cache under lock, checks expiry again, requests refreshed tokens when needed, persists successful responses, and releases the lock on exit.

CI shell-script linting

Layer / File(s) Summary
Changed shell-script linting
.github/workflows/ci.yml
The quality job installs ShellCheck if needed, then lints existing changed .sh files. Errors can fail the step; warnings are reported without failing it. The step skips linting when ShellCheck or a usable base is unavailable, or when no matching files changed.

Priority: Not assessed

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant RefreshScript
  participant TokenCache
  participant LockFile
  participant PortalAuthServer
  RefreshScript->>TokenCache: Read cached expiry and refresh token
  RefreshScript->>LockFile: Acquire exclusive lock
  RefreshScript->>TokenCache: Re-read cache while locked
  RefreshScript->>PortalAuthServer: Submit refresh token
  PortalAuthServer-->>RefreshScript: Return refreshed token response
  RefreshScript->>TokenCache: Persist updated token cache
  RefreshScript->>LockFile: Release lock
Loading

Suggested reviewers: 1jehuang

Merge Risk: Moderate · up to 1ccdc

The new shell-script lint step will silently lint nothing in CI because the comparison commit is not fetched, so it gives no protection until the checkout depth is fixed. The token refresh lock works between helper callers on Linux and macOS. It does not coordinate with mcp-remote's own refresh, and it does nothing on Windows, so concurrent refreshes there can still fail with invalid_grant.

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
✨ Simplify code
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Oct 27, 2026
"""
if fcntl is None:
return None
fd = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

@kilo-code-bot

kilo-code-bot Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: 1 Issue Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 1
SUGGESTION 0
Issue Details (click to expand)

WARNING

File Line Issue
scripts/refresh-portal-token.py 193 Lock file mode only applied on creation; pre-existing lock file may retain broader permissions
Files Reviewed (2 files)
  • scripts/refresh-portal-token.py - 1 issue
  • .github/workflows/ci.yml - 0 issues

Fix these issues in Kilo Cloud


Reviewed by free · Input: 153.7K · Output: 2.5K · Cached: 206.3K

@codeant-ai

codeant-ai Bot commented Oct 27, 2026

Copy link
Copy Markdown

CodeAnt  CodeAnt Nitpicks

3 code suggestions

1. The default shallow checkout fetches only the PR merge commit, so HEAD~1 is unavailable and this step silently exits successfully without linting changed scripts.

Api mismatch · .github/workflows/ci.yml:81


2. The *.sh pathspec excludes valid shell scripts such as scripts/jcode-dev and scripts/rustc-parallel-frontend, so changes to them bypass ShellCheck.

Incomplete implementation · .github/workflows/ci.yml:84


3. A fresh cache written by mcp-remote has expires_in but no expires_at, so left is None and the first scheduled call refreshes even a new token.

Incorrect condition logic · scripts/refresh-portal-token.py:258-259

@codeant-ai

codeant-ai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

CodeAnt  CodeAnt PR Risk

🟢  Low Risk

  • The PR appears safe to merge; no actionable issues were identified in the review.

Assessed commit: 1ccdc46b964e

@KooshaPari
KooshaPari merged commit 9d09966 into master Oct 27, 2026
7 of 16 checks passed
@KooshaPari
KooshaPari deleted the fix/portal-token-refresh-locking branch October 27, 2026 08:21
KooshaPari added a commit that referenced this pull request Nov 11, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

2 participants