Skip to content

Commit 6375126

Browse files
committed
feat: Automatically generate bedrock token
1 parent f321c20 commit 6375126

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

src/api/routers/bedrock_proxy.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import httpx
77
from fastapi import APIRouter, Depends, HTTPException, Request, BackgroundTasks
88
from fastapi.responses import StreamingResponse, Response
9+
from aws_bedrock_token_generator import provide_token
910

1011
from api.auth import api_key_auth
1112
from api.setting import AWS_REGION, DEBUG
@@ -14,11 +15,23 @@
1415

1516
router = APIRouter(prefix="/bedrock")
1617

17-
# Get AWS bearer token from environment
18+
# Get static token if provided (convenience feature)
1819
AWS_BEARER_TOKEN = os.environ.get("AWS_BEARER_TOKEN_BEDROCK")
1920

20-
if not AWS_BEARER_TOKEN:
21-
logger.warning("AWS_BEARER_TOKEN_BEDROCK not set - bedrock proxy endpoints will not work")
21+
def get_aws_bearer_token() -> str:
22+
"""Get AWS bearer token - static if provided, otherwise auto-generate"""
23+
if AWS_BEARER_TOKEN:
24+
logger.debug("Using static AWS bearer token")
25+
return AWS_BEARER_TOKEN
26+
27+
# Default: auto-generate token using AWS SDK credentials
28+
try:
29+
token = provide_token(region=AWS_REGION)
30+
logger.debug("Generated fresh AWS Bedrock token")
31+
return token
32+
except Exception as e:
33+
logger.error(f"Failed to generate AWS token: {e}")
34+
raise HTTPException(status_code=503, detail="Failed to generate AWS authentication token. Ensure AWS credentials are configured or set AWS_BEARER_TOKEN_BEDROCK")
2235

2336

2437
def get_aws_url(model_id: str, endpoint_path: str) -> str:
@@ -36,8 +49,9 @@ def get_proxy_headers(request: Request) -> Dict[str, str]:
3649
headers.pop("authorization", None)
3750
headers.pop("host", None) # Let httpx set the correct host
3851

39-
if AWS_BEARER_TOKEN:
40-
headers["Authorization"] = f"Bearer {AWS_BEARER_TOKEN}"
52+
# Get fresh AWS token (static or auto-generated)
53+
aws_token = get_aws_bearer_token()
54+
headers["Authorization"] = f"Bearer {aws_token}"
4155

4256
return headers
4357

@@ -53,12 +67,8 @@ async def transparent_proxy(
5367
"""
5468
Transparent HTTP proxy to AWS Bedrock.
5569
Forwards all requests as-is, only changing auth and URL.
70+
Supports both static tokens and auto-refresh tokens.
5671
"""
57-
if not AWS_BEARER_TOKEN:
58-
raise HTTPException(
59-
status_code=503,
60-
detail="AWS_BEARER_TOKEN_BEDROCK not configured"
61-
)
6272

6373
# Build AWS URL
6474
aws_url = get_aws_url(model_id, endpoint_path)

src/requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,5 @@ requests==2.32.4
77
httpx==0.27.0
88
numpy==1.26.4
99
boto3==1.37.0
10-
botocore==1.37.0
10+
botocore==1.37.0
11+
aws-bedrock-token-generator

0 commit comments

Comments
 (0)