Skip to main content

Policy as Code for API Keys and Tokens

Last updated on

Harness uses Open Policy Agent (OPA) for its policy engine, allowing you to define your governance rules as code using the Rego language.

You can apply these policies to automate and secure how API keys and tokens are created, updated, rotated, and used within your Harness account. For example, you can create a policy that limits token validity duration, enforces naming standards, or requires periodic rotation.

Policies are automatically evaluated during the “On Save” event — which occurs whenever an API key is created or updated, or when a token is created, updated, or rotated.

Prerequisites

Configure Policy as Code for API Keys and Tokens

In the following steps, we use a user API key and token as an example. You can follow the same steps to configure a Service Account API key and token, or a Personal Access Token (PAT).

note

To configure policies at the Organization scope, navigate to the Organization Settings and follow the same process.

Policy Examples

  1. Restrict token creation by type: Prevents users from creating tokens with specific apiKeyType values.

    Account tokens (blocks USER type):

    package opapolicy

    deny[msg] {
    contains(input.token.apiKeyType, "USER")
    msg = sprintf("Token APIKeyType %s contains 'USER'", [input.token.apiKeyType])
    }

    Service Account tokens (blocks SERVICE type):

    package opapolicy

    deny[msg] {
    contains(input.token.apiKeyType, "SERVICE")
    msg = sprintf("Token APIKeyType %s contains 'SERVICE'", [input.token.apiKeyType])
    }
  2. validTo : The expiry timestamp assigned at the time of initial token creation. The example below shows that the expiry time cannot be set beyond the allowed date and time (timestamp: 1779647400000).

    package opapolicy

    deny[msg] {
    input.token.validTo > 1779647400000
    msg = sprintf("For CreateToken, Token APIKeyType ValidTo %v greater than X date", [input.token.validTo])
    }
  3. scheduledExpireTime: The new expiry timestamp set when the token is rotated. The example below show that the expiry time cannot be set beyond the allowed date and time while rotating a token (timestamp: 1771957800000).

    package opapolicy

    deny[msg] {
    input.token.scheduledExpireTime > 1771957800000
    msg = sprintf("For RotateToken, Token APIKeyType ScheduledExpireTime %v greater than X date", [input.token.scheduledExpireTime])
    }