Skip to content

Support automatic service account token refresh for in-cluster configurations#141

Merged
gtsystem merged 2 commits into
gtsystem:masterfrom
dev022022:master
May 13, 2026
Merged

Support automatic service account token refresh for in-cluster configurations#141
gtsystem merged 2 commits into
gtsystem:masterfrom
dev022022:master

Conversation

@dev022022
Copy link
Copy Markdown
Contributor

Problem

When running lightkube inside a Kubernetes pod, the service account token is mounted as a projected volume at /var/run/secrets/kubernetes.io/serviceaccount/token.
Starting with Kubernetes 1.22+, these tokens are bound and have a limited lifetime (1h by default, configurable via --service-account-max-token-expiration).

Previously, from_service_account() read the token file once at startup and stored it as a static string. When the token expired, all subsequent API calls failed with HTTP 401 — requiring a full client restart to recover. This is a problem when lightkube is for example used in a long running Kubernetes operator.

This is a well-known problem that Go's client-go solves via its fileTokenSource / cachingTokenSource / tokenSourceTransport mechanism, which re-reads the token file and retries on 401.

Solution

This PR adds a BearerTokenFileAuth class that follows in general the same pattern:

  • Caches the token after the initial file read (avoids unnecessary I/O)
  • Re-reads the token from disk and retries when the server returns 401 (the kubelet writes a fresh token before the old one expires, so the rotated token is always available on disk)
  • Works for both sync and async client flows

Backward compatibility

Fully backward compatible:

  • user.token is still populated by from_service_account(), so existing code that reads config.get().user.token continues to work.
  • For kubeconfig-based configurations (where token_file is None), behavior is completely unchanged — the existing BearerAuth with static tokens is used.
  • token_file is only set programmatically by from_service_account(); it does not interfere with YAML kubeconfig parsing.

I also tried to adapt the documentation accordingly. If I missed something or changes are necessary from your pov, please let me know and I will adapt the PR.

dev022022 added 2 commits May 12, 2026 19:56
Extend the currently available token auth mechanism which already reads a token
from file in the from_service_account function by a mechanism which re-reads
the token in case the token is expired (HTTP 401).
Extending existing unit tests to also cover the new functionality.
@gtsystem gtsystem merged commit 5c36844 into gtsystem:master May 13, 2026
17 of 18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants