DEV Community

Cover image for A refresh you cannot keep: re-authorizing Bitbucket Cloud import
Priyanshu Jha
Priyanshu Jha

Posted on

A refresh you cannot keep: re-authorizing Bitbucket Cloud import

Bitbucket Cloud access tokens last about two hours. The import page only needs them while you are on that page. Refreshing the token in the session looked like the right fix, until a reviewer pointed out that the refresh itself was the problem.

This is the story of gitlab-org/gitlab!272089. I'll cover the issue that asked us to persist a rotated refresh token, the first version that tried to do that, the review that replaced it with a re-authorize flow, and the later comments that kept import polling from kicking the user out mid-import.

The issue: a refresh token that was already dead

The issue was gitlab-org/gitlab#640895, opened by Jasmin Taj Shaik. Import::BitbucketController could refresh an expired Bitbucket OAuth token, but it never wrote the new credentials back into the session.

Bitbucket Cloud rotates refresh tokens. The previous refresh token is invalid after the first refresh. Every later request then retried with the dead token from the session and failed with unauthorized_client: refresh_token is invalid. Imports looked fine for a couple of hours, then they stayed broken.

The issue asked for the refreshed credentials to be persisted. That is a reasonable first reading of the failure.

Version 1: write the new tokens back

The first commit (2d7167a81a) did what the issue asked. It introduced a session refresh strategy and wrote the rotated access token, expiry, and refresh token back into the Rails session so the next request would not reuse the dead token.

That closes the "we forgot to save" hole. It opens a different one. If two tabs refresh at the same time, both read the same refresh token from the session, both rotate it, and only one write wins. The other tab has just invalidated the token the winner stored. You can also get the same mess if a request refreshes in memory in the Bitbucket gem and something else still holds the old session values.

The review: stop refreshing in the controller

Rodrigo Tomonari reviewed it and proposed not refreshing in the controller at all:

Bitbucket access tokens last about two hours, and the session only needs them while the user is on the import page. Instead of refreshing (and rotating) the refresh token in the session, what do you think about not refreshing in the controller at all: when bitbucket_expires_at has passed, clear the session credentials and send the user back to the authorize page, the same way a missing token does in bitbucket_auth? That would remove the rotation problems in the session, such as race conditions when multiple tabs are open and try to refresh the token simultaneously.

That is a better design for this page. The session is a short-lived cache of a token the user can grant again in one redirect. It does not have to be a careful store of rotating credentials.

I took the refresh-and-persist path out and replaced it with a re-authorize flow. When bitbucket_expires_at has passed, or the token is missing, the controller clears the session and sends the user through authorization again:

def bitbucket_auth
  return if bitbucket_session_authorized?

  clear_session_credentials
  request_bitbucket_authorization
end
Enter fullscreen mode Exit fullscreen mode

HTML requests redirect to the Bitbucket authorize URL, as a missing token already did. JSON status and create requests cannot follow a redirect to Bitbucket, so they return { error: { redirect } } with a 404. The import UI already looks for error.redirect and reloads that URL, which then starts the HTML authorize flow.

def request_bitbucket_authorization
  respond_to do |format|
    format.json do
      render json: { error: { redirect: status_import_bitbucket_url(namespace_id: namespace_id_param) } },
        status: :not_found
    end
    format.html { go_to_bitbucket_for_permissions }
  end
end
Enter fullscreen mode Exit fullscreen mode

Because fetchImportFactory is shared, the same error.redirect handling now also covers a Bitbucket Server ConnectionError on create. That request used to show a generic alert. It now follows the redirect to the credentials page with the flash, the way status already did.

The Bitbucket gem may still refresh in memory during a single request. We do not write that rotation back into the session. When create starts an import, it passes ProjectCreator the credentials from client.connection, so the import data stores what the client ended with, not a token the gem may have already rotated past.

Kiesha Herman later asked that we note this on the issue, because #640895 asked for refreshed tokens to be written back. The fix that merged re-authorizes instead. That is the honest description of what shipped.

Do not kick the user out mid-import

A later pass had to special-case realtime_changes. That action lives on the parent controller and only polls import progress. It does not call Bitbucket. If we treat an expired-but-present token as unauthorized there, a long import would send the user back to Bitbucket in the middle of the run, just because the session clock had run out.

# realtime_changes lives on the parent and only polls import progress, so
# an expired-but-present token must not start the authorize flow.
def bitbucket_session_authorized?
  return session[:bitbucket_token].present? if action_name == 'realtime_changes'

  session[:bitbucket_token].present? && !session_credentials_expired?
end
Enter fullscreen mode Exit fullscreen mode

Presence is enough for polling. Expiry is checked on the actions that actually talk to Bitbucket.

The rest of the review

Kiesha reviewed the frontend, asked Carla Drago to look as well, and Carla asked AppSec for an advisory review of how the tokens are stored and cleared in the session. Chris Bonk looked at it and was fine with the change once the bot findings were addressed. There is no database review: these are session.delete calls on the Rails session, which is stored in Redis.

Other review comments that landed in the final MR, in short:

  • Keep namespace_id on the JSON authorize redirect, so the user returns to the same namespace.
  • pathWithParams has to use & when the path already has a query string, or the redirect URL is wrong.
  • Skip the expiry check only inside bitbucket_auth, not on every action.
  • A mid-request credential refresh is stubbed with a plain double of Bitbucket::OauthConnection, so the four readers the controller uses stay verified.

The MR merged on 1 December 2026.

What I took away

1. The issue's proposed fix is a starting point, not a commitment. Persisting the rotated token would have fixed the reported error and created a multi-tab race. Rodrigo's question — does this page even need to refresh? — was the one that mattered.

2. A two-hour token on a page you are sitting on can be re-granted. Re-authorization is a redirect. Token rotation in a shared session is a concurrency problem. For this controller, the redirect is the smaller design.

3. HTML and JSON cannot share one "go to Bitbucket" path. The browser will follow a redirect. An axios call will not, unless the payload tells the UI to reload. error.redirect was already there for status. Create needed to use it too.

4. Not every action that sees the session is talking to Bitbucket. Import progress polling would have been a very confusing place to start an OAuth flow. Expiry belongs on the requests that need a live token.

5. If the shipped approach is not the one the issue asked for, say so on the issue. Otherwise the next reader will wonder why the tokens are still not written back.

Links

Thanks to Jasmin Taj Shaik for the issue, to Rodrigo Tomonari for the design change, to Kiesha Herman and Carla Drago for the frontend and follow-up review, and to Chris Bonk for the AppSec look.

If you've been thinking about contributing to GitLab, the community issues are a great place to start: contributors.gitlab.com.

Top comments (0)