Skip to content

Expose `created_by.id` and `created_by.username` in the Users API

Kenneth Chu requested to merge kenneth-expose-created-by-id-in-api into master

What does this MR do and why?

Expose created_by.id and created_by.username in the Users API for admin users.

A customer contacted us about wanting to get the information about who created a bot user with the API. Internal ZD ticket: https://gitlab.zendesk.com/agent/tickets/310043

Example API response

$ curl -s --header "PRIVATE-TOKEN: <ADMIN_TOKEN>" https://example.gitlab.com/api/v4/users/22 | jq
{
  "id": 22,
  "username": "project_23_bot",
  "name": "aa",
  ...
  "created_by": {
    "id": 1,
    "username": "root"
  },
  ...
}

How to set up and validate locally

  1. Create 3 users for testing
  2. Note the IDs of each user (can be found in the admin section of each user)
  3. Create an admin token for the API with the read_api scope.
    • Navigate to https://gitlab.example.com/api/v4/users/<user_id> for each created test user.
    • created_by_id should be present for Users 1 and 2, and should be null on User 3
  4. Create a user token for the API with the read_api scope. (any user).
    • Navigate to https://gitlab.example.com/api/v4/users/<user_id> for each created test user.
    • created_by_id should be not be present in the API response for any user.

Tests

On a service account

$ curl -s --header "PRIVATE-TOKEN: <ADMIN_TOKEN>" https://example.gitlab.com/api/v4/users/22 | jq
{
  "id": 22,
  "username": "project_23_bot",
  "name": "aa",
  ...
  "created_by": {
    "id": 1,
    "username": "root"
  },
  ...
}

On an account that was created by an admin manually

curl -s --header "PRIVATE-TOKEN: <ADMIN_TOKEN>" https://example.gitlab.com/api/v4/users/16 | jq
{
  "id": 16,
  "username": "cherry",
  "name": "cherry",
  ...
  "created_by": {
    "id": 1,
    "username": "root"
  },
  ...
}

On an account created via sign up

$ curl -s --header "PRIVATE-TOKEN: <ADMIN_TOKEN>" https://example.gitlab.com/api/v4/users/23 | jq
{
  "id": 23,
  "username": "New_User",
  "name": "New User",
  ...
  "created_by": {
    "id": null,
    "username": null
  },
  ...
}

User token

created_by doesn't show up with a normal user token, matching that only the admin area can you see who created a user:

$ curl -s --header "PRIVATE-TOKEN: <USER_TOKEN>" https://example.gitlab.com/api/v4/users/16 | grep created_by

$ curl -s --header "PRIVATE-TOKEN: <USER_TOKEN>" https://example.gitlab.com/api/v4/users/22 | grep created_by

$ curl -s --header "PRIVATE-TOKEN: <USER_TOKEN>" https://example.gitlab.com/api/v4/users/23 | grep created_by

MR acceptance checklist

This checklist encourages us to confirm any changes have been analyzed to reduce risks in quality, performance, reliability, security, and maintainability.

Edited by Kenneth Chu

Merge request reports