Limit the number of agent tokens created
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 viacached_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
Attempt to create a 3rd token - ERROR
REST API
Creating a second token - SUCCESS
Creating a third token - ERROR
GraphQL API
Creating a second token - SUCCESS
Creating a third token - FAILURE
How to set up and validate locally
-
Choose an existing test project or create a new one
-
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.
-
To test the UI - navigate to the Agent page -> Agent Tokens tab, and create new tokens.
-
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\"}"
-
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.
-
I have evaluated the MR acceptance checklist for this MR.