REAL-WORLD SCENARIOS

Diagnosing Token Expiry Failures Across Test Environments

Token expiry failures are some of the most frustrating I see in API suites, not because they're hard to understand but because they look different in every environment. A test passes in dev, fails now and then in staging, and fails reliably in the nightly CI run. The error is usually a bare 401, and the natural reaction is to suspect the credentials or the auth service rather than the clock.

Underneath, the cause is nearly always the same: something in the suite assumes a token lives longer than it does in that environment. Dev might issue tokens that last a working day, staging might mirror production's much shorter lifetime, and CI runs the whole suite in one go, long enough to cross the line. Agents add a new version of the problem. A coding agent running the suite repeatedly while it works, or an evaluation run where an agent makes many tool calls in sequence, can easily outlive a token fetched at the start.

Here's how I read the signals, fix token lifecycle handling so expiry can't silently bite, and keep a diagnostic checklist that holds up as environments change.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Reading the signals

Expiry failures leave a recognisable pattern once you know to look for it:

  • Failures cluster late in a run. Tests that run early pass and tests that run after a certain point fail, whatever they test. Reordering the suite moves the failures with the clock, not with the tests.
  • They depend on the environment, not the code. The same commit passes in one environment and fails in another with a shorter token lifetime.
  • Re-running a single failed test passes. A fresh run fetches a fresh token, so the failure disappears when you look at it.
  • The response says so, if you look. Many servers include the reason in the WWW-Authenticate header or the error body, such as an expired token, which tells you more than the status code.

The quickest confirmation is to log, at session start, how long the token the suite received is valid for, and record the time each 401 happens relative to that. If every failure comes after expiry, you have your answer.

import base64
import json
import logging
import time

log = logging.getLogger("auth")


def token_lifetime(token):
    payload = token.split(".")[1]
    payload += "=" * (-len(payload) % 4)
    claims = json.loads(base64.urlsafe_b64decode(payload))
    return claims.get("exp", 0) - int(time.time())


def log_token_lifetime(env_name, token):
    log.info("env=%s token valid for %ss", env_name, token_lifetime(token))

This only works for JWT access tokens. For opaque tokens, rely on the expires_in value the token endpoint returns, which is the more reliable source anyway.

Fixing token lifecycle management

The fix is to stop treating the token as a constant. A suite should know when its token expires and refresh before that point, in one place.

import threading
import time


class ManagedToken:
    """Holds one access token and refreshes it ahead of expiry."""

    def __init__(self, fetch, refresh_margin=60):
        self._fetch = fetch                  # returns (token, expires_in_seconds)
        self._margin = refresh_margin
        self._lock = threading.Lock()
        self._token = None
        self._expires_at = 0.0

    def get(self):
        with self._lock:
            if time.monotonic() >= self._expires_at - self._margin:
                self._token, expires_in = self._fetch()
                self._expires_at = time.monotonic() + expires_in
            return self._token

The client asks for token.get() on each request instead of storing the header once. Using the expires_in value from the token response, rather than a lifetime hard-coded in the suite, is what makes this work across environments: each one tells you its own lifetime.

A few related rules matter as much as the code:

  • Don't set the header once on a shared session. Fetch the current token per request, or refresh the session header from the managed token.
  • Handle refresh tokens expiring too. If the refresh token itself has a lifetime, the provider needs a path back to a full login, or the long run fails a second time later.
  • Keep the margin generous. A token that is valid when the request is built can expire before the server checks it, especially with slow calls or slightly skewed clocks.
  • Never cache tokens across environments. If you cache to disk to speed up local runs, key the cache by environment and audience.
  • Keep credentials out of the repo. Client secrets per environment come from environment variables or CI secrets; see keeping test secrets out of your version control history.

There's one thing I deliberately don't do: retry any request that gets a 401 with a new token. It makes expiry failures vanish, and it also makes real auth bugs vanish. Refresh based on the known expiry time, and let a 401 fail the test.

Testing expiry on purpose

Expiry handling is behaviour worth testing directly, not just tolerating. Two tests I like to have, where the environment allows:

  • The API rejects an expired token. Use a token that has genuinely expired, or a short-lived one issued for the test, and assert the 401 and the error detail.
  • The client refreshes correctly. Unit-test the provider with a fake fetch and a controllable clock, so the refresh logic is proven without waiting for real expiry.

If an environment allows configuring token lifetime for a test client, a very short lifetime in one scheduled CI job is an effective way to flush out code paths that store tokens. I cover structuring one suite across several targets in when one API test suite covers multiple environments.

Long-running agents and expiring tokens

Agents change the timing. A coding agent might keep a session open and run the suite many times while it works. An agent under test, or an agent doing exploratory testing, might call your API through an MCP server or tool wrapper over a long, multi-step task. Either way, a token fetched at the start is likely to expire partway through, and the symptom looks like the agent suddenly failing.

Two practices help:

  • Put the managed token in the tool layer. The MCP server or tool wrapper should own token refresh, the same way the test client does. The agent should never handle raw tokens, and certainly never have them in its prompt or context.
  • Make expiry visible to the agent. If a tool call fails with 401, return a clear error such as "authentication expired" rather than a raw response, and test that the agent stops and reports it instead of retrying blindly or claiming success.

For agent evaluation runs that execute a task many times to measure a pass rate, separate auth failures from task failures in the results. Otherwise an expired token shows up as the agent getting worse, and someone goes off tuning a prompt to fix a credentials problem.

A diagnostic checklist that survives environment changes

  1. What token lifetime does each environment issue? Log it at session start.
  2. Do failures cluster after that lifetime has passed?
  3. Does anything store a token or header once instead of asking for the current one?
  4. Does the refresh path handle an expired refresh token?
  5. Are any caches shared between environments, audiences or workers?
  6. Do the server's error details or WWW-Authenticate header say "expired"?
  7. For agent runs: does the tool layer refresh tokens, and are auth failures reported separately from task failures?

Not every intermittent 401 is expiry; races, clock skew and leaking headers produce similar symptoms, and I cover those in intermittent 401s that aren't actually auth failures. If you'd like to build token handling like this into a suite from day one, my API testing courses walk through it in Python and Node with GitHub Copilot.