Kubernetes Model Serving OAuth2 Token Exchange Failing After Outbound Network Block
Problem
AI model serving pods (e.g., TensorFlow Serving, Triton Inference Server) receive inference requests that require an OAuth2 access token from an external Identity Provider (IdP). In an air‑gapped Kubernetes cluster the outbound network path to the IdP is blocked, causing the token acquisition and refresh steps to time out. All inference requests return 401 Unauthorized and the pod logs contain repeated token‑exchange failures.
Symptoms and Impact
- Inference API returns HTTP 401 with body
{"error":"authentication_failed"}. - Pod logs show:
2024-11-21T10:12:34Z ERROR oauth2: token endpoint returned 504 Gateway Timeout 2024-11-21T10:12:34Z ERROR oauth2: failed to acquire token: context deadline exceeded 2024-11-21T10:13:04Z INFO token refresh scheduled in 30m - Prometheus metric
model_serving_oauth2_token_success{pod="model-serve-1"} = 0. - Downstream services that depend on the model (e.g., recommendation engine) experience increased latency and error rates.
Root Cause Analysis
The model serving container uses the client_credentials grant to obtain an access token from https://idp.example.com/oauth2/token. The Kubernetes nodes have no direct egress to the internet; a NetworkPolicy and host‑level firewall block all outbound TCP/443 traffic except traffic routed through an internal HTTP proxy (http://proxy.internal:3128). The serving code does not respect the HTTP_PROXY/HTTPS_PROXY environment variables, so the TLS handshake never leaves the pod, resulting in a timeout at the HTTP client layer. Consequently, token acquisition fails and the refresh loop never succeeds.
Investigation and Debugging
- Confirm outbound connectivity from a pod:
kubectl exec -it model-serve-1 -- curl -v https://idp.example.com/.well-known/openid-configurationExpected output: HTTP 200 with JSON metadata.
Observed output:curl: (7) Failed to connect to idp.example.com port 443: Connection timed out. - Check proxy environment variables inside the container:
kubectl exec -it model-serve-1 -- env | grep -i proxyObserved: No
HTTP_PROXYorHTTPS_PROXYvariables set. - Inspect the OAuth2 client library configuration (Python example):
import os print(os.getenv("OAUTH2_TOKEN_URL")) print(os.getenv("CLIENT_ID"))The token URL is correct, but the library does not automatically pick up proxy settings.
- Validate NetworkPolicy allowing egress to the proxy:
apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-egress-proxy spec: podSelector: {} policyTypes: - Egress egress: - to: - ipBlock: cidr: 10.0.5.0/24 # proxy subnet ports: - protocol: TCP port: 3128Policy present, but pods are not configured to use the proxy.
Solution
Configure the model serving containers to route all outbound HTTP/HTTPS traffic through the internal proxy and ensure the OAuth2 client library respects those settings.
Step 1 – Add proxy environment variables to the Deployment
Before (partial manifest):
apiVersion: apps/v1
kind: Deployment
metadata:
name: model-serve
spec:
template:
spec:
containers:
- name: model-server
image: myregistry/model-server:2.1
env:
- name: OAUTH2_TOKEN_URL
value: "https://idp.example.com/oauth2/token"
- name: CLIENT_ID
valueFrom:
secretKeyRef:
name: idp-cred
key: client_id
After – proxy variables added and NO_PROXY set for internal services:
apiVersion: apps/v1
kind: Deployment
metadata:
name: model-serve
spec:
template:
spec:
containers:
- name: model-server
image: myregistry/model-server:2.1
env:
- name: OAUTH2_TOKEN_URL
value: "https://idp.example.com/oauth2/token"
- name: CLIENT_ID
valueFrom:
secretKeyRef:
name: idp-cred
key: client_id
- name: HTTP_PROXY
value: "http://proxy.internal:3128"
- name: HTTPS_PROXY
value: "http://proxy.internal:3128"
- name: NO_PROXY
value: "localhost,127.0.0.1,10.0.0.0/8"
Step 2 – Enable proxy support in the OAuth2 client
If using requests (Python) or urllib3, the library reads the environment automatically. For Go’s golang.org/x/oauth2 library, explicitly set a custom http.Client with a proxy transport:
import (
"golang.org/x/oauth2"
"net/http"
"net/url"
)
func newOAuth2Config() *oauth2.Config {
proxyURL, _ := url.Parse("http://proxy.internal:3128")
transport := &http.Transport{Proxy: http.ProxyURL(proxyURL)}
client := &http.Client{Transport: transport}
return &oauth2.Config{
ClientID: os.Getenv("CLIENT_ID"),
ClientSecret: os.Getenv("CLIENT_SECRET"),
Endpoint: oauth2.Endpoint{
TokenURL: os.Getenv("OAUTH2_TOKEN_URL"),
},
// Use the custom client for token exchange
// Note: oauth2.NewClient uses http.DefaultClient by default
}.Client(context.Background(), client)
}
Step 3 – Verify NetworkPolicy permits egress to the proxy
Apply a policy that allows traffic to the proxy on port 3128 for the model serving namespace.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: model-serve-egress-proxy
namespace: ai-models
spec:
podSelector: {}
policyTypes:
- Egress
egress:
- to:
- ipBlock:
cidr: 10.0.5.0/24 # proxy subnet
ports:
- protocol: TCP
port: 3128
Verification
- Redeploy the updated manifest and wait for pods to become ready.
- Check that the proxy variables are present:
kubectl exec -it model-serve-1 -- env | grep -i proxy HTTP_PROXY=http://proxy.internal:3128 HTTPS_PROXY=http://proxy.internal:3128 NO_PROXY=localhost,127.0.0.1,10.0.0.0/8 - Trigger a token request manually:
kubectl exec -it model-serve-1 -- curl -v -X POST \ -d "grant_type=client_credentials&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET" \ $OAUTH2_TOKEN_URLExpected output:
{"access_token":"eyJ...","expires_in":3600,"token_type":"Bearer"}. - Observe pod logs for successful token acquisition:
2024-11-21T10:45:12Z INFO oauth2: obtained access token, expires in 3599s - Run an inference request and confirm HTTP 200 response.
- Verify Prometheus metric:
model_serving_oauth2_token_success{pod="model-serve-1"} = 1
Prevention and Operational Guardrails
- Enforce proxy configuration as a policy: Use an
admission controller(e.g., OPA Gatekeeper) to requireHTTP_PROXY/HTTPS_PROXYin all pods that need external egress. - NetworkPolicy default deny egress combined with explicit allow rules for the proxy ensures no accidental internet exposure.
- Health check endpoint that validates token refresh status; alert on
model_serving_oauth2_token_success == 0for >5 minutes. - Periodic token refresh test via a CronJob that runs the same curl command and reports success/failure to a monitoring system.
- Document offline credential flow (e.g., using service account JWTs exchanged for IdP tokens) for future air‑gapped deployments.
FAQ
- Why does the token exchange work locally but fail in the cluster?
Because the local machine has direct internet access, while the cluster enforces egress through an internal proxy that the container was not configured to use. - Can I use a sidecar proxy (e.g., Envoy) instead of environment variables?
Yes. Deploy a sidecar that intercepts outbound traffic on127.0.0.1:15001and forwards to the internal proxy. Then configure the OAuth2 client to point tohttp://127.0.0.1:15001. This isolates proxy configuration from the application. - What if the IdP requires mutual TLS?
Mount the client certificate and key as a Kubernetes secret, setSSL_CERT_FILEandSSL_KEY_FILEenvironment variables, and ensure the proxy is configured to forward client certificates (e.g.,proxy_ssl_certificatein Nginx). - How do I debug a timeout that still occurs after setting the proxy?
Capture traffic withtcpdumpon the node:sudo tcpdump -i any host proxy.internal and port 3128 -w /tmp/proxy.pcapInspect the pcap for the HTTP POST to the token endpoint and verify the response code.
- Is there a way to avoid outbound calls altogether?
In a fully air‑gapped environment you can use a pre‑generated long‑lived service account token or configure the IdP to accept JWTs signed by an internal CA. The model server then validates the JWT locally without contacting the IdP.
Related Topic Hub: Distributed Systems Troubleshooting Hub