Add service to restore a GitHub sync repository with a new token
What does this MR do and why?
Adds POST /projects/:id/import/github/sync/restore, so a user can reconnect GitHub updates for a project imported with a personal access token (PAT) after the token was revoked or expired.
Currently a PAT can't be re-authorized in the browser like an OAuth token, so once sync disconnects the repository after repeated authentication failures there is no way back. The new endpoint takes a new token, checks that it reads the same GitHub repository, replaces the stored token, reconnects the repository and re-creates the webhook.
This is MR 3 of 3 for #634424 (closed). It builds on the credential_type column from !270471 (merged) and the PAT continuous sync support from !271321 (merged).
The endpoint exists on EE only. CE has no route.
Changes
- Service:
Import::Sync::Github::PersonalAccessToken::RestoreService.- Guards: rejects a caller without
restore_github_update(the route also authorizes, so the service stays safe if it is called from elsewhere), and a repository that is not a PAT repository (bycredential_type, not by import data), is not disconnected, or whose project has no import data. - Token check: with the new token, reads the repository by its numeric GitHub id and reads the GitHub user, both before anything is written. A token that can't read the repository, or that reads a different repository, changes nothing. The GitHub account is not compared, so a teammate can rotate the token.
- Writes: under a row lock, re-checks that the repository is still disconnected, replaces
credentials[:user], stores the new token'sprovider_account_xidandprovider_account_login, and restores the repository to the state it had before it was disconnected.connected_by_useris left alone. - Webhook: reuses
Oauth::WebhookManagementService#enable, which does nothing if a hook is already recorded.- An exact
ForbiddenorNotFoundkeeps the repository connected without a webhook and returns awarning. - Any other error, a busy lease or a rejected token puts the old token, the old account fields and the disconnected state back. A project that had no stored token gets none written back.
- The rollback runs under the row lock. If another change moved the repository in the meantime, for example a stop request that moved it to
cutting_over, the rollback leaves the token and state alone, so the stop is not dropped. The error is still returned.
- An exact
- Catch-up: requests an update so changes missed while disconnected are picked up. It is skipped when the repository restores to
provisioning, which its import handles. A failed catch-up request is logged or sent to error tracking and does not fail the restore. - Token handling: the token is never logged or returned, and
inspectis overridden.
- Guards: rejects a caller without
- Shared webhook handling:
EnableContinuousSyncWorkerand the restore service now shareImport::Sync::Github::MissingWebhookService, so both treat a missing webhook permission the same way.- Import failure: the worker still records a non-fatal import failure. The restore passes
record_failure: false, because a restore on a finished import would add a failure row each time. - Log field: the
import_stagelog field is nowerror_source, as the caller can be a service.
- Import failure: the worker still records a non-fatal import failure. The restore passes
- Route (EE):
ee/lib/ee/api/import_github.rb.- Authorization: uses the new
restore_github_updatepermission with a project boundary, plusfind_project!andauthorize!. It needs the Maintainer role. - Tier:
route_setting :tier, :premium, asgithub_continuous_syncis a Premium feature. - Rate limit: shares the
project_importlimiter withPOST /import/github. - No flag check:
github_continuous_importis not checked, like the other GitHub updates actions, so a project that already has sync stays manageable. - Response: the existing GitHub updates status payload, plus
warningwhen the webhook could not be created.
- Authorization: uses the new
- Authz: adds a dedicated
restore_github_updatepermission, so a granular token that can only request an update cannot replace the stored GitHub credential. It follows the other GitHub updates permissions: granted to Maintainer, denied on archived and pending-deletion projects, and available to granular access tokens through its own assignable group.update_github_updateis unchanged.fine_grained_access_tokens_rest.mdis regenerated. - Audit event: a new
github_updates_restoredevent records who restored GitHub updates, likegithub_updates_stop_requesteddoes for a stop. An audit failure is sent to error tracking and does not fail the restore.audit_event_types.mdis regenerated. - Docs: a section and history entry in
doc/api/import.md, and the new path indoc/api/openapi/openapi_v3.yaml.
Status codes
| Case | Status |
|---|---|
| Restored | 200 |
personal_access_token missing or blank |
400 |
| GitHub rejects the token (on the repository or the user read) | 401 |
| No permission | 403 |
| No project, or no GitHub updates | 404 |
| GitHub updates not disconnected, or another change in progress | 409 |
| Not a PAT repository, token can't read the repository, reads a different one, or another GitHub client error | 422 |
| Rate limited, by GitLab or by GitHub | 429 |
| GitHub is not available, or the connection to GitHub failed | 503 |
Behavior to note
- Permission scope: a granular token needs
restore_github_updateto use this endpoint. A token that only hasupdate_github_updatecannot replace the stored credential. - Any account's token is accepted: a PAT usually stops working when its owner leaves, so a teammate has to be able to supply a new one. The restore stores the new token's GitHub account (
provider_account_xidandprovider_account_login) so the record matches the token in use. This differs from the OAuth reauthorize flow, which requires the same account. connected_by_useris not changed: it records who first connected the repository, and nothing reads it. Thegithub_updates_restoredaudit event records who restored.- No webhook is not a failure: a token without webhook access restores sync with a warning and a scheduled check, matching the import behavior in !271321 (merged).
Not in this MR
- The UI to restore a disconnected PAT repository: #639656.
- The user docs and the fine-grained token wording in the importer: #639657 (closed).
Review notes
- Failure mapping: the repository read, the user read and the webhook step map GitHub errors the same way: 5xx and connection failures or timeouts to 503, other client errors to 422, and rate limits propagate as 429. The user read goes through the client's
with_rate_limit, like the repository read. - Spec files: the service spec covers each branch, including rollback, the held lease, a concurrent reconnect and a stop request that arrives while the webhook is created. It also covers the account fields on success and rollback, and the authorization check. The request spec covers each status code, the shared rate limit, a granular token, and that the token is never returned or logged.
- Database review: there are no migrations, queries or scopes in this MR. The restore writes the existing sync repository row with single-row updates under the existing row lock.
- Audit event type:
introduced_by_mringithub_updates_restored.ymlis !272186 (merged). The docs milestone is 19.7, like !271321 (merged). - Router sync: the route snapshot was added in the paired MR gitlab-org/cells/http-router!1556 (merged), which is merged. The
pipeline:skip-router-synclabel was used while that MR was open.
How to set up and validate locally
With an EE license, a project imported with optional_stages[continuous_sync]=true and a disconnected repository, run this with your own values:
curl --request POST --header "PRIVATE-TOKEN: <gitlab token>" \
--header "Content-Type: application/json" \
--data '{"personal_access_token":"<new github token>"}' \
"https://gdk.test:3000/api/v4/projects/<id>/import/github/sync/restore"Then check that:
- The response is
200and the repository is back inprovider_canonical. - The repository's
provider_account_xidandprovider_account_loginmatch the user of the new token. - A token for another repository returns
422and the stored token is unchanged. - A token without webhook access returns
200with awarningand no webhook. - A project imported with OAuth returns
422, and one that is not disconnected returns409. - A Developer gets
403. - Each restore adds a
github_updates_restoredaudit event.
References
Relates to #634424 (closed)
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.
Related to #634424 (closed)