Skip to content

fix: prevent silent token expiry failures in gateway Vertex/Bedrock providers - #138

Closed
jflowers wants to merge 0 commit into
unbound-force:mainfrom
jflowers:opsx/gateway-token-refresh-fix
Closed

jflowers wants to merge 0 commit into
unbound-force:mainfrom
jflowers:opsx/gateway-token-refresh-fix

Conversation

@jflowers

@jflowers jflowers commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Fixed silent token expiry failures in the gateway's Vertex AI and Bedrock providers that produced cryptic ACCESS_TOKEN_TYPE_UNSUPPORTED (401) errors after ~60 minutes
  • Added token/credential expiry tracking (tokenExpiry/credExpiry fields) with safety margins and atomic stale-token invalidation on refresh failure
  • Added proactive refresh in PrepareRequest with sync.Mutex.TryLock() deduplication and 5-second subprocess timeout
  • Detached gateway now writes logs to .uf/gateway.log (0600 permissions) instead of discarding them; uf gateway status shows the log path

Root Cause

When the background token refresh failed (e.g., gcloud ADC credentials expired), the gateway continued forwarding the stale, expired token to Vertex AI. PrepareRequest only checked for an empty token, not an expired one. Combined with detached mode discarding all child process output, refresh failures were completely silent.

How to Test

Automated tests

# Run the full gateway test suite (includes 14 new test functions)
go test -race -count=1 ./internal/gateway/

# Run only the new token-refresh tests
go test -race -count=1 -run "StaleToken|Proactive|Expired|ClearsToken|ClearsCredentials|LogFile|LogPath|ForegroundNo" ./internal/gateway/

# Run the full project test suite
go test -race -count=1 ./...

Manual testing — Vertex AI (requires GCP project with Claude access)

# 1. Authenticate with gcloud ADC
gcloud auth application-default login

# 2. Set Vertex AI environment
export CLAUDE_CODE_USE_VERTEX=1
export ANTHROPIC_VERTEX_PROJECT_ID=<your-project-id>
export ANTHROPIC_VERTEX_REGION=us-east5  # or your region

# 3. Build and start the gateway
go build -o uf ./cmd/unbound-force/
./uf gateway start --detach

# 4. Verify it's running and log path is shown
./uf gateway status
# Expected output includes:
#   Provider:  vertex
#   Log:       .uf/gateway.log

# 5. Send a test request through the gateway
curl -s http://localhost:53147/v1/messages \
  -H "Content-Type: application/json" \
  -H "x-api-key: gateway" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 32,
    "messages": [{"role": "user", "content": "Say hello"}]
  }'
# Expected: valid response from Vertex AI

# 6. Check gateway logs are captured
cat .uf/gateway.log
# Expected: charmbracelet/log output with startup info

# 7. Simulate expired token — revoke ADC credentials
gcloud auth application-default revoke --quiet

# 8. Wait for the 50-minute refresh to fire, OR restart
#    the gateway to observe the immediate startup failure:
./uf gateway stop
./uf gateway start --detach
# Expected: gateway fails with a clear error message
#   mentioning "gcloud auth application-default login"

# 9. Clean up
./uf gateway stop
gcloud auth application-default login  # re-authenticate

Manual testing — expired token error message

# Build and start the gateway normally
./uf gateway start --detach

# Wait >55 minutes (the token lifetime with safety margin)
# OR to test faster, temporarily modify vertexTokenLifetime
# in provider.go to 1*time.Minute, rebuild, and wait ~1 min

# Send a request after token expires
curl -s http://localhost:53147/v1/messages \
  -H "Content-Type: application/json" \
  -H "x-api-key: gateway" \
  -d '{"model":"claude-sonnet-4-20250514","max_tokens":1,"messages":[{"role":"user","content":"hi"}]}'

# Expected: 502 JSON error with actionable message:
# {"error":{"type":"auth_error","message":"vertex AI token expired. Re-authenticate: gcloud auth application-default login"}}

# Check the log file for refresh failure details
cat .uf/gateway.log

Manual testing — log file behavior

# Foreground mode: logs go to stderr, no log file created
./uf gateway start  # (Ctrl+C to stop)
ls -la .uf/gateway.log  # should NOT exist (or be from a previous detach run)

# Detached mode: logs go to .uf/gateway.log
./uf gateway start --detach
ls -la .uf/gateway.log
# Expected: -rw------- (0600 permissions, owner-only)

# Status shows log path
./uf gateway status
# Expected: "Log:       .uf/gateway.log" line in output

./uf gateway stop

Manual testing — Bedrock (requires AWS account with Bedrock access)

# 1. Authenticate with AWS SSO
aws sso login

# 2. Set Bedrock environment
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION=us-east-1  # or your region

# 3. Start and test (same flow as Vertex above)
./uf gateway start --detach
./uf gateway status
curl -s http://localhost:53147/v1/messages \
  -H "Content-Type: application/json" \
  -H "x-api-key: gateway" \
  -d '{"model":"claude-sonnet-4-20250514","max_tokens":32,"messages":[{"role":"user","content":"Say hello"}]}'

./uf gateway stop

Changes

File Change
internal/gateway/provider.go +223 lines: expiry fields, named constants (vertexTokenLifetime, proactiveRefreshWindow, bedrockCredLifetime), tryProactiveRefresh() with goroutine+channel timeout, atomic token clearing on refresh failure
internal/gateway/gateway.go +37 lines: log file creation in detach() with 0600 permissions, parent fd cleanup, log path in status output
internal/gateway/gateway_test.go +572 lines: 14 new test functions, 8 updated existing call sites
AGENTS.md Recent Changes entry
openspec/changes/gateway-token-refresh-fix/ Proposal, design, delta spec (FR-001 through FR-007), tasks (7 groups, 42 tasks)
Scaffold assets (18 files) Pre-existing drift sync

Test Results

All 19 packages pass with -race -count=1. 14 new test functions:

  • TestVertexPrepareRequest_StaleTokenRegression (TC-006 regression test)
  • TestVertexPrepareRequest_ValidToken
  • TestVertexPrepareRequest_ProactiveRefresh
  • TestVertexPrepareRequest_ProactiveRefreshFails
  • TestVertexPrepareRequest_ProactiveRefreshTimeout
  • TestVertexRefreshFailure_ClearsToken
  • TestVertexPrepareRequest_ConcurrentProactiveRefresh (WaitGroup barrier + atomic counter)
  • TestBedrockPrepareRequest_ExpiredCredentials
  • TestBedrockRefreshFailure_ClearsCredentials
  • TestBedrockPrepareRequest_ProactiveRefresh
  • TestBedrockPrepareRequest_ProactiveRefreshFails
  • TestDetach_CreatesLogFile
  • TestStatus_ShowsLogPath
  • TestStart_ForegroundNoLogFile

Review Council

Spec review: 5/5 APPROVE (2nd pass after fixing HIGH findings)
Code review: 5/5 APPROVE (2nd pass after implementing missing timeout)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

1 participant