Skip to content

Limit the number of agent tokens created

Pam Artiaga requested to merge pam/limit-agent-tokens-creation into master

What does this MR do and why?

Issue: #361030 (closed)

The Agent Tokens API (REST and GraphQL) include the last_used_at field in the returned list of agent tokens. (See #361030 (comment 1391404262)).

The last_used_at column is cached in Redis via cached_attr_reader :last_used_at. So, when loading multiple tokens on the "list" API endpoint, the presenter will hit Redis once per token record. This is considered a N+1 problem.

We want to minimize the the number of requests to Redis. The solution we have come up with is to limit the number of tokens per agent to 2. Having a fewer number of tokens to be managed will also help with security.

Existing Agents with more than 2 Tokens will still be allowed.

Screenshots or screen recordings

UI

Agent with 2 tokens

setup_agent-tokens

Attempt to create a 3rd token - ERROR

create_error_ui

REST API

Creating a second token - SUCCESS

create_successful_restapi

Creating a third token - ERROR

create_error_restapi

GraphQL API

Creating a second token - SUCCESS

create_successful_graphql

Creating a third token - FAILURE

create_error_graphql

How to set up and validate locally

  1. Choose an existing test project or create a new one

  2. Create a new Agent in the project (steps 1 and 2 in this guide). You should only be able to create up to 2 tokens for this agent.

  3. To test the UI - navigate to the Agent page -> Agent Tokens tab, and create new tokens.

  4. To test the REST API, call the POST /projects/:id/cluster_agents/:agent_id/tokens endpoint:

    Example:

    $ curl "https://gdk.test:3443/api/v4/projects/20/cluster_agents/26/tokens" \
    -ki -X POST \
    --header "Authorization: Bearer $PERSONAL_ACCESS_TOKEN" \
    --header "Content-Type: application/json" \
    --data "{\"name\": \"agentk-test-1-token-2\", \"description\":\"this is the second token\"}"
  5. To test the GraphQL API, call the clusterAgentTokenCreate mutation.

    Example:

    $ curl "https://gdk.test:3443/api/graphql" \
    -k -X POST \
    --header "Authorization: Bearer $PERSONAL_ACCESS_TOKEN" \
    --header "Content-Type: application/json" \
    --data "{\"query\": \"mutation { clusterAgentTokenCreate(input: {clusterAgentId: \\\"gid://gitlab/Clusters::Agent/26\\\", name: \\\"agentk-test-1-token-2\\\", description: \\\"this is the second agent token\\\"}) { clientMutationId errors token { id name lastUsedAt status description }} }\"}" \
    | json_pp -json_opt pretty,canonical

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 Pam Artiaga

Merge request reports