Skip to content

feat(#7500): rotate GitLab role credentials with recovery - #7514

Merged
ggallen merged 2 commits into
mainfrom
agent/7500-gitlab-role-credential-rotation
Sep 21, 2026
Merged

ggallen merged 2 commits into
mainfrom
agent/7500-gitlab-role-credential-rotation

Conversation

@fullsend-ai-coder

Copy link
Copy Markdown
Contributor

Summary

Implement role-aware rotation, recovery, and rollback for GitLab Poller, Analyst, Coder, and custom own-credential roles so expiring or revoked project access tokens can be replaced without stranding a role or silently falling back to the shared bot PAT.

Related Issue

#7500 (sub-issue of #7496; depends on the merged contract in #7497 / #7506 and provisioning in #7498 / #7508).

Changes

  • Add gitlabroles.DiagnoseLifecycle to classify each registered role as ok, expiring, expired, revoked, unverified, overlapping, or unconfigured from project-access-token inventory (names, IDs, and dates only).
  • Add repos.RotateGitLabRoleCredentials: create-then-distribute a replacement PAT, keep the previous PAT valid for in-flight jobs for 24 hours, serialize concurrent attempts, and roll back a failed distribution by revoking only the unused replacement.
  • Wire rotation into repos install (auto-rotate due roles when the gate is migrating/enforced) with --rotate-gitlab-roles and --rotate-gitlab-role.
  • Store non-secret rotation state in protected unmasked FULLSEND_GITLAB_ROLE_ROTATION. Uninstall removes it. The shared FULLSEND_FORGE_TOKEN is never rotated or selected as a fallback.
  • Surface expiry/revocation on repos status and document the lifecycle in the GitLab role-credential contract and CLI/operator guides.

Testing

  • go test -race ./internal/gitlabroles/ ./internal/repos/ ./internal/forge/gitlab/ covering normal rotation per built-in role, custom-role rotation, reuse-follows-target, concurrent serialized/idempotent rotation, failed create, failed distribution/rollback, in-flight overlap, grace cleanup, recovery of a partial distribution, disabled-mode skip, dry-run, enrolled replacement, and expiry/revocation status drift.
  • Targeted CLI tests for flag parsing, skip-on-disabled, and rotate output (no secret leakage).
  • go vet on changed packages. Direct execution of pre-commit equivalents after pre-commit run failed to fetch hook repos (HTTP 403): gofmt, docs-link scope, lychee, scan-secrets.

Checklist

  • PR title follows Conventional Commits (feat, issue-number scope)
  • Commits are not DCO-signed (autonomous agent exemption)
  • I can explain all changes in this PR

Closes #7500

Post-script verification

  • Branch is not main/master (agent/7500-gitlab-role-credential-rotation)
  • Secret scan passed (gitleaks — 465f437ad067eab2b58991080a2b7c4342ac5d91..HEAD)
  • PR body secret scan passed (gitleaks — no-git)

@fullsend-ai-coder
fullsend-ai-coder Bot requested a review from a team September 21, 2026 01:54
@fullsend-ai-coder fullsend-ai-coder Bot added the ready-for-review Triggers review agent dispatch label Sep 21, 2026
@fullsend-ai-review

fullsend-ai-review Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 1:56 AM UTC · Completed 2:16 AM UTC

Commit: 7a918a5 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5 · Effort: high · Cost: $8.30

@fullsend-ai-review fullsend-ai-review Bot added the risk/moderate PR risk: moderate label Sep 21, 2026
@fullsend-ai-review

fullsend-ai-review Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Risk Assessment: moderate (2/5)

Details

Re-anchored to the prior score of 2 (moderate): Tier 1 metadata is unchanged in kind (same 20 files, 0 protected/security-sensitive paths, no CI/dependency changes, established bot author, test ratio still in the 0.10-0.29 band) and lines_changed (3627) stays in the same >=2000 bucket as the prior round; Tier 2 shows the same concentrated 30d churn and low code age on shared docs/CLI/forge files, with the rotation/test files still new/untracked in base history; this rounds delta is a small, targeted bug fix (~13 production lines, ~90 test lines) to an already-scored file, giving no specific reason to depart from the anchored composite score of 2.

Previous run

Risk Assessment: moderate (2/5)

Details

Anchored to the prior score of 2 (moderate): Tier 1 metadata is unchanged in kind (same 20 files, 0 protected/security-sensitive paths, no CI/dependency changes, established bot author, test ratio still in the 0.10-0.29 band), and line growth from ~3489 to 3533 stays within the same >=2000 bucket. Tier 2 shows the same pattern as before - concentrated 30d churn and fix/revert history on shared docs/CLI/forge files this PR only lightly touches, offset by very low code age and author contention; the four new dedicated rotation/lifecycle files remain untracked and excluded from scoring. Tier 3 remains unchanged with issue scope essentially matched, no unresolved discussion, a security label but no breaking-change/needs-discussion flags, and rotation gated behind new opt-in CLI flags. No Tier 2/3 signal provides a specific reason to depart from the anchored composite score of 2.

Previous run (2)

Risk Assessment: moderate (2/5)

Details

Re-anchored to the prior score of 2 (moderate): Tier 1 metadata is unchanged in kind (same 20 files, 0 protected/security-sensitive paths, no CI/dependency changes, established bot author with 5+ prior review rounds), and the growth from 3187 to 3489 lines stays within the same large/>=2000 bucket; Tier 2 shows the same pattern as before - concentrated 30d churn and fix/revert history on shared docs/CLI/forge files this PR only lightly touches, with the four new dedicated rotation/lifecycle files still untracked and excluded from scoring; Tier 3 remains unchanged with issue scope matched, no unresolved discussion, and only a moderate risk label. No Tier 2/3 signal provides a specific reason to depart from the anchored composite score of 2.

Previous run (3)

Risk Assessment: moderate (2/5)

Details

Re-anchored to the prior score of 2 (moderate): Tier 1 metadata is unchanged in kind (same 20 files, 0 protected/security-sensitive paths, no CI/dependency changes, established bot author) and the growth from 2921 to 3187 lines stays within the same large bucket; Tier 2 confirms the same pattern as the prior run: concentrated churn/fix history on shared docs/CLI/forge files this PR only lightly touches, with the four new dedicated rotation/lifecycle files still untracked and excluded from scoring; Tier 3 remains unchanged with full acceptance-criteria coverage, no unresolved discussion, and a moderate risk label. The single intervening commit touched only files already covered by the prior review's risk profile, so no Tier 2/3 delta justifies departing from the anchored score of 2.

Previous run (4)

Risk Assessment: moderate (2/5)

Details

Re-review anchored to the prior score of 2 (moderate): Tier 1 metadata is unchanged in kind (same 20 files, 0 protected/security-sensitive paths, no CI/dependency changes, established bot author) and line growth from 2673 to 2921 stays within the same >=2000 large bucket (Tier 1 avg ~1.75); Tier 2 independently confirms concentrated churn/fix/coupling history on the shared docs/CLI/forge files this PR only lightly touches (avg ~3.0) while the four new dedicated rotation/lifecycle files are untracked and excluded from history scoring; Tier 3 shows full acceptance-criteria coverage, no unresolved discussion, and a built-in rollback design with only a moderate risk label (avg ~1.8). The weighted composite (0.50x1.75 + 0.30x3.0 + 0.20x1.8 = 2.14) rounds to 2, matching the prior anchor with no Tier 2/3 delta large enough to justify a different score.

Previous run (5)

Risk Assessment: moderate (2/5)

Details

Re-review anchored to the prior score of 2 (moderate): Tier 1 metadata is unchanged in kind (same 20 files, 0 protected/security-sensitive paths, no CI/dependency changes, established bot author) and the line growth from 2673 to 2844 stays within the same >=2000 large bucket; Tier 2 still shows concentrated churn/fix history on shared docs/infra/CLI files this PR only lightly touches while the new dedicated rotation files remain untracked/new; Tier 3 still shows full acceptance-criteria coverage with an explicit rollback design and no risk-elevating labels. No specific, articulable Tier 2/3 delta justifies moving off the prior anchor score.

Previous run (6)

Risk Assessment: moderate (2/5)

Details

Re-review anchored to the prior score of 2 (moderate): Tier 1 metadata is unchanged in kind (same 20 files, 0 protected paths, 0 security-sensitive/dependency matches, no CI changes, established bot author) and the diff-size growth from 2408 to 2673 lines does not cross a scoring bucket boundary (both fall in the >=2000 large band). Tier 2 continues to show elevated churn/fix-history concentration on shared files this PR only lightly touches, while the newly added dedicated rotation files have no git history and are excluded from churn analysis. Tier 3 signals show the PR fully addresses #7500's five acceptance criteria with an explicit rollback/grace-period design. No specific, articulable Tier 2/3 delta justifies moving off the prior anchor score.

Previous run (7)

Risk Assessment: moderate (2/5)

Details

Tier 1 metadata signals are unchanged in kind from the prior review (still no protected paths, no security-sensitive or dependency-file matches, no CI changes, non-first-time bot author, large diff of 2408 lines across the same 20 files), and Tier 2 shows the same pattern as before -- elevated churn/fix history only on shared files this PR barely touches while the new dedicated credential-rotation files have no history -- so the score is anchored to the prior moderate score of 2. This review still found unresolved high-severity credential-stranding gaps in the rotation recovery path, but risk scoring reflects blast radius and change characteristics, not code-review outcome.

Previous run (8)

Risk Assessment: moderate (2/5)

Details

Despite touching security-sensitive GitLab credential-rotation code with a large diff (2219 lines across 20 files), the PR has no protected-path or CI/dependency changes, a non-first-time bot author, reasonable test coverage, and moderate git-history churn/fix signals on shared files it barely touches plus a well-scoped, criteria-matched linked issue with built-in rollback support, yielding a moderate overall score of 2.

@fullsend-ai-review

fullsend-ai-review Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Review

This round re-verified the prior medium logic-error finding in currentListed (internal/repos/gitlab_roles_rotate.go:897) against the only two files that changed since the last review. The fix is correct and complete: equal-expiry ties now resolve to the higher token ID, an unparseable expires_at can no longer displace a dated winner, and three new regression tests cover the tie-break, the unparseable-expiry ordering, and the end-to-end RotateGitLabRoleCredentials scenario. Correctness and security independently confirmed the fix and found no remaining or new issues in the delta. Intent-coherence confirmed the fix stays within issue #7500's authorized scope. Style-conventions (trivial scope) found nothing.

Findings

Low

  • [sub-agent-failure] N/A — The challenger sub-agent returned an empty adjudicated-findings set for a non-empty input (two non-actionable, info-level intent-coherence notes confirming scope/architecture fit). Per policy, an empty result from a non-empty input is treated as a challenger failure rather than a legitimate full clearance, so this review falls back to the pre-challenger finding set. The affected findings were both info-level and below this review's severity threshold regardless, so this does not change the verdict.
Previous run

Review

This round re-verified the prior high-severity permission-expansion finding in the rotation-state initial-distribution/backfill path (recordInitialDistribution/backfillInitialDistributionProof) and the prior medium logic-error finding about dry-run reporting would rotate for already-proven roles — both are fixed in the current code (create-if-absent write path with a fresh re-read; dry-run now reaches the same skip decision as live install). Security, docs-currency, style-conventions, and cross-repo-contracts came back clean or with only informational notes. Correctness found one new medium-severity bug in the same rotation file.

Findings

Medium

  • [logic-error] internal/repos/gitlab_roles_rotate.go:897 — currentListed is what distributionProven compares IncomingID against, but it is not a stable "current PAT" selector. On equal YYYY-MM-DD expiries it keeps whichever matching token appears first in GitLab's list (exp.After is false, so a later same-day replacement never wins). A same-day force-rotate (or recovery mint) therefore leaves two active PATs with identical expiry; if the older token is listed first, IncomingID == current.ID is false, recentlyDistributed expires after five minutes, and the next non-Force repos install treats a healthy overlapping replacement as unproven and mints again — an unexpected bot-identity change. The unparseable-expiry branch is also wrong relative to currentToken in lifecycle.go: a dated winner can be overwritten by a higher-ID token whose ExpiresAt failed to parse (if best.ID == 0 || tok.ID > best.ID, which ignores whether a valid dated winner was already found), so an empty/unparseable expires_at can steal "current" from the real latest-expiry PAT. No test in gitlab_roles_rotate_test.go covers currentListed.
    Remediation: Make currentListed match currentToken: never replace a parseable-expiry winner with an unparseable one, and on equal expiry (or when neither date parses) tie-break on higher token ID. Add a regression test with two active same-named PATs, same ExpiresAt, older ID first in the list, rotation-state incoming_id set to the newer ID, and assert the next non-Force rotate skips rather than minting.

Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run (2)

Review

The four prior docs-currency findings and the prior correctness finding (unproven-orphan proof gap on the already-present-secret provisioning path) are resolved and verified against the current code. This round's re-review of the security and intent-coherence dimensions (re-qualified because internal/repos/gitlab_roles_rotate.go and internal/repos/gitlab_roles.go changed since the prior review) surfaced one new high-severity finding and one new medium-severity finding, both in the rotation-state merge/backfill path.

Findings

High

  • [permission-expansion] internal/repos/gitlab_roles_rotate.go:768 — recordInitialDistribution always overwrites the role's FULLSEND_GITLAB_ROLE_ROTATION entry via mergeRoleState with holder "", which skips the rotation-lock check (if holder != "" && otherHoldsRotationLock(...) at line 746) and unconditionally replaces phase, incoming_id, outgoing_ids, holder, and lock_until with a fresh idle proof. backfillInitialDistributionProof only skips writing when an entry already exists on its first loadRotationState call (line 811); it then calls ListProjectAccessTokens (a wide window) before calling recordInitialDistribution, whose merge re-read still writes unconditionally with no create-if-absent check and no lock check (holder "" disables otherHoldsRotationLock, lines 649-651). A concurrent RotateGitLabRoleCredentials run that claims the lock, mints a replacement, and records outgoing_ids inside that window is clobbered: the previous PAT(s) are dropped from grace-revocation tracking and remain valid Developer/api credentials until their natural expiry (up to one year). The same empty-holder write path is used after a fresh mint in provisionOwnRoles. This is the same class of state-clobber the PR already fixed for lock-claim writes (claimRoleRotationLock now merges only Holder/LockUntil onto a freshly re-read entry), but the initial-distribution/backfill write path was not given the same treatment. TestProvisionGitLabRoleCredentials_BackfillSkipsExistingRotationState only covers the no-concurrency case.
    Remediation: Make initial-distribution proof create-if-absent on the same re-read used to write: after loadRotationState inside the write path, if the role already has any entry (or a still-valid lock holder), skip the write and do not pass holder "". Do not overwrite phase/incoming_id/outgoing_ids/lock fields on that path. Add a test that injects an in-progress overlapping/distributing entry (with outgoing_ids) between backfill's first load and the merge write, and assert those fields survive.

Medium

  • [logic-error] internal/repos/gitlab_roles_rotate.go:388 — repos install --dry-run still reports would rotate for healthy own-credential roles that a live install will not replace. Live install runs provision then rotate (internal/cli/repos.go): provision backfills rotation-state proof in provisionOwnRoles (internal/repos/gitlab_roles.go:234, guarded by if !cfg.DryRun), after which live rotate skips not-due proven tokens (distributionProven check in rotateOneRole, lines 347-365). Dry-run skips that backfill entirely, so with an empty FULLSEND_GITLAB_ROLE_ROTATION (pre-Implement rotation, recovery, and rollback for GitLab role credentials #7500 repos, or any repo whose proof write has not yet landed), DiagnoseLifecycle reports ok (it is inventory-only) but distributionProven is still false, and the dry-run branch at lines 388-391 appends the role to Rotated anyway. Operators previewing an upgraded install therefore see a mass identity change that the real run will not perform.
    Remediation: Make dry-run use the same skip decision as live install would reach after backfill: if DryRun && !Force && !RoleDueForRotation && !needsRecovery and a matching active PAT exists (or Tokens is nil, matching the free-tier idle-proof case), skip with a diagnostic noting that proof would be backfilled, rather than appending to Rotated. Keep reporting would-rotate in dry-run only for roles that would actually rotate on a live run (due/recovery/Force).

Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR

Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run (3)

Review

Three of the four medium findings from the prior review are resolved and verified against the current code: the lock-claim overwrite race (claimRoleRotationLock now merges only Holder/LockUntil onto a freshly re-read entry), the fail-open mergeRoleState/loadRotationState write-on-read-error path (now returns the error without writing, backed by TestMergeRoleState_FailsClosedOnReadError), and the administrator-provided-rotation permission-expansion gap (now emits an explicit manual-revocation diagnostic instead of implying automatic grace cleanup it can't perform). The fourth prior finding (rotateProvided setting IncomingID=0 so provided credentials were treated as unproven orphans) is also fixed for the provided-enrollment path via recordInitialDistribution(..., 0, "", now), but the same proof-recording gap still exists for the already-present-secret skip path in initial provisioning, described below.

Findings

Medium

  • [logic-error] internal/repos/gitlab_roles_rotate.go:357 — Not-due own-credential roles are skipped only when distributionProven is true. provisionOwnRoles records that proof only on first-time create/enroll; when the secret is already present (the present[secret] skip in internal/repos/gitlab_roles.go, the pre-Implement rotation, recovery, and rollback for GitLab role credentials #7500 Provision and migrate built-in and custom GitLab role credentials #7498 provisioning path), no rotation-state proof is backfilled for that role. Pre-existing repos therefore look identical to crash orphans: the first post-upgrade repos install/converge against an already-provisioned migrating/enforced repo runs maybeRotateGitLabRoles and mints a replacement for every healthy Poller/Analyst/Coder/custom own PAT even though DiagnoseLifecycle reports ok. This contradicts docs/contributing/gitlab-role-credentials.md and docs/cli/repos.md, which state install rotates only when lifecycle is expiring/expired/revoked/unverified. GitLab assigns a new bot user per PAT, so this is a mass identity change on first upgraded install, not a no-op converge. TestRotateGitLabRoleCredentials_CustomOwnAndReuse already has to seed idle proof for healthy tokens to avoid triggering this path.
    Remediation: When provisionOwnRoles skips an already-present secret, backfill recordInitialDistribution from the live PAT (or idle/IncomingID=0/DistributedAt for provided) if that role has no rotation-state entry yet. Keep reminting unproven tokens only for genuine crash orphans (alreadyFresh without proof) or roles that are otherwise due (RoleDueForRotation/needsRecovery). If an empty-state remint on first upgraded install is intentional, document that explicitly instead of claiming install rotates only when lifecycle is due.

Low

  • [docs-accuracy] docs/contributing/gitlab-role-credentials.md:432 — Under "Identity continuity": "Rotation state records the old and new token IDs (never secret values) so repos status can show the chain." Neither repos status nor RepoStatus reads FULLSEND_GITLAB_ROLE_ROTATION or formats a token-ID chain; rotation state is used internally by RotateGitLabRoleCredentials for serialization, crash recovery, and outgoing-ID grace tracking, not for status display. RoleReport.TokenIDs is populated but never surfaced in status output.
    Remediation: Update the sentence to describe the actual use of rotation-state token IDs (serialization, recovery, grace-period revocation tracking during repos install), and remove the claim that repos status displays a token chain.

  • [docs-accuracy] docs/contributing/gitlab-role-credentials.md:437 — Under "Diagnostics": "Lines carry secret names, dates, and token IDs only." lifecycleMessages in internal/gitlabroles/lifecycle.go formats role names, secret names, and expiration dates (e.g. %s: expiring (%s) expires %s) and never interpolates a token ID into any formatted line.
    Remediation: Update the sentence to state that diagnostic lines carry role names, secret names, and dates only, matching lifecycleMessages.

  • [docs-staleness] docs/contributing/gitlab-role-credentials.md:458 — The "Credential-routing security checklist" intro still refers to "the remaining rollout stages (Implement rotation, recovery, and rollback for GitLab role credentials #7500, Verify extensible GitLab role migration and retire shared-token fallback #7501)", but the roadmap table earlier in the same document (line 449) now marks Implement rotation, recovery, and rollback for GitLab role credentials #7500 as Implemented by this PR.
    Remediation: Update the sentence to reference only the actual remaining rollout stage (Verify extensible GitLab role migration and retire shared-token fallback #7501), or otherwise reflect that Implement rotation, recovery, and rollback for GitLab role credentials #7500 is implemented.

  • [docs-currency] docs/cli/repos.md:215 — States that table/JSON output include per-role lifecycle diagnostics for ok, expiring, expired, revoked, unverified, or overlapping. lifecycleMessages skips both ok and unconfigured states (no diagnostic line is emitted for either), so ok never actually appears in diagnostic output and unconfigured is omitted from the doc's list.
    Remediation: Clarify that diagnostic lines are emitted only for roles needing attention (expiring, expired, revoked, unverified, overlapping), and mention unconfigured if it is meant to be included in this list.


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run (4)

Review

Findings

Medium

  • [race-condition] internal/repos/gitlab_roles_rotate.go:262 — The lock-claim write still assigns the entire pre-claim rs over the re-read role entry. mergeRoleState only aborts on otherHoldsRotationLock, which is false once the winner has released the lock (empty holder). A process that loaded an unlocked snapshot, stalled through a full mint/distribute/defer-unlock, then claimed will persist idle state with IncomingID=0/OutgoingIDs=nil, steal the free lock, fail distributionProven, and mint another PAT. TestRotateGitLabRoleCredentials_StaleClaimRejectedAfterConcurrentWinner only injects a still-held distributing winner; lock-released completed state is untested. The mergeRoleState comment still says an empty holder "is only correct for the initial lock claim," which contradicts the claim site (non-empty holder) and recordInitialDistribution (empty holder).
    Remediation: On lock claim, copy only Holder and LockUntil onto the freshly re-read role entry (preserve phase, incoming_id, outgoing_ids, distributed_at). After the claim, set local rs from that merged entry. Rewrite the mergeRoleState comment: empty holder skips the check for recordInitialDistribution, not for claiming. Extend the stale-claim test so the injected winner is overlapping/idle with lock released (empty holder) and assert incoming_id/outgoing_ids survive and only one replacement is minted.

  • [logic-error] internal/repos/gitlab_roles_rotate.go:538 — rotateProvided sets IncomingID=0 while writing DistributedAt, so distributionProven and recentlyDistributed (both require IncomingID != 0) never fire. The next unflagged repos install without --gitlab-role-token therefore treats a healthy administrator-provided credential as an unproven orphan and, when a token client exists, mints an API PAT over it even if DiagnoseLifecycle is ok/not due. provisionOwnRoles also records no proof after provided enroll, so the documented five-minute idempotency window cannot apply to provided enrollment. This contradicts docs/contributing/gitlab-role-credentials.md, which says install rotates only when DiagnoseLifecycle reports expiring/expired/revoked/unverified.
    Remediation: Record a skip-able proof for administrator-provided enrollment that does not require a GitLab token ID (e.g., treat phase=idle with DistributedAt set and IncomingID=0 as proven and not due, without classifying phase=failed the same way). Mirror that proof from provisionOwnRoles after a successful provided enroll. Align the "Rotation and recovery" contract with the unproven-orphan remint policy, or stop reminting lifecycle-ok tokens that are merely missing IncomingID.

  • [fail-open] internal/repos/gitlab_roles_rotate.go:676 — mergeRoleState fails open when loadRotationState errors: it keeps the caller-supplied *state and writes it anyway. recordInitialDistribution starts with a zero-value rotationStateFile and an empty holder, so a GetRepoVariable flake during provision writes a single-role document that replaces the whole variable and drops every other role's lock, incoming_id, and outgoing_ids. Lost outgoing_ids leave previously scheduled grace revocations untracked. (Not observed in current diff: a chain from this to revocation of a live CI secret via CreateRepoSecret — that would additionally require a lock-TTL lapse or a second concurrent rotator, which is not demonstrated.)
    Remediation: If loadRotationState fails, return that error and do not write. Never treat an uninitialized *state as a safe fallback. recordInitialDistribution should fail closed on read error (the provision caller already treats this as non-fatal).

  • [permission-expansion] internal/repos/gitlab_roles_rotate.go:540 — Administrator-provided rotation (rotateProvided) stores the new secret then sets phase=idle, incoming_id=0, outgoing_ids=nil. Previous same-named project access tokens are never scheduled for grace revocation (the replacement's GitLab ID cannot be resolved from the provided value alone, so recording all matches would risk revoking the new PAT). The diagnostic still says previous credentials "remain during the grace period," and the user-facing rotation docs claim a later install revokes the outgoing PAT after 24h. A leak-response that re-enrolls via --gitlab-role-token therefore leaves the leaked PAT valid with the same Developer+api rights, with no operator warning to revoke it manually.
    Remediation: Do not imply grace cleanup when outgoing_ids cannot be filled. Require a replacement token ID (or snapshot IDs before enroll and revoke IDs that are not the replacement once it can be identified), and fail or warn if other active same-named PATs remain. At minimum, surface an operator action to revoke previous PATs manually and keep those IDs out of the "grace period" language.


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run (5)

Review

Findings

Medium

  • [race-condition] internal/repos/gitlab_roles_rotate.go:256 — The lock claim still calls mergeRoleState with an empty holder, so otherHoldsRotationLock is skipped and the write overwrites whatever is currently stored for this role. The post-claim re-read only detects a concurrent winner if that overwrite landed before the re-read. A second process that loaded an unlocked document, stalled, and then claimed after this holder already minted/distributed will persist its stale pre-claim role snapshot (idle, no incoming_id/outgoing_ids) on top of the in-progress or completed state, steal the lock, and mint another PAT. otherHoldsRotationLock already returns false when the lock is free or self-owned, so passing holder is correct for the claim; the comment that the check must be skipped because this holder does not own the lock yet is wrong. TestRotateGitLabRoleCredentials_ConcurrentSerializedAndIdempotent does not catch this: both goroutines share cfg.Now (same derived holder) and roleRotateLocks serializes them in-process. TestRotateGitLabRoleCredentials_ConcurrentSiblingRoleSurvivesLockClaim only injects a sibling role, not a distinct-holder same-role claim.
    Remediation: Pass holder (not "") into the lock-claim mergeRoleState. Map errRotationLockLost to InProgress rather than a generic lock-write failure. Extend a test to inject a same-role claim after the winner has written distributing/overlapping state (distinct Holder values, no reliance on the in-process mutex) and assert incoming_id/outgoing_ids survive and only one replacement is minted.

  • [algorithm-mismatch] docs/contributing/gitlab-role-credentials.md:405 — The rotation/recovery contract states: "A crash after create but before store is recovered by revoking the orphan incoming PAT (its value is only returned at creation) and minting a fresh one." That does not match the implemented recovery path. In rotateOneRole (internal/repos/gitlab_roles_rotate.go:372-386), when rs.Phase == rotationPhaseDistributing && rs.IncomingID != 0, the code explicitly does not revoke the incoming token — the comment says never revoke it without proof distribution did not complete, keeps it in outgoing_ids, marks phase failed, and mints a replacement so grace cleanup retires the previous PAT. TestRotateGitLabRoleCredentials_RecoveryAfterPartialDistribution and its WithoutForce variant both assert assert.NotContains(t, tokens.revoked, 8, ...) for that incoming ID. The code is safer than the doc (the "orphan" may already be the live CI secret), but this is the canonical internal contract for credential rotation/recovery; a later change that follows the written algorithm could revoke a token that is already the live CI secret.
    Remediation: Update the "Rotation and recovery" section to describe the actual recovery behavior: on a crash after create where store is unproven, preserve the previously-created (possibly-live) incoming PAT in outgoing_ids, mark phase failed, mint and distribute a replacement, and revoke previous IDs only after the 24h grace. Do not claim the orphan is revoked immediately.


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run (6)

Review

Findings

High

  • [credential-stranding] internal/repos/gitlab_roles_rotate.go:320 — Prior finding is only partially fixed. alreadyFresh / the !RoleDueForRotation skip still treat a single unproven same-named PAT as success unless needsProof is set (overlapping inventory, phase overlapping, or IncomingID != 0 in distributing/failed). TestRotateGitLabRoleCredentials_OrphanBeforeFirstStateWriteIsNotTrustedAsDue seeds two live PATs, so rr.Overlapping forces proof, but the crash window remains when CreateProjectAccessToken succeeds and the process dies before the first mergeRoleState of phase=distributing: there is then exactly one active PAT (plaintext gone, CI secret never updated, phase never advanced). That is the recovery path for unverified (secret present, no prior PAT) and revoked (prior PAT inactive) roles — primary cases this PR claims to heal. On retry, currentListed picks up the orphan; same-day ExpiresAt == GitLabPATExpiresAt(now) satisfies alreadyFresh because needsProof is false. On later days RoleDueForRotation is false (LifecycleOK: secret present + one active PAT) and the second skip still fires until ~30 days before the ~1-year expiry. EnrichGitLabRoleStatus only surfaces drift for expired/revoked tokens, so repos status can still report health while the CI secret holds the orphaned credential. Provision (provisionOwnRoles) also does not write IncomingID/DistributedAt, so a healthy provisioned PAT hits the same unproven-but-fresh path.
    Remediation: Do not treat the role as alreadyFresh or not-due unless distribution is proven (IncomingID matches the live PAT and DistributedAt is set), including the single-active-PAT case. Write that proof during provision as well so a healthy provisioned PAT is not immediately re-minted. If an active same-named PAT exists without that proof, mint a replacement, distribute it, and put every other listed same-named ID into outgoing_ids. Add a regression test that seeds only the crash-created orphan (no second live PAT; prior token absent or inactive) and asserts a retry mints and distributes a replacement rather than skipping.

Medium

  • [race-condition] internal/repos/gitlab_roles_rotate.go:244 — The lock-claim write still persists the pre-claim multi-role snapshot via writeRotationState, so a sibling role's update that landed after loadRotationState and before this write is reverted. The post-claim re-read then adopts that reverted document (state = claimed). mergeRoleState only helps if the sibling writes again after the claim; the existing sibling-survival test injects after the first write and therefore does not cover this window. Two concurrent repos install/rotate processes on different roles can still silently roll back the other's incoming_id/outgoing_ids/phase. The in-process roleRotateLocks mutex is per-role and does not serialize the shared document.
    Remediation: Claim the lock with mergeRoleState (re-read, write only this role's holder/lock_until) instead of writeRotationState of the pre-claim snapshot. Before each later mergeRoleState write, abort if this holder no longer owns the lock. Extend the sibling test to inject between loadRotationState and the lock-claim write.

Low

  • [missing-test] internal/repos/gitlab_roles_rotate_test.go:732 — TestRotateGitLabRoleCredentials_RecoveryAfterPartialDistributionWithoutForce asserts the role is not Skipped and that tokens 7/8 are not revoked, but does not assert Rotated or that a replacement was minted. A regression that failed or no-op'd without appending Skipped would still pass.
    Remediation: Assert result.Rotated contains poller and that tokens.created has length 1, matching the Force recovery test.

Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run (7)

Review

Findings

High

  • [logic-error] internal/repos/gitlab_roles_rotate.go:309 — Incomplete distributing recovery is unreachable on the default auto-rotate path. alreadyFresh correctly refuses to skip when phase is distributing/failed, but the following !Force && !RoleDueForRotation(rr) short-circuit consults only the current PAT inventory, not rs.Phase. After a crash that minted a replacement and recorded phase=distributing, ListProjectAccessTokens shows two active same-named tokens; DiagnoseLifecycle classifies that as overlapping/ok, so RoleDueForRotation is false. Auto repos install (Force unset) skips and never reaches the phase==distributing recovery handler. cleanupOutgoing also requires phase==overlapping, so grace cleanup never starts either. TestRotateGitLabRoleCredentials_RecoveryAfterPartialDistribution only exercises this with Force:true, which bypasses the due check.
    Remediation: Do not allow the !RoleDueForRotation skip when rs.Phase is distributing or failed (and IncomingID is set). Add a non-Force test with phase=distributing, an incoming token with a long-lived expiry, and an older outgoing PAT, asserting recovery rather than Skipped.

  • [credential-stranding] internal/repos/gitlab_roles_rotate.go:299 — See also: [logic-error] finding at line 309 (same root cause: the skip/due decision relies solely on the listed PAT inventory, not on rotation-state proof of a completed distribution), flagged separately because this covers a distinct, earlier crash window. A crash after CreateProjectAccessToken succeeds but before the following writeRotationState call leaves an active same-named PAT whose plaintext is gone, while phase was never advanced to distributing at all — so the existing recovery block can't even trigger. On retry, the orphan is picked up by currentListed; same-day it satisfies alreadyFresh, and on later days the general !RoleDueForRotation skip still treats the orphan as evidence rotation already succeeded. repos status reports health from the token list, hiding that the CI secret may still hold an old/expiring credential.
    Remediation: Only treat the role as not-due when rotation state proves distribution (IncomingID matches the live PAT and DistributedAt is set). If active same-named PATs exist without that proof, mint a replacement, distribute it, and put every other listed same-named ID into outgoing_ids. Add a regression test for crash-after-create-before-first-state-write.

  • [credential-stranding] internal/repos/gitlab_roles_rotate.go:491 — rotateProvided (administrator-supplied replacement via --gitlab-role-token, documented for free-tier enrollment or a custom own credential) records every currently-listed active same-named project access token via activeIDsExcept(matches, 0) and sets IncomingID=0. cleanupOutgoing only ever excludes rs.IncomingID from revocation, so after the 24h grace period it revokes every recorded ID — including the just-enrolled replacement itself when that replacement is a project access token GitLab already lists under the same name (the documented free-tier workflow, since creating project access tokens via the API requires GitLab Premium/Ultimate, so an administrator would create the PAT via the UI with the matching name and pass its value here). TestRotateGitLabRoleCredentials_ProvidedReplacement seeds no pre-existing token, so this path is untested.
    Remediation: Resolve the provided token's own GitLab ID before recording outgoing_ids (e.g. GET /personal_access_tokens/self with the provided value) and exclude it while setting IncomingID to it. If the ID cannot be resolved, do not schedule any same-named active PAT for grace revocation. Add a test that seeds an existing same-named PAT, enrolls it via ProvidedTokens, advances past grace, and asserts it is not revoked.

Medium

  • [race-condition] internal/repos/gitlab_roles_rotate.go:254 — Cross-process locking is check-then-act on a multi-role JSON blob with no compare-and-swap. After writing the lock claim, the code re-reads (claimed, _, err := loadRotationState(...)) and aborts only when claimed.Roles[role].Holder != holder — it never replaces the in-memory state with claimed. Subsequent writes in the same rotation (cleanup, distributing-phase, completed-distribution) persist mutations against the snapshot loaded before the lock claim. Because FULLSEND_GITLAB_ROLE_ROTATION stores all roles in one document, a concurrent process rotating a sibling role can have its incoming_id/outgoing_ids/phase silently reverted by this process's next write. The per-role in-process mutex does not help across processes, and the realistic trigger is two concurrent repos install/repos rotate processes.
    Remediation: After a successful lock claim, set state = claimed (and refresh rs) so subsequent writes build on the latest document. Before every later write, re-load, verify this holder still owns the lock, and merge only this role's fields into the freshly loaded document. Add a test where a sibling role's state is written between this role's lock claim and its next state write, asserting the sibling survives.

Low

  • [code-organization] internal/cli/repos_gitlab.go:268 — annotateGitLabRoleLifecycle increments result.Summary.Drifted whenever EnrichGitLabRoleStatus adds a lifecycle drift entry, without checking whether the repo was already counted. repos.Status() already increments Summary.Drifted once per repo with any Drifts. A repo that had unrelated drift and then also gains a GitLab-role lifecycle drift is counted twice, inflating the aggregate count (potentially beyond Summary.Total) in table/JSON output. This is a regression introduced while fixing the previously-reported gap that GitLab-role drift wasn't reflected in Summary.Drifted at all — that gap is closed, but at the cost of double-counting already-drifted repos. Pass/fail behavior is unaffected since the repo was already counted as drifted.
    Remediation: Record wasDrifted := len(st.Drifts) > 0 before calling EnrichGitLabRoleStatus and increment Summary.Drifted only on the no-drift→drift transition. Add a test with pre-existing non-role drift plus a new lifecycle drift, asserting Drifted increases by exactly 1.

  • [naming-convention] internal/repos/gitlab_roles_rotate.go:686 — removeListedID does not remove the token from the slice; it keeps every entry and sets Active=false on the matching ID so later lifecycle analysis treats it as inactive. The name implies deletion/filtering, which doesn't match the actual behavior.
    Remediation: Rename to deactivateListedToken or markListedInactive.

  • [doc-style] internal/repos/gitlab_roles_rotate.go:817 — The EnrichGitLabRoleStatus doc comment does not describe what its boolean return value means (it reports whether any lifecycle drift entries were newly appended), which is exactly the semantic the CLI-layer double-counting finding above got wrong.
    Remediation: Document the return value, e.g. "It reports whether any lifecycle drift entries were newly added to status.Drifts."


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run (8)

Review

Findings

High

  • [logic-error] internal/repos/gitlab_roles_rotate.go:313 — Recovery of phase=distributing revokes IncomingID before a replacement is minted. The write order is: set phase=distributing+IncomingID, write state, call CreateRepoSecret, then set phase=overlapping/idle and write state again. If the process crashes (or the second writeRotationState call fails, whose error is ignored via _ = writeRotationState) after CreateRepoSecret succeeds but before the final state write, the CI secret now holds IncomingID's token while the state still says phase=distributing. On the next run, the recovery branch unconditionally revokes rs.IncomingID as an 'orphan' — but that token is now the live, in-use CI secret. Retry may mint a replacement, but this still removes the last known-good distributed path (and strands the role if the subsequent mint/store fails). TestRotateGitLabRoleCredentials_RecoveryAfterPartialDistribution only covers crash-before-store. See also: [credential-stranding] finding at this location (security dimension) — same underlying defect, flagged separately for its security-remediation audience.
    Remediation: Do not revoke IncomingID on recovery until it is confirmed to not be the currently-distributed secret. Track distribution completion explicitly (e.g., only treat IncomingID as an orphan when phase=distributing AND DistributedAt is unset), or re-verify against the live CI secret value/ID before revoking. Do not ignore the error from the post-distribute writeRotationState call — retry or fail loudly. Add a test for crash-after-store (state stuck at distributing but CI secret already holds IncomingID) asserting the live token is not revoked.

  • [credential-stranding] internal/repos/gitlab_roles_rotate.go:313 — Same code path as the [logic-error] finding at this location: on recovery, phase=distributing with a nonzero IncomingID is treated as an orphaned replacement and revoked unconditionally before minting a new one. Because the state write that would advance phase to overlapping/idle happens only after CreateRepoSecret succeeds — and that second write's error is discarded (_ = writeRotationState) — a crash or failed final write after a successful distribution leaves the state pointing at a token that is now the live CI secret. The next run's recovery path revokes that live credential, directly contradicting the rollback/recovery contract's 'a failed rotation does not strand a role or remove the last known-good path' guarantee, and TestRotateGitLabRoleCredentials_RecoveryAfterPartialDistribution does not cover the crash-after-store ordering.
    Remediation: Never revoke IncomingID on recovery without first confirming it is not the currently-live CI secret (e.g. only treat it as an orphan when DistributedAt is unset, or compare against the CI variable's current value/metadata before revoking). Do not discard the error from the post-distribution writeRotationState call. Add a regression test for crash-after-store.

  • [logic-error] internal/repos/gitlab_roles_rotate.go:654 — Auto-rotation never treats unverified credentials (CI secret present but no matching project access token) as due. roleReportFrom passes only that role's matched tokens into DiagnoseLifecycle; DiagnoseLifecycle returns immediately when len(tokens)==0, the same short-circuit used for 'no inventory supplied', so Lifecycle stays empty and RoleDueForRotation is false. This also fires when the entire project inventory is empty (every PAT deleted). A role whose secret exists but has zero matching PATs is silently skipped by auto-rotation unless --rotate-gitlab-roles/--rotate-gitlab-role forces it. This contradicts the PR's stated behavior and the recovery acceptance criterion in issue Implement rotation, recovery, and rollback for GitLab role credentials #7500.
    Remediation: Distinguish nil inventory (fetch failed / not supplied) from a successfully fetched but empty token list in DiagnoseLifecycle — only apply the 'no inventory supplied' skip for the former. When a role's secret exists with zero matches, classify it LifecycleUnverified so RoleDueForRotation is true. Pass the full listed inventory into DiagnoseLifecycle (not the per-role matches filter). Add a test for auto-rotate (Force=false) of a configured role with zero matching PATs.

  • [fail-open] internal/repos/gitlab_roles_rotate.go:511 — loadRotationState is fail-open on both API errors and malformed state, not just on the legitimate first-run case. It treats err != nil from GetRepoVariable identically to !exists/empty (returning a fresh empty document with no error signal), and a JSON decode failure is handled the same way (logging a diagnostic but returning an empty document and proceeding). Because writeRotationState then persists the whole document, a transient GET failure clobbers other roles' incoming_id/outgoing_ids. otherHoldsRotationLock similarly returns false whenever LockUntil is empty or fails RFC3339 parsing. GetRepoVariable already distinguishes 404 (!exists, err=nil) from transport/API errors, so collapsing them is unnecessary. TestRotateGitLabRoleCredentials_InvalidStateAndEmptyCreate currently encodes this fail-open behavior as expected. (This also subsumes a duplicate style-dimension finding that loadRotationState suppresses GetRepoVariable errors, diverging from the package's own error-propagation convention.)
    Remediation: Distinguish the three outcomes in loadRotationState: (1) variable does not exist or is whitespace-only → legitimate empty state (first run); (2) GetRepoVariable returns err != nil → propagate the error and do not rotate that role this run; (3) JSON decode fails or LockUntil/DistributedAt fail to parse → fail the role for this run (do not silently start a fresh document, and do not overwrite the CI variable with a fresh document on next write). Update TestRotateGitLabRoleCredentials_InvalidStateAndEmptyCreate to expect a failure rather than a fresh rotation.

  • [race-condition] internal/repos/gitlab_roles_rotate.go:233 — Cross-process rotation locking is check-then-act with no compare-and-swap: a process reads the rotation-state CI variable, and if it looks unlocked, writes its own holder/lock_until via UpdateCIVariable. The only true mutual exclusion is an in-process sync.Mutex (roleRotateLocks), which does not help across two concurrent repos install/repos rotate processes (e.g. two CI runners, or a scheduled job overlapping a manual invocation). Two processes can both observe an unlocked document, both mint a Developer+api PAT, and both call CreateRepoSecret — the loser's PAT can remain valid and unaccounted for, or (combined with the loadRotationState fail-open and the revoke-first recovery path) the CI secret's live token can end up revoked. The existing concurrency test only exercises two goroutines within one process, so it does not cover this.
    Remediation: Use a lock primitive with real compare-and-swap semantics for FULLSEND_GITLAB_ROLE_ROTATION (e.g., re-read after writing the lock and abort unless the read-back document still shows this process as holder, or use an ETag/generation counter if the forge API exposes one). Keep the in-process mutex as a fast-path optimization only. Add a test that interleaves two clients' GetRepoVariable/UpdateCIVariable calls to simulate real cross-process contention.

Medium

  • [logic-error] internal/repos/gitlab_roles_rotate.go:273 — alreadyFresh skips rotation whenever the active PAT's ExpiresAt equals GitLabPATExpiresAt(now), including on --rotate-gitlab-roles/--rotate-gitlab-role force runs. Because GitLab PATs minted the same UTC day share that expiry date, this makes the documented five-minute idempotent window effectively last the rest of the day — a second force-rotate later the same day (e.g. after a suspected compromise of the just-distributed replacement) is a silent no-op.
    Remediation: Drop the same-day ExpiresAt equality short-circuit, or gate it on recentlyDistributed/phase so only retries inside IdempotentRotationWindow are skipped; Force should mint a new PAT once that window has elapsed. Add a test: rotate once, advance time past 5 minutes but within the same calendar day, Force=true, and expect a second mint.

  • [logic-error] internal/repos/gitlab_roles_rotate.go:178 — --rotate-gitlab-role=<reuse-role> does not rotate the reuse target. The loop records the reuse role in Reused and continues without adding Credential.ReuseOf to the wanted set, so the underlying own-credential target is skipped even though docs/cli/repos.md and the contract doc state 'a reuse role follows its target.'
    Remediation: When building the wanted-role set, if a requested role has credential=reuse, also add its reuse target (transitively). Add a test with Roles=[deployer] where deployer reuses coder and coder is due, asserting coder is rotated.

  • [logic-error] internal/forge/gitlab/ci.go:1109 — LiveClient.ListProjectAccessTokens issues a single unpaginated GET (confirmed by reading the function — no per_page or page-following loop, unlike other list helpers in this file). Rotation and status now treat this call as a complete token inventory to decide due-ness, outgoing IDs, and grace cleanup. GitLab's default page size (20) means a project with more tokens than that can silently truncate the inventory, causing a role to be misclassified as unverified (triggering an unnecessary mint) or causing newly recorded outgoing_ids to omit a same-named PAT. This function pre-dates the PR but the PR newly makes it load-bearing for rotation correctness and security. See also: [credential-leak] finding at this location (security dimension) — same root defect, flagged separately for its security-remediation audience.
    Remediation: Paginate GET /projects/:id/access_tokens (per_page=100, follow pages until a short page) in LiveClient.ListProjectAccessTokens, matching the pattern used by other list helpers (e.g. ListResourceGroups) in this file. Add an HTTP test with more than one page and assert every token is returned.

  • [credential-leak] internal/forge/gitlab/ci.go:1109 — Same underlying gap as the [logic-error] finding at this location: LiveClient.ListProjectAccessTokens performs a single unpaginated GET (confirmed by reading the function body — no per_page or page-following). Rotation uses this call as the inventory for outgoing-ID tracking; a truncated page can omit a previously-issued same-named PAT from outgoing_ids at mint time, so later grace cleanup never revokes it and it remains a valid, unaccounted-for Developer+api credential past its intended rotation. (Grace cleanup itself iterates rs.OutgoingIDs from state, not the live list — the leak is at recording time.)
    Remediation: Paginate ListProjectAccessTokens (per_page=100, follow pages until a short page) and fail closed (return an error) rather than silently returning a partial list if pagination cannot complete. Add a multi-page test in ci_accesstoken_test.go.

  • [credential-leak] internal/repos/gitlab_roles_rotate.go:441 — rotateProvided (administrator-supplied replacement enrollment) overwrites the CI secret and resets phase/incoming/outgoing state without recording or revoking other still-active, same-named project access tokens that were previously minted by rotation. Those Developer+api PATs remain valid until their own GitLab expiry even though jobs now use the enrolled replacement, and because outgoing_ids is cleared, later grace cleanup will never revoke them. The diagnostic acknowledges overlap is not tracked, but leftovers are still not revoked.
    Remediation: When enrolling a provided replacement, record other active PATs matching the role's token name in outgoing_ids (or revoke them after the same grace window used for minted rotation) instead of clearing the field. If the provided token itself cannot be inventoried as a project PAT, still revoke leftover minted same-name IDs discovered via ListProjectAccessTokens.

  • [scope-documentation-mismatch] internal/cli/repos_gitlab.go:533 — maybeRotateGitLabRoles sets Force: opts.rotateGitLabRoles || len(opts.rotateGitLabRoleFilter) > 0, so passing --rotate-gitlab-role= alone force-rotates that role even when it is not due (and also runs on disabled/rollback leftover secrets). docs/cli/repos.md and the contract doc describe --rotate-gitlab-role as scoping which role(s) a normal (due-respecting) run considers, and --rotate-gitlab-roles as the separate force-all flag — the two are documented as independent, but the implementation collapses them into one force condition.
    Remediation: Set Force only from opts.rotateGitLabRoles; use opts.rotateGitLabRoleFilter purely to scope cfg.Roles (as already done). If forcing on a named-role selection is actually intended, update docs/cli/repos.md and docs/contributing/gitlab-role-credentials.md to state that explicitly.

  • [code-organization] internal/cli/repos_gitlab.go:245 — annotateGitLabRoleLifecycle mutates result.Repos[i].Drifts via EnrichGitLabRoleStatus after repos.Status(...) has already computed result.Summary from per-repo Drifts. Expired/revoked role credentials therefore appear in the table DRIFT column and JSON drifts array, but Summary.Drifted (and the non-zero exit in renderStatusResult) stay unchanged. A repo whose only drift is an expired/revoked GitLab role credential can still exit 0.
    Remediation: Move lifecycle-drift enrichment into package repos (e.g. a StatusResult method that updates both per-repo status and Summary) instead of mutating StatusResult fields from the CLI layer, and recompute or increment Summary.Drifted when a repo newly gains Drifts.

  • [incomplete-doc] docs/cli/repos.md:200 — internal/cli/repos.go's runReposStatus now calls annotateGitLabRoleLifecycle, which reports per-role lifecycle states (ok/expiring/expired/revoked/unverified/overlapping) in table output and surfaces expired/revoked role credentials as configuration drift (gitlab-role:) under enforced mode. The 'repos status' → 'Output' section of docs/cli/repos.md does not mention this new lifecycle diagnostic output or role-based drift.
    Remediation: Add a note under the Output section describing that, for GitLab repositories, table output includes per-role lifecycle diagnostics and that enforced mode reports expired/revoked role credentials under DRIFT.

Low

  • [api-shape] internal/repos/gitlab_roles.go:31 — repos.ProjectAccessToken omits a Revoked bool field that both its upstream source (gitlab.ProjectAccessToken.Revoked) and its downstream consumer (gitlabroles.TokenSnapshot.Revoked) define. gitlabTokenAdapter.ListProjectAccessTokens and snapshotsFrom silently drop revocation status when converting between these representations. Harm is limited: RevokeProjectAccessToken is a DELETE and annotateRoleLifecycle already classifies !Active as LifecycleRevoked, so this does not by itself misclassify listed inactive tokens; it would only matter if GitLab returns Active=true with Revoked=true, which is not demonstrated here.
    Remediation: Add Revoked bool to repos.ProjectAccessToken, populate it in gitlabTokenAdapter.ListProjectAccessTokens (internal/cli/repos_gitlab.go), and propagate it through snapshotsFrom (internal/repos/gitlab_roles_rotate.go).

  • [api-shape] internal/repos/gitlab_roles_rotate.go:725 — EnrichGitLabRoleStatus accepts []gitlabroles.TokenSnapshot instead of package repos's own []ProjectAccessToken, forcing an exported conversion helper (TokenSnapshotsFrom) that exists solely so callers can convert immediately before calling it.
    Remediation: Change EnrichGitLabRoleStatus to accept []ProjectAccessToken and convert internally via the unexported snapshotsFrom; unexport or remove TokenSnapshotsFrom.

  • [incorrect-doc] docs/contributing/gitlab-role-credentials.md:326 — The doc states leftover secrets after rollback are expected 'until uninstall or rotation removes them', but internal/repos/gitlab_roles_rotate.go never deletes CI secrets — rotation only mints a replacement PAT and upserts (CreateRepoSecret) the existing variable. Only repos uninstall removes the variables. The following sentence already says --rotate-gitlab-roles 'refreshes' leftovers, so the 'rotation removes them' clause is the inaccurate part.
    Remediation: Clarify the passage so it reads: 'leftover secrets after rollback are expected until uninstall removes them; repos install --rotate-gitlab-roles only refreshes (does not remove) those leftover secrets.'

  • [incomplete-doc] docs/cli/repos.md:227 — The 'repos uninstall' section lists the gate/registry variables removed on uninstall but omits the newly added forge.VarGitLabRoleRotation (FULLSEND_GITLAB_ROLE_ROTATION), which internal/repos/uninstall.go now also removes.
    Remediation: Update the uninstall description to include the rotation-state variable alongside the gate and registry variables.


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR

fullsend-ai-review[bot]

This comment was marked as outdated.

fullsend-ai-review[bot]

This comment was marked as outdated.

@ggallen
ggallen force-pushed the agent/7500-gitlab-role-credential-rotation branch from 7a918a5 to 6ec003d Compare September 21, 2026 02:50
@ggallen

ggallen commented Sep 21, 2026

Copy link
Copy Markdown
Member

Implemented and pushed as 6ec003d12 after rebasing onto upstream/main and squashing the branch.

Review follow-up:

  • ListProjectAccessTokens now paginates and fails closed on page/decode errors.
  • CLI status output documents GitLab role lifecycle diagnostics and includes rotation state in uninstall documentation.
  • Rotation state errors, malformed timestamps, force semantics, reuse-target selection, empty inventories, recovery ordering, provided-token overlap, revocation propagation, and summary drift accounting were corrected.

Verification: make lint, make go-test, targeted go test -race ./internal/gitlabroles/ ./internal/repos/ ./internal/forge/gitlab/ ./internal/cli/, and 82.9% total Go statement coverage. I replied to each existing inline conversation; all are being resolved now.

@fullsend-ai-review

fullsend-ai-review Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🤖 Review · ❌ Terminated · Started 2:52 AM UTC · Ended 3:15 AM UTC

Commit: 6ec003d · View workflow run →

@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Site preview

Preview: https://f07539f8-site.fullsend-ai.workers.dev

Commit: 0f5f723dcfbc05ea328477228585d5564df444df

@codecov

codecov Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

fullsend-ai-review[bot]

This comment was marked as outdated.

@fullsend-ai-review

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 2:52 AM UTC · Completed 3:15 AM UTC

Commit: 6ec003d · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5 · Effort: high · Cost: $7.55

@fullsend-ai-coder

fullsend-ai-coder Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Finished Fix · ✅ Success · Started 3:17 AM UTC · Completed 3:42 AM UTC

Commit: 6ec003d · View workflow run →

Runtime: claude · Model: sonnet → claude-sonnet-5 · Effort: high · Cost: $5.04

fullsend-ai-coder Bot added a commit that referenced this pull request Sep 21, 2026
Fix GitLab role rotation findings from review:
- Do not trust a fresh-looking or "not due" live PAT as proof rotation
  completed when the inventory is ambiguous (multiple active same-named
  tokens, or an incomplete distributing/failed phase); require the
  rotation state to prove this process distributed the live token
  before skipping. Fixes two related crash-recovery gaps: partial
  distribution unreachable on the default auto-rotate path, and an
  orphan token minted before the first state write masquerading as a
  completed rotation.
- Stop recording every active same-named PAT as outgoing when enrolling
  an administrator-provided replacement, since its own token ID is
  unknown and grace cleanup could revoke the just-enrolled replacement
  itself.
- Persist rotation-state writes against a freshly re-read document
  (via a new mergeRoleState helper) instead of the snapshot loaded
  before the lock claim, so a concurrent process rotating a sibling
  role is not silently reverted.
- Fix double-counting of Summary.Drifted when a repo already had
  unrelated drift and also gains a GitLab-role lifecycle drift.
- Rename removeListedID to deactivateListedToken to match its actual
  behavior, and document EnrichGitLabRoleStatus's boolean return value.

Addresses #7514
@fullsend-ai-coder

Copy link
Copy Markdown
Contributor Author

🔧 Fix agent — iteration 1 (bot-triggered)

Fixed all three High findings (two related auto-rotate skip-logic gaps that let an ambiguous token inventory mask an incomplete or crashed distribution, and rotateProvided's risk of self-revoking an administrator-enrolled replacement), the Medium race condition where a lock-claim re-read was discarded instead of replacing the working state (extended to a reload-and-merge pattern at every subsequent write site), and all three Low findings (Summary.Drifted double-counting, a misleading function name, and an incomplete doc comment). Added five new regression tests, each verified to fail against the pre-fix code and pass after the fix. All existing tests in internal/repos, internal/cli, internal/gitlabroles, and internal/forge/gitlab pass (including -race for repos/gitlabroles/forge-gitlab); go vet and gofmt are clean. pre-commit itself could not run (sandbox network policy blocks fetching hook repositories), so the configured hooks relevant to the changed Go files were run directly: gofmt -w (no changes needed), go vet ./... (clean), plus manual checks for trailing whitespace, missing final newline, merge-conflict markers, and private keys (all clean) — matching the generic pre-commit-hooks and local go-fmt/go-vet hooks in .pre-commit-config.yaml for these file types.

Fixed (7):

  1. logic-error at internal/repos/gitlab_roles_rotate.go:309 — incomplete distributing recovery unreachable on the default auto-rotate path (internal/repos/gitlab_roles_rotate.go): Added a needsProof/needsRecovery gate: when multiple active same-named PATs exist (rr.Overlapping) or the state records an incomplete distributing/failed phase, a live token is only treated as proof of a completed rotation when rotation state itself shows this process's IncomingID matches the live token and DistributedAt is set. Otherwise the role proceeds to the existing phase==distributing recovery handler instead of being skipped. Added TestRotateGitLabRoleCredentials_RecoveryAfterPartialDistributionWithoutForce, which fails on the pre-fix code (asserted Skipped) and passes after the fix.
  2. credential-stranding at internal/repos/gitlab_roles_rotate.go:299 — orphan PAT from a crash before the first state write is treated as evidence rotation succeeded (internal/repos/gitlab_roles_rotate.go): Same distributionProven/needsProof gate as the sibling logic-error finding covers this crash window too: an orphan token that was never recorded in rotation state (IncomingID/DistributedAt do not match it) no longer satisfies alreadyFresh or the general not-due skip, so rotation proceeds, mints a genuine replacement, and records every other listed same-named ID (the legitimate prior token and the orphan) in outgoing_ids for later grace cleanup. Added TestRotateGitLabRoleCredentials_OrphanBeforeFirstStateWriteIsNotTrustedAsDue, which fails on the pre-fix code and passes after the fix.
  3. credential-stranding at internal/repos/gitlab_roles_rotate.go:491 — rotateProvided can schedule the just-enrolled replacement itself for grace revocation (internal/repos/gitlab_roles_rotate.go): rotateProvided's own GitLab token ID for an administrator-supplied replacement is unknown (only its secret value was supplied), so it can't be distinguished from a genuinely leftover same-named PAT. Implemented the review's documented fallback: stopped recording any same-named active PAT in outgoing_ids for this path (previously activeIDsExcept(matches, 0) recorded all of them, including the replacement itself if GitLab already listed it under this name). Did not implement the alternative (resolving the provided token's own ID via a new GET /personal_access_tokens/self-style API call) because it would require adding a new ProjectAccessTokenClient interface method, a LiveClient implementation making an HTTP request authenticated with a token other than the client's own, and a corresponding fake/test double — a materially larger, riskier change than the safe fallback the review itself offered, for a low-likelihood, already partially-accepted leftover-PAT scenario (the existing diagnostic already acknowledges provided-replacement overlap isn't tracked). Added TestRotateGitLabRoleCredentials_ProvidedReplacementDoesNotScheduleSelfForRevocation, which fails on the pre-fix code and passes after the fix.
  4. race-condition at internal/repos/gitlab_roles_rotate.go:254 — lock claim re-read (claimed) is discarded instead of replacing state, so sibling-role writes can be silently reverted (internal/repos/gitlab_roles_rotate.go): After verifying this holder still owns the lock, replaced state/rs with the freshly re-read document (state = claimed; rs = state.Roles[...]). Additionally introduced a mergeRoleState helper that re-reads the rotation-state document immediately before every later write in rotateOneRole and merges only this role's entry into it, matching the pattern the function's own lock-release defer already used. Left the very first (lock-claim) write and that pre-existing defer untouched since they were not part of the reported defect. Did not add full compare-and-swap lock re-verification (abort + rollback) at every write site, since that would require rollback semantics for in-flight token creation/distribution beyond the specific sibling-state-loss bug reported and its required regression test. Added TestRotateGitLabRoleCredentials_ConcurrentSiblingRoleSurvives, which fails on the pre-fix code (sibling role's state is lost) and passes after the fix.
  5. code-organization at internal/cli/repos_gitlab.go:268 — annotateGitLabRoleLifecycle double-counts Summary.Drifted for repos that already had unrelated drift (internal/cli/repos_gitlab.go): Recorded wasDrifted := len(st.Drifts) > 0 before calling EnrichGitLabRoleStatus, and only increment Summary.Drifted on the no-drift -> drift transition (!wasDrifted). Added TestAnnotateGitLabRoleLifecycleDoesNotDoubleCountDrifted (two subtests: already-drifted repo not double-counted, and a fresh no-drift repo still counted once), which fails the first subtest on the pre-fix code and passes both after the fix.
  6. naming-convention at internal/repos/gitlab_roles_rotate.go:686 — removeListedID does not remove anything, it deactivates (internal/repos/gitlab_roles_rotate.go): Renamed removeListedID to deactivateListedToken and added a doc comment describing the actual in-place deactivation behavior; updated its one call site in cleanupOutgoing.
  7. doc-style at internal/repos/gitlab_roles_rotate.go:817 — EnrichGitLabRoleStatus doc comment omits the meaning of its boolean return value (internal/repos/gitlab_roles_rotate.go): Extended the doc comment to state that the return value reports whether any lifecycle drift entries were newly added to status.Drifts, and clarified that a false return does not mean the repo is otherwise drift-free.

Tests: passed

Decision points
  • Scoped the 'not due' skip's state-proof requirement to only the ambiguous cases (multiple active same-named tokens, or an incomplete distributing/failed phase) rather than requiring rotation-state proof universally (alternatives: Require rotation-state proof (IncomingID match + DistributedAt set) for every 'not due' skip, regardless of whether the token inventory is ambiguous, Scope the proof requirement to only overlapping/incomplete-phase cases, trusting a single unambiguous active token's own expiry otherwise; rationale: A universal proof requirement broke pre-existing, correct behavior for roles whose current PAT was provisioned outside this rotation flow (e.g. initial manual provisioning): TestRotateGitLabRoleCredentials_CustomOwnAndReuse regressed because poller/analyst/coder's single fresh tokens have no recorded IncomingID, so a universal check force-rotated all of them unnecessarily. A single active same-named token is unambiguous on its own expiry; the actual defect only manifests when the inventory is ambiguous (overlap or an incomplete phase), so the proof requirement is scoped to exactly that case.)
  • Fixed rotateProvided's self-revocation risk via the review's documented fallback (never record any same-named PAT in outgoing_ids) instead of resolving the provided token's own GitLab ID (alternatives: Add a new API call/interface method to resolve the provided token's own ID (e.g. GET /personal_access_tokens/self) and exclude only that ID from outgoing_ids, Never schedule any same-named active PAT for grace revocation when enrolling an administrator-provided replacement; rationale: Resolving the token's own ID would require a new ProjectAccessTokenClient interface method, a LiveClient HTTP call authenticated with a token other than the client's configured credential, and a fake/test double for it — a much larger surface change than the specific reported bug (self-revocation) warrants, especially since the review itself offered the narrower fallback as an explicit acceptable remediation.)
  • Fixed the sibling-role state-clobbering race via reload-and-merge-before-write, not full per-write lock re-verification with rollback (alternatives: Re-verify lock ownership before every write and abort/roll back in-flight token creation or distribution if the lock was lost, Reload the rotation-state document immediately before every write and merge only this role's field into it, without re-verifying lock ownership at each site; rationale: The reported defect and its required regression test are specifically about a sibling role's state being silently reverted by a stale in-memory snapshot. Reload-and-merge-before-write closes that window at every write site using the same pattern the function's own lock-release defer already relied on. Adding rollback-capable lock re-verification at each of the ~7 write sites (some after already minting/distributing a live credential) would introduce new failure modes and rollback logic well beyond the scope of this specific fix.)

Next steps:

  • /fs-review — request a re-review of the changes
  • /fs-fix <your instruction> — run another fix pass with specific guidance
  • Push commits directly — review re-runs automatically on push
    Updated by fullsend fix agent

@fullsend-ai-review

fullsend-ai-review Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 3:44 AM UTC · Completed 4:05 AM UTC

Commit: 4ca5c68 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5 · Effort: high · Cost: $6.08

fullsend-ai-review[bot]

This comment was marked as outdated.

@fullsend-ai-coder

fullsend-ai-coder Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Finished Fix · ✅ Success · Started 4:07 AM UTC · Completed 4:27 AM UTC

Commit: 4ca5c68 · View workflow run →

Runtime: claude · Model: sonnet → claude-sonnet-5 · Effort: high · Cost: $3.75

fullsend-ai-coder Bot added a commit that referenced this pull request Sep 21, 2026
Fix GitLab role rotation findings from re-review:
- Require rotation-state proof (IncomingID matches the live PAT and
  DistributedAt is set) before treating any live token as already
  rotated or not due, including the single-active-PAT case. Previously
  a lone active same-named PAT was trusted without proof whenever no
  overlap or stale distributing/failed phase was present, so a crash
  right after CreateProjectAccessToken succeeded (before any
  rotation-state write landed) could leave an orphaned token that
  auto-rotation would trust indefinitely.
- Record rotation-state distribution proof during initial provisioning
  (provisionOwnRoles) too, so a healthy just-provisioned PAT is not
  immediately treated as unproven and re-minted by the next rotation
  run.
- Claim the rotation lock via mergeRoleState (re-read immediately
  before writing) instead of writeRotationState of the state snapshot
  loaded earlier in the call, closing the window where a sibling
  role's concurrent update landing between that load and the lock
  claim was silently reverted. Later mergeRoleState writes in the same
  rotation now abort if a different, still-valid holder has since
  reclaimed the lock.
- Add missing Rotated/created-count assertions to the non-Force
  partial-distribution recovery test so a regression that no-ops
  without appending Skipped would be caught.

Addresses #7514
@fullsend-ai-coder

Copy link
Copy Markdown
Contributor Author

🔧 Fix agent — iteration 2 (bot-triggered)

Addressed all three findings from the re-review: unconditional distribution proof for the alreadyFresh/not-due skip (plus provisioning now writes that proof), lock claim via mergeRoleState with an ownership check on later writes, and the missing regression assertions. All internal/repos, internal/gitlabroles, and internal/forge/gitlab tests pass with -race; go vet is clean repo-wide. pre-commit could not fetch hook repos (HTTP 403, same as the PR's prior run); ran gofmt, go vet ./..., trailing-whitespace/EOF/merge-conflict checks, and scan-secrets directly instead.

Fixed (3):

  1. [credential-stranding] gitlab_roles_rotate.go:320 — alreadyFresh/!RoleDueForRotation skip trusted a single unproven same-named PAT as evidence rotation already succeeded (internal/repos/gitlab_roles_rotate.go): Removed the needsProof gate so both the alreadyFresh and not-due skips require rotation-state proof (IncomingID matches the live PAT and DistributedAt is set) unconditionally, including the single-active-PAT case. Also wired proof-writing into provisionOwnRoles (internal/repos/gitlab_roles.go) via a new recordInitialDistribution helper, so a healthy just-provisioned PAT is not immediately treated as unproven and re-minted. Added TestRotateGitLabRoleCredentials_SingleUnprovenOrphanIsNotTrustedAsDue covering the narrow crash window (only the orphan token exists, no prior state at all) and updated TestProvisionGitLabRoleCredentials_FreshBuiltins and TestRotateGitLabRoleCredentials_CustomOwnAndReuse to reflect the new proof requirement for already-healthy roles.
  2. [race-condition] gitlab_roles_rotate.go:244 — the lock-claim write persisted the pre-claim multi-role snapshot via writeRotationState, reverting a sibling role's concurrent update landing between loadRotationState and the claim write (internal/repos/gitlab_roles_rotate.go): Lock claim now goes through mergeRoleState (re-reads immediately before writing) instead of writeRotationState of the earlier snapshot. mergeRoleState also gained a holder/now-based ownership check so every later write in the same rotation aborts (errRotationLockLost) if a different, still-valid holder has since reclaimed the lock; all existing call sites were updated to pass holder and now. Added TestRotateGitLabRoleCredentials_ConcurrentSiblingRoleSurvivesLockClaim, which injects a sibling role's write between the initial read and the lock claim (via a GetRepoVariable-hooking fake) and asserts it survives.
  3. [missing-test] gitlab_roles_rotate_test.go:732 — TestRotateGitLabRoleCredentials_RecoveryAfterPartialDistributionWithoutForce did not assert Rotated or the created-token count, so a regression that no-op'd without appending Skipped would still pass (internal/repos/gitlab_roles_rotate_test.go): Added assert.Equal on result.Rotated and require.Len on tokens.created (== 1), matching the Force recovery test's assertions.

Tests: passed

Decision points
  • Requiring distribution proof unconditionally (not just in ambiguous overlap/distributing/failed cases) also affects already-healthy roles that were never rotated or provisioned by this codebase (e.g. seeded directly in tests, or from before this feature existed) (alternatives: Keep the old needsProof gate and only require proof in ambiguous cases (rejected: this is the exact bug the reviewer flagged), Require proof unconditionally everywhere, and also make provisionOwnRoles write that proof going forward; rationale: The reviewer's remediation explicitly asks for unconditional proof, including the single-PAT case, and explicitly asks for provisioning to write the same proof so a healthy provisioned credential isn't immediately re-minted. Updated two existing tests (TestProvisionGitLabRoleCredentials_FreshBuiltins, TestRotateGitLabRoleCredentials_CustomOwnAndReuse) to seed that proof for already-healthy roles, matching what real production state would look like once provisioning also records it.)

Next steps:

  • /fs-review — request a re-review of the changes
  • /fs-fix <your instruction> — run another fix pass with specific guidance
  • Push commits directly — review re-runs automatically on push
    Updated by fullsend fix agent

@fullsend-ai-review

fullsend-ai-review Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 11:33 AM UTC · Completed 11:57 AM UTC

Commit: addc8a2 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5 · Effort: high · Cost: $9.11

fullsend-ai-review[bot]

This comment was marked as outdated.

@fullsend-ai-coder

fullsend-ai-coder Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Finished Fix · ✅ Success · Started 11:59 AM UTC · Completed 12:14 PM UTC

Commit: addc8a2 · View workflow run →

Runtime: claude · Model: sonnet → claude-sonnet-5 · Effort: high · Cost: $2.05

…lacements

currentListed (the "current PAT" selector distributionProven compares
IncomingID against) picked whichever same-named token GitLab listed
first when two active PATs shared a calendar-day expiry, since
exp.After never fires on a tie. A same-day force-rotate or recovery
mint could therefore leave a healthy, already-distributed replacement
unrecognized as current, causing the next non-Force rotate to treat it
as unproven and mint again. Separately, the unparseable-expiry branch
could steal "current" from a valid dated winner because it compared
only token IDs without checking whether a dated winner had already
been found.

Mirror currentToken's guard against unparseable expiries displacing a
dated winner, and add a higher-token-ID tie-break for equal expiries
so a same-day replacement is recognized as current regardless of list
order. Add direct unit tests for both branches of currentListed and an
integration-level regression test seeding two same-day PATs (older ID
listed first, incoming_id set to the newer ID) asserting the next
non-Force rotate skips rather than minting.

Note: pre-commit run could not fetch its hook repositories (sandbox
network policy). Ran the applicable local file-type hooks directly
instead: gofmt (clean) and go vet ./... (clean). Full go test ./...
passes for internal/repos and internal/gitlabroles; three pre-existing
failures elsewhere (internal/cli TestPostScriptEnv_* and
internal/fetch TestPortRestriction/DefaultRejectsNonStandard) are
unrelated to this change (sandbox network/DNS restrictions and
unrelated schema-env logic) and were not touched by this commit.

Addresses #7514
@fullsend-ai-coder

Copy link
Copy Markdown
Contributor Author

🔧 Fix agent — iteration 1 (bot-triggered)

Fixed the reviewer's currentListed logic-error finding: the selector now mirrors currentToken's unparseable-expiry guard and adds a higher-token-ID tie-break for equal (same-day) expiries, so a same-day replacement is recognized as the current PAT instead of whichever token GitLab lists first. Added unit and integration regression tests per the reviewer's remediation and verified currentListed reaches 100% function coverage.

Fixed (1):

  1. logic-error: currentListed is not a stable current-PAT selector at internal/repos/gitlab_roles_rotate.go:897 (same-day expiry ties resolve to list order, and the unparseable-expiry branch can steal current from a valid dated winner) (internal/repos/gitlab_roles_rotate.go): Fixed currentListed to (1) never let an unparseable ExpiresAt displace a winner that already has a valid parsed expiry, matching currentToken's guard in lifecycle.go, and (2) tie-break equal-expiry tokens on the higher token ID, so a same-day force-rotate/recovery replacement is recognized as the current PAT regardless of GitLab's list order. Added internal/repos/gitlab_roles_rotate_test.go unit tests (TestCurrentListed_SameDayExpiryTieBreaksOnHigherID, TestCurrentListed_UnparseableExpiryNeverDisplacesParsedWinner) covering both branches directly, and an integration-level regression test (TestRotateGitLabRoleCredentials_SameDayReplacementIsRecognizedAsCurrent) that seeds two active same-named PATs with identical ExpiresAt, older ID listed first, rotation-state incoming_id set to the newer ID, and asserts the next non-Force rotate skips rather than minting a replacement.

Tests: passed

Decision points
  • Scoped this run to only the single current-review finding on currentListed (alternatives: Re-address findings from the collapsed
    Details history blocks (prior iterations already resolved and reverified by the reviewer), Address only the new finding in the top-level review body; rationale: The fix-review procedure instructs treating
    blocks as prior iterations to ignore; the current (non-collapsed) review body contains exactly one new medium-severity finding, which is the one addressed here.)

Next steps:

  • /fs-review — request a re-review of the changes
  • /fs-fix <your instruction> — run another fix pass with specific guidance
  • Push commits directly — review re-runs automatically on push
    Updated by fullsend fix agent

@fullsend-ai-review

fullsend-ai-review Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 12:16 PM UTC · Completed 12:30 PM UTC

Commit: 0f5f723 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5 · Effort: high · Cost: $3.79

@fullsend-ai-review
fullsend-ai-review Bot dismissed stale reviews from themself September 21, 2026 12:30

Superseded by updated review

@fullsend-ai-review fullsend-ai-review Bot added the ready-for-merge All reviewers approved — ready to merge label Sep 21, 2026
@ggallen
ggallen added this pull request to the merge queue Sep 21, 2026
Merged via the queue into main with commit e1f2c8a Sep 21, 2026
54 checks passed
@ggallen
ggallen deleted the agent/7500-gitlab-role-credential-rotation branch September 21, 2026 13:36
@fullsend-ai-retro

fullsend-ai-retro Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🤖 Finished Retro · ✅ Success · Started 1:38 PM UTC · Completed 1:46 PM UTC

Commit: 0f5f723 · View workflow run →

Runtime: claude · Model: sonnet → claude-sonnet-5 · Effort: high · Cost: $2.15

@fullsend-ai-retro

Copy link
Copy Markdown

PR #7514 (GitLab role credential rotation, #7500) took 9 automated review rounds and 7 fix rounds — hitting the bot fix-iteration cap of 5 at fix #6 and escalating to human ggallen — before merging ~12.5h after triage-ready. The review agent repeatedly caught genuine high/medium-severity concurrency and security bugs in the PAT rotation state machine (orphan-token stranding on crash, revoking a live in-use token during recovery, self-revocation of a just-enrolled replacement, cross-process rotation-lock races, a fail-open state loader, and a final tie-break edge case), and a human reviewer (ggallen) verified each fix inline before approving and merging — a healthy, substantive review process on both sides, not a rubber stamp. The root-cause driver of the high rework rate was on the code-generation side: the code agent's skill set contains no guidance on safe credential/secret rotation patterns (revoke-after-verify ordering, idempotent/crash-resumable state machines, avoiding self-revocation, concurrent-lock correctness) — confirmed absent from agents/code.md and skills/code-implementation/SKILL.md in fullsend-ai/agents@57df504a4e48. I'm filing one new proposal for that gap. I checked for duplicates on four other angles surfaced by this PR and found the ground already well covered, so I'm recording them here as evidence rather than new issues: (1) fix-iteration-cap persistence/escalation behavior — this run is a concrete data point matching agents#1293 (bot cap hit, human intervened, 2 more rounds ran under the higher human cap of 10, consistent with the counter not resetting) and generally agents#1297/#1348/#1340/#636/#1294/#1201/fullsend#5547/#7389; no new issue needed. (2) Inline review comment 422s — two out-of-diff pagination findings fell back to a top-level comment successfully in this run, which is useful counter-evidence against fullsend#7346's claim that the fallback path itself fails 100% of the time; matches the well-tracked agents#193/#430/#699/#760/fullsend#6039/#7346 cluster. (3) Risk score staying flat at 'moderate (2/5)' across all 9 rounds despite repeated critical findings is consistent with the risk-assessment sub-agent's documented design (blast-radius/churn/metadata only, explicitly not review-outcome-driven per skills/pr-risk-assessment/SKILL.md) — this is a real data point supporting agents#1349's concern that the risk score discards churn/fix-revert signal, worth attaching there rather than a new issue. (4) No autonomy-readiness gap found: the human's 13 inline comments confirmed bot-identified fixes rather than catching anything new, so the review agent already matches human performance on this class of change; no repo-level autonomy change is indicated beyond what's already in flight.

Proposals filed

This branch was successfully deployed

1 active and 1 inactive deployments
site-preview — 0f5f723d Deployed Sep 21, 2026 by github-actions[bot]
dev — 0f5f723d Deployed Sep 21, 2026 by fullsend-ai-coder[bot] via behaviour #13407
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-human Agent loop needs human intervention ready-for-merge All reviewers approved — ready to merge ready-for-review Triggers review agent dispatch risk/moderate PR risk: moderate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement rotation, recovery, and rollback for GitLab role credentials

1 participant