Support granular scopes when admins create a personal access token for a user via REST

Problem

Admins can't create a fine-grained personal access token for another user through the REST API.

POST /users/:user_id/personal_access_tokens only accepts legacy scopes, and scopes is required. The other token creation endpoints already accept granular_scopes:

The workaround today is an impersonation token with granular_scopes, but that token doesn't show up on the user's own access tokens page and isn't what most people are after.

This came up in gitlab-org#18555 (comment 3890422549).

Proposal

Add optional granular_scopes to POST /users/:user_id/personal_access_tokens, following the same pattern as the impersonation tokens endpoint in lib/api/users.rb:

  • Make scopes optional and require exactly one of scopes or granular_scopes.
  • Build the scopes for the target user with build_granular_scopes and create the token with create_granular_token(..., target_user:).
  • Return 404 when granular_personal_access_tokens is disabled for the target user.
  • Document the new parameter in doc/api/user_tokens.md, together with the impersonation tokens one, which is also undocumented.

This is additive. Requests that pass scopes keep working as they do now.

Edited by 🤖 GitLab Bot 🤖