Add cloud-providers module: keyless Spring AI on Amazon Bedrock (AWS default credential chain under IRSA and EKS Pod Identity) and Azure OpenAI (managed identity, Microsoft Entra ID bearer tokens), an audit advisor, and the traps reproduced (leftover static key beats the role, AWS_REGION ignored by Bedrock auto-configuration, short-lived credentials refetched per call, azure-identity missing, leftover OPENAI_API_KEY, other modalities defaulting to OpenAI, SigV4 session token in AWS SDK DEBUG logs). No AWS account or Azure subscription used: a local server stands in for STS, Bedrock, the Azure identity endpoint and Azure OpenAI; the Spring AI, AWS SDK and azure-identity code is real. Spring Boot 4.2.0, Spring AI 2.1.0, Java 25.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5uEyg58znuchZ8C8i
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
98ed878675
commit
8f69e7bf50
@@ -0,0 +1 @@
|
||||
target/
|
||||
@@ -0,0 +1,60 @@
|
||||
# cloud-providers
|
||||
|
||||
Keyless Spring AI on **Amazon Bedrock** (IAM role, IRSA, EKS Pod Identity) and **Azure OpenAI** (Microsoft Entra ID, managed identity): no API key and no secret key in the application, and an audit line for every model call.
|
||||
|
||||
**No AWS account and no Azure subscription was used, and no real cloud endpoint was called.** `LocalCloud` is one local HTTP server that stands in for AWS STS, Bedrock Runtime, the Azure managed identity token endpoint and an Azure OpenAI chat-completions endpoint. The real Spring AI classes (`BedrockProxyChatModel`, `OpenAiChatModel`), the real AWS SDK v2 credential provider chain and the real `azure-identity` library run in a child JVM with an exact environment (`AWS_ROLE_ARN`, `AWS_WEB_IDENTITY_TOKEN_FILE`, `AWS_CONTAINER_CREDENTIALS_FULL_URI`, `IDENTITY_ENDPOINT`, `IDENTITY_HEADER`) and talk to it, so what the stub records is what those libraries send. What is **not** verified: that a real STS, Entra ID, Bedrock or Azure OpenAI accepts those requests; IAM and Azure RBAC policies (`deploy/` files are examples, never applied); model ids; EKS and AKS webhooks; CloudTrail and Azure Monitor contents; latency.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Spring Boot | 4.2.0 (GA 2026-11-19) |
|
||||
| Spring AI | 2.1.0 (GA 2026-11-19) |
|
||||
| AWS SDK for Java v2 | 2.55.14 (what Spring AI 2.1.0 resolves; Maven Central has 2.59.11) |
|
||||
| azure-identity | 1.19.0 (latest on Maven Central; Spring AI does not bring it, you add it) |
|
||||
| Java | 25 (Temurin 25.0.5.1) |
|
||||
|
||||
## Run it
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=/path/to/jdk-25
|
||||
./scripts/run-all.sh # runs the tests; they write every file under output/
|
||||
```
|
||||
|
||||
Every figure in `output/` is also an assertion in a test. Each scenario starts the application in its own JVM, so the full run takes several minutes.
|
||||
|
||||
To run the application by hand against your own account: `SPRING_PROFILES_ACTIVE=bedrock` (credentials come from whatever your environment provides) or `azure` / `azure-default` with `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_DEPLOYMENT` set.
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | What it is |
|
||||
|---|---|
|
||||
| `src/main/.../AuditAdvisor.java` | One structured audit line per model call: provider, principal, model, outcome, tokens. No prompt, no secret |
|
||||
| `src/main/.../BedrockConfig.java` | Audit identity for Bedrock: STS `GetCallerIdentity` through the same credentials provider. No credential code |
|
||||
| `src/main/.../BedrockRegionFromEnvConfig.java` | A one-bean fix so Bedrock honours `AWS_REGION` (profile `bedrock-region-env`) |
|
||||
| `src/main/.../AzureConfig.java` | Explicit `ManagedIdentityCredential` and an `OpenAiChatModel` built on it (profile `azure`) |
|
||||
| `src/main/.../AzureDefaultConfig.java` | Properties-only Azure: Spring AI builds `DefaultAzureCredential` (profile `azure-default`) |
|
||||
| `src/main/resources/application-*.properties` | The whole configuration per profile |
|
||||
| `src/test/.../support/LocalCloud.java` | The local stand-in for STS, Bedrock, the Azure identity endpoint and Azure OpenAI |
|
||||
| `src/test/.../support/AppProcess.java` | Runs the real application in a child JVM with an exact environment |
|
||||
| `deploy/` | Example IAM policies, IRSA and Pod Identity manifests, Azure CLI steps. **Never applied** |
|
||||
| `scripts/azure-starter-check.sh` | Shows that the dedicated Azure OpenAI starter is not in the Spring AI 2.1.0 BOM |
|
||||
|
||||
## Captured output
|
||||
|
||||
| File | Test | What it shows |
|
||||
|---|---|---|
|
||||
| [`00-azure-starter.txt`](output/00-azure-starter.txt) | `scripts/azure-starter-check.sh` | `spring-ai-starter-model-azure-openai` stops at 2.0.0-M4 and is not in the 2.1.0 BOM |
|
||||
| [`01-bedrock-irsa.txt`](output/01-bedrock-irsa.txt) | `BedrockTest` | IRSA environment in, SigV4 request signed with temporary STS credentials out |
|
||||
| [`02-bedrock-region-trap.txt`](output/02-bedrock-region-trap.txt) | `BedrockTest` | `AWS_REGION` is ignored by Spring AI's Bedrock auto-configuration, and a one-bean fix |
|
||||
| [`03-bedrock-precedence.txt`](output/03-bedrock-precedence.txt) | `BedrockTest` | A leftover `AWS_ACCESS_KEY_ID` or `spring.ai.bedrock.aws.access-key` beats the role |
|
||||
| [`04-bedrock-no-credentials.txt`](output/04-bedrock-no-credentials.txt) | `BedrockTest` | The full chain error, and a failed call that is still audited |
|
||||
| [`05-bedrock-credential-refresh.txt`](output/05-bedrock-credential-refresh.txt) | `BedrockTest` | STS calls for five Bedrock calls at three credential lifetimes |
|
||||
| [`06-bedrock-pod-identity.txt`](output/06-bedrock-pod-identity.txt) | `BedrockTest` | EKS Pod Identity: the same application, the container credentials endpoint |
|
||||
| [`07-azure-managed-identity.txt`](output/07-azure-managed-identity.txt) | `AzureTest` | Bearer token from the identity endpoint, no `api-key` header |
|
||||
| [`07b-azure-leftover-api-key.txt`](output/07b-azure-leftover-api-key.txt) | `AzureTest` | A leftover `OPENAI_API_KEY` in the environment turns Entra ID off (profile `azure-default`) |
|
||||
| [`08-azure-token-refresh.txt`](output/08-azure-token-refresh.txt) | `AzureTest` | Identity endpoint calls for five chat calls at three token lifetimes |
|
||||
| [`09-azure-without-azure-identity.txt`](output/09-azure-without-azure-identity.txt) | `AzureTest` | The failure when `azure-identity` is not on the classpath |
|
||||
| [`10-azure-identity-failure.txt`](output/10-azure-identity-failure.txt) | `AzureTest` | An unusable managed identity, and the audited failure |
|
||||
| [`11-startup-trap.txt`](output/11-startup-trap.txt) | `CommonTest` | Other modalities default to OpenAI and stop startup |
|
||||
| [`12-audit-and-secret-hygiene.txt`](output/12-audit-and-secret-hygiene.txt) | `CommonTest` | Audit lines, and a search of the logs for every secret the run handled |
|
||||
|
||||
The article walks through all of this in one page: [Spring AI on Amazon Bedrock and Azure OpenAI: Keyless Auth with IAM Roles and Entra ID](https://ankurm.com/spring-ai-bedrock-azure-openai-keyless-auth-iam-entra-id/).
|
||||
@@ -0,0 +1,35 @@
|
||||
# NOT APPLIED to a real cluster. Client id and names are examples. AKS workload identity: DefaultAzureCredential picks
|
||||
# the federated token up from the environment the webhook injects. Use the azure-default profile, or the azure
|
||||
# profile with a managed identity if the pod runs on a host that has one assigned.
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: spring-ai
|
||||
namespace: ai
|
||||
annotations:
|
||||
azure.workload.identity/client-id: 00000000-0000-0000-0000-000000000000
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: spring-ai
|
||||
namespace: ai
|
||||
spec:
|
||||
replicas: 2
|
||||
selector:
|
||||
matchLabels: { app: spring-ai }
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: spring-ai
|
||||
azure.workload.identity/use: "true"
|
||||
spec:
|
||||
serviceAccountName: spring-ai
|
||||
containers:
|
||||
- name: app
|
||||
image: registry.example.com/spring-ai-cloud-providers:1.0.0
|
||||
env:
|
||||
- name: SPRING_PROFILES_ACTIVE
|
||||
value: azure-default
|
||||
- name: AZURE_OPENAI_ENDPOINT
|
||||
value: https://my-openai-resource.openai.azure.com/openai/v1
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
# NOT RUN against a real subscription. Names are examples. Gives an App Service app a system-assigned managed
|
||||
# identity, lets it call one Azure OpenAI resource with Entra ID, then turns key authentication off.
|
||||
set -euo pipefail
|
||||
RG=my-rg; APP=my-spring-ai-app; AOAI=my-openai-resource
|
||||
|
||||
az webapp identity assign --resource-group "$RG" --name "$APP"
|
||||
PRINCIPAL_ID=$(az webapp identity show --resource-group "$RG" --name "$APP" --query principalId -o tsv)
|
||||
SCOPE=$(az cognitiveservices account show --resource-group "$RG" --name "$AOAI" --query id -o tsv)
|
||||
|
||||
# The data-plane role. Owner and Contributor on the resource do not let a caller run inference with Entra ID.
|
||||
az role assignment create --assignee-object-id "$PRINCIPAL_ID" --assignee-principal-type ServicePrincipal \
|
||||
--role "Cognitive Services OpenAI User" --scope "$SCOPE"
|
||||
|
||||
# Entra ID authentication needs a custom subdomain on the resource (https://<name>.openai.azure.com).
|
||||
# Then switch API keys off, so a leaked key stops being a way in:
|
||||
az resource update --ids "$SCOPE" --set properties.disableLocalAuth=true
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "InvokeOneModelOnly",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"bedrock:InvokeModel",
|
||||
"bedrock:InvokeModelWithResponseStream"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-4-5-20250929-v1:0",
|
||||
"arn:aws:bedrock:us-east-1:111122223333:inference-profile/us.anthropic.claude-sonnet-4-5-20250929-v1:0"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
# NOT APPLIED to a real cluster. Account id, OIDC provider id and names are examples.
|
||||
# IRSA: the annotation is the whole link between the pod and the IAM role. The application sets no AWS key.
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: spring-ai
|
||||
namespace: ai
|
||||
annotations:
|
||||
eks.amazonaws.com/role-arn: arn:aws:iam::111122223333:role/spring-ai-bedrock
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: spring-ai
|
||||
namespace: ai
|
||||
spec:
|
||||
replicas: 2
|
||||
selector:
|
||||
matchLabels: { app: spring-ai }
|
||||
template:
|
||||
metadata:
|
||||
labels: { app: spring-ai }
|
||||
spec:
|
||||
serviceAccountName: spring-ai
|
||||
containers:
|
||||
- name: app
|
||||
image: registry.example.com/spring-ai-cloud-providers:1.0.0
|
||||
env:
|
||||
- name: SPRING_PROFILES_ACTIVE
|
||||
value: bedrock
|
||||
# IRSA's webhook injects AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE (confirmed in AWS's docs); check with
|
||||
# `kubectl describe pod` whether AWS_REGION is there too. Spring AI ignores AWS_REGION for Bedrock
|
||||
# (output/02-bedrock-region-trap.txt), so set the region property explicitly:
|
||||
- name: SPRING_AI_BEDROCK_AWS_REGION
|
||||
value: us-east-1
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# NOT RUN against a real account. Names and ids are examples. EKS Pod Identity instead of IRSA: no OIDC provider,
|
||||
# and the pod receives AWS_CONTAINER_CREDENTIALS_FULL_URI (see output/06-bedrock-pod-identity.txt for that path).
|
||||
set -euo pipefail
|
||||
aws iam create-role --role-name spring-ai-bedrock \
|
||||
--assume-role-policy-document file://deploy/pod-identity-trust-policy.json
|
||||
aws iam put-role-policy --role-name spring-ai-bedrock --policy-name invoke-one-model \
|
||||
--policy-document file://deploy/bedrock-invoke-policy.json
|
||||
aws eks create-pod-identity-association --cluster-name my-cluster --namespace ai \
|
||||
--service-account spring-ai --role-arn arn:aws:iam::111122223333:role/spring-ai-bedrock
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"Federated": "arn:aws:iam::111122223333:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE"
|
||||
},
|
||||
"Action": "sts:AssumeRoleWithWebIdentity",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:aud": "sts.amazonaws.com",
|
||||
"oidc.eks.us-east-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:sub": "system:serviceaccount:ai:spring-ai"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "AllowEksAuthToAssumeRoleForPodIdentity",
|
||||
"Effect": "Allow",
|
||||
"Principal": { "Service": "pods.eks.amazonaws.com" },
|
||||
"Action": [ "sts:AssumeRole", "sts:TagSession" ]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# What happened to spring-ai-starter-model-azure-openai?
|
||||
|
||||
A. Versions on Maven Central (maven-metadata.xml)
|
||||
spring-ai-starter-model-azure-openai newest listed version=2.0.0-M4
|
||||
spring-ai-starter-model-openai newest listed version=2.1.0
|
||||
spring-ai-starter-model-bedrock-converse newest listed version=2.1.0
|
||||
|
||||
B. Does the Spring AI 2.1.0 BOM manage the Azure starter?
|
||||
spring-ai-starter-model-azure-openai NOT managed
|
||||
spring-ai-azure-openai NOT managed
|
||||
spring-ai-starter-model-openai managed
|
||||
spring-ai-starter-model-bedrock-converse managed
|
||||
|
||||
C. Maven asked to resolve the Azure starter with no version under that BOM
|
||||
'dependencies.dependency.version' for org.springframework.ai:spring-ai-starter-model-azure-openai:jar is missing. @ line 4, column 27
|
||||
@@ -0,0 +1,23 @@
|
||||
# Bedrock with IRSA: no key in the application, the default chain finds the projected token
|
||||
|
||||
Environment the pod gets (the only configuration the application receives):
|
||||
AWS_ROLE_ARN = arn:aws:iam::111122223333:role/spring-ai-bedrock
|
||||
AWS_WEB_IDENTITY_TOKEN_FILE = <projected service account token>
|
||||
(AWS_ENDPOINT_URL_* point at the local stub; on EKS they are absent)
|
||||
spring.ai.bedrock.aws.access-key / secret-key / session-token: not set
|
||||
|
||||
Application output:
|
||||
INFO audit - provider=bedrock principal=arn:aws:sts::111122223333:assumed-role/spring-ai-bedrock/pod-session model=us.anthropic.claude-sonnet-4-5-20250929-v1:0 outcome=OK inputTokens=12 outputTokens=7 ms=<n>
|
||||
ANSWER 1: Hello from the Bedrock stub.
|
||||
|
||||
STS received 1 AssumeRoleWithWebIdentity call(s) (1 GetCallerIdentity for the audit identity)
|
||||
Authorization header on AssumeRoleWithWebIdentity: null (this call is not signed)
|
||||
RoleArn = arn:aws:iam::111122223333:role/spring-ai-bedrock
|
||||
RoleSessionName starts with = aws-sdk-java-
|
||||
WebIdentityToken equals the token file content: true
|
||||
|
||||
Bedrock received POST /model/us.anthropic.claude-sonnet-4-5-20250929-v1:0/converse
|
||||
signed by access key id : ASIASTUB0000... (temporary: starts with ASIA)
|
||||
signing service / region: bedrock / us-east-1
|
||||
x-amz-security-token signed: true
|
||||
X-Amz-Security-Token header present: true
|
||||
@@ -0,0 +1,8 @@
|
||||
# Region: AWS_REGION=eu-west-1 is set, which region does Spring AI sign for?
|
||||
|
||||
AWS_REGION=eu-west-1 in the environment in all four runs.
|
||||
|
||||
nothing else set -> Bedrock request signed for region us-east-1
|
||||
spring.ai.bedrock.aws.region=${AWS_REGION} -> Bedrock request signed for region eu-west-1
|
||||
spring.ai.bedrock.aws.region=eu-west-1 -> Bedrock request signed for region eu-west-1
|
||||
own AwsRegionProvider bean (DefaultAwsRegionProviderChain) -> Bedrock request signed for region eu-west-1
|
||||
@@ -0,0 +1,7 @@
|
||||
# Precedence: IRSA is configured, and a static key is also present somewhere
|
||||
|
||||
IRSA variables are set in all three runs. What signs the Bedrock request?
|
||||
|
||||
nothing else -> ASIASTUB0000001 AssumeRoleWithWebIdentity calls: 1
|
||||
AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY set -> AKIALEFTOVERENVKEY1 AssumeRoleWithWebIdentity calls: 0
|
||||
spring.ai.bedrock.aws.access-key/secret-key -> AKIALEFTOVERPROPKEY AssumeRoleWithWebIdentity calls: 0
|
||||
@@ -0,0 +1,8 @@
|
||||
# Bedrock with no credential source at all (a laptop, or a pod whose service account is not annotated)
|
||||
|
||||
Environment: AWS_EC2_METADATA_DISABLED=true, nothing else.
|
||||
|
||||
WARN audit - provider=bedrock principal=unresolved model=us.anthropic.claude-sonnet-4-5-20250929-v1:0 outcome=FAILED error=SdkClientException ms=<n>
|
||||
FAILED 1: SdkClientException / root cause SdkClientException: Unable to load credentials from any of the providers in the chain AwsCredentialsProviderChain(credentialsProviders=[SystemPropertyCredentialsProvider(), EnvironmentVariableCredentialsProvider(), WebIdentityTokenFileCredentialsProvider(), ProfileCredentialsProvider(profileName=default, profileFile=ProfileFile(sections=[])), ContainerCredentialsProvider(), InstanceProfileCredentialsProvider()]) : [SystemPropertyCredentialsProvider(): Unable to load credentials from system settings. Access key must be specified either via environment variable (AWS_ACCESS_KEY_ID) or system property (aws.accessKeyId)., EnvironmentVariableCredentialsProvider(): Unable to load credentials from system settings. Access key must be specified either via environment variable (AWS_ACCESS_KEY_ID) or system property (aws.accessKeyId)., WebIdentityTokenFileCredentialsProvider(): Either the environment variable AWS_WEB_IDENTITY_TOKEN_FILE or the javaproperty aws.webIdentityTokenFile must be set., ProfileCredentialsProvider(profileName=default, profileFile=ProfileFile(sections=[])): Profile file contained no credentials for profile 'default': ProfileFile(sections=[]), ContainerCredentialsProvider(): Cannot fetch credentials from container - neither AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variables are set., InstanceProfileCredentialsProvider(): IMDS credentials have been disabled by environment variable or system property.]
|
||||
|
||||
Requests that reached the Bedrock stub: 0
|
||||
@@ -0,0 +1,6 @@
|
||||
# How often does the SDK go back to STS? Five Bedrock calls, three credential lifetimes
|
||||
|
||||
STS credential lifetime AssumeRoleWithWebIdentity distinct access key ids on Bedrock calls
|
||||
3600 s 1 1 (of 5 calls)
|
||||
300 s 1 1 (of 5 calls)
|
||||
30 s 6 5 (of 5 calls)
|
||||
@@ -0,0 +1,10 @@
|
||||
# EKS Pod Identity: same application, a different environment, nothing changed in the code
|
||||
|
||||
Environment: AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE (what the Pod Identity webhook injects)
|
||||
no AWS_ROLE_ARN, no AWS_WEB_IDENTITY_TOKEN_FILE
|
||||
|
||||
ANSWER 1: Hello from the Bedrock stub.
|
||||
Credentials endpoint calls : 1
|
||||
Authorization header equals the token file : true
|
||||
AssumeRoleWithWebIdentity calls : 0
|
||||
Bedrock request signed by : ASIAPODID000...
|
||||
@@ -0,0 +1,26 @@
|
||||
# Azure OpenAI with a managed identity: no api-key, a bearer token from the identity endpoint
|
||||
|
||||
Environment: IDENTITY_ENDPOINT and IDENTITY_HEADER (what App Service injects), no AZURE_CLIENT_SECRET, no api-key.
|
||||
|
||||
profile azure (exit 0)
|
||||
INFO audit - provider=azure principal=oid=00000000-0000-0000-0000-00000000a11c,tid=11111111-2222-3333-4444-555555555555 model=gpt-4o-mini outcome=OK inputTokens=11 outputTokens=6 ms=<n>
|
||||
ANSWER 1: Hello from the Azure stub.
|
||||
identity endpoint calls : 1
|
||||
identity request query : api-version=2019-08-01&resource=https://cognitiveservices.azure.com
|
||||
chat request path : POST /openai/v1/chat/completions
|
||||
Authorization : Bearer eyJhbG... (3 segments, 262 chars)
|
||||
token claim aud : https://cognitiveservices.azure.com
|
||||
request body model : gpt-4o-mini
|
||||
api-key header : null
|
||||
|
||||
profile azure-default (exit 0)
|
||||
INFO audit - provider=azure principal=DefaultAzureCredential(unresolved) model=gpt-4o-mini outcome=OK inputTokens=11 outputTokens=6 ms=<n>
|
||||
ANSWER 1: Hello from the Azure stub.
|
||||
identity endpoint calls : 1
|
||||
identity request query : api-version=2019-08-01&resource=https://cognitiveservices.azure.com
|
||||
chat request path : POST /openai/v1/chat/completions
|
||||
Authorization : Bearer eyJhbG... (3 segments, 262 chars)
|
||||
token claim aud : https://cognitiveservices.azure.com
|
||||
request body model : gpt-4o-mini
|
||||
api-key header : null
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# Entra ID is configured, and OPENAI_API_KEY is also in the environment
|
||||
|
||||
profile azure-default, identity endpoint available, OPENAI_API_KEY=<leftover> set (exit 0)
|
||||
INFO audit - provider=azure principal=DefaultAzureCredential(unresolved) model=gpt-4o-mini outcome=OK inputTokens=11 outputTokens=6 ms=<n>
|
||||
ANSWER 1: Hello from the Azure stub.
|
||||
identity endpoint calls : 0
|
||||
api-key header : <leftover value, sent as is>
|
||||
Authorization header : null
|
||||
@@ -0,0 +1,6 @@
|
||||
# How often is the identity endpoint called? Five chat calls, three token lifetimes
|
||||
|
||||
token lifetime profile azure profile azure-default
|
||||
3600 s 1 identity calls 1 identity calls
|
||||
600 s 1 identity calls 1 identity calls
|
||||
240 s 11 identity calls 10 identity calls
|
||||
@@ -0,0 +1,7 @@
|
||||
# profile azure-default with azure-identity removed from the classpath
|
||||
|
||||
Classpath: the application's own classpath minus azure-identity-*.jar.
|
||||
|
||||
Microsoft Foundry was detected, but no credential was provided. If you want to use passwordless authentication, you need to add the Azure Identity library (groupId=`com.azure`, artifactId=`azure-identity`)
|
||||
|
||||
exit code: 1, identity endpoint calls: 0, chat calls: 0
|
||||
@@ -0,0 +1,8 @@
|
||||
# Managed identity not usable: the identity endpoint refuses the request
|
||||
|
||||
Environment: IDENTITY_HEADER does not match what the endpoint expects.
|
||||
|
||||
WARN audit - provider=azure principal=unresolved model=gpt-4o-mini outcome=FAILED error=ClientAuthenticationException ms=<n>
|
||||
FAILED 1: ClientAuthenticationException / root cause MsalServiceException: [Managed Identity] Error Code: bad identity header Error Message: null
|
||||
|
||||
identity endpoint calls: 2, chat calls that reached the stub: 0
|
||||
@@ -0,0 +1,7 @@
|
||||
# Only chat is used, but the OpenAI starter is on the classpath: what starts?
|
||||
|
||||
profile bedrock, spring.ai.model.chat=bedrock-converse, no OpenAI key.
|
||||
|
||||
with spring.ai.model.audio.speech=none (this module's setting): exit 0
|
||||
with spring.ai.model.audio.speech unset (the default, here set to its default value openai): exit 1
|
||||
Error creating bean with name 'openAiSdkAudioSpeechModel' defined in class path resource [org/springframework/ai/model/openai/autoconfigure/OpenAiAudioSpeechAutoConfiguration.class]: Failed to instantiate [org.springframework.ai.openai.OpenAiAudioSpeechModel]: Factory method 'openAiSdkAudioSpeechModel' threw exception with message: At least one credential source must be specified: credential (apiKey), workloadIdentity, or adminApiKey
|
||||
@@ -0,0 +1,25 @@
|
||||
# Audit lines, and a search of the whole log for every secret the run handled
|
||||
|
||||
Audit lines from the Bedrock run (two calls, default log levels):
|
||||
INFO audit - provider=bedrock principal=arn:aws:sts::111122223333:assumed-role/spring-ai-bedrock/pod-session model=us.anthropic.claude-sonnet-4-5-20250929-v1:0 outcome=OK inputTokens=12 outputTokens=7 ms=<n>
|
||||
INFO audit - provider=bedrock principal=arn:aws:sts::111122223333:assumed-role/spring-ai-bedrock/pod-session model=us.anthropic.claude-sonnet-4-5-20250929-v1:0 outcome=OK inputTokens=12 outputTokens=7 ms=<n>
|
||||
Audit lines from the Azure run (two calls, DEBUG on com.azure, MSAL, okhttp, Spring AI):
|
||||
INFO audit - provider=azure principal=oid=00000000-0000-0000-0000-00000000a11c,tid=11111111-2222-3333-4444-555555555555 model=gpt-4o-mini outcome=OK inputTokens=11 outputTokens=6 ms=<n>
|
||||
INFO audit - provider=azure principal=oid=00000000-0000-0000-0000-00000000a11c,tid=11111111-2222-3333-4444-555555555555 model=gpt-4o-mini outcome=OK inputTokens=11 outputTokens=6 ms=<n>
|
||||
|
||||
Searched each whole log for every secret the run handled:
|
||||
|
||||
Bedrock, default levels Bedrock, DEBUG on awssdk + Spring AI Azure, DEBUG
|
||||
STS secret access key not found not found -
|
||||
STS session token not found FOUND -
|
||||
Web identity token (projected) not found not found -
|
||||
Azure access token (JWT) - - not found
|
||||
Azure token payload segment - - not found
|
||||
IDENTITY_HEADER value - - not found
|
||||
Prompt text not found not found not found
|
||||
|
||||
Log size: Bedrock default 9 lines, Bedrock DEBUG 273 lines, Azure DEBUG 49 lines
|
||||
The session token in the DEBUG log comes from the SigV4 signer's canonical request:
|
||||
DEBUG DefaultV4RequestSigner - AWS4 Canonical Request: POST
|
||||
...
|
||||
x-amz-security-token:stub-session-token-1
|
||||
@@ -0,0 +1,74 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.2.0</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.ankurm</groupId>
|
||||
<artifactId>cloud-providers</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>cloud-providers</name>
|
||||
<description>Keyless Spring AI on Amazon Bedrock (IAM role, IRSA) and Azure OpenAI (Microsoft Entra ID managed identity), verified against local stubs.</description>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<spring-ai.version>2.1.0</spring-ai.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-bom</artifactId>
|
||||
<version>${spring-ai.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-starter-model-bedrock-converse</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-starter-model-openai</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.azure</groupId>
|
||||
<artifactId>azure-identity</artifactId>
|
||||
<version>1.19.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<useManifestOnlyJar>false</useManifestOnlyJar>
|
||||
<argLine>-Duser.timezone=UTC -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bash
|
||||
# Shows what happened to the dedicated Azure OpenAI starter: it is not managed by the Spring AI 2.1.0 BOM, and the
|
||||
# newest version on Maven Central is a 2.0 milestone. Needs network access to Maven Central. Writes output/00-*.txt.
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
out=output/00-azure-starter.txt
|
||||
tmp=$(mktemp -d)
|
||||
mkdir -p output
|
||||
|
||||
# Maven Central answers 429 when polled quickly; retry, and refuse to write a transcript from an empty answer.
|
||||
fetch() {
|
||||
local r
|
||||
for _ in 1 2 3 4 5 6 7 8; do
|
||||
if r=$(curl -sf "$1") && [ -n "$r" ]; then printf '%s' "$r"; return 0; fi
|
||||
sleep 10
|
||||
done
|
||||
echo "could not fetch $1" >&2; return 1
|
||||
}
|
||||
declare -A meta
|
||||
for a in spring-ai-starter-model-azure-openai spring-ai-starter-model-openai spring-ai-starter-model-bedrock-converse; do
|
||||
meta[$a]=$(fetch "https://repo1.maven.org/maven2/org/springframework/ai/$a/maven-metadata.xml") || exit 1
|
||||
sleep 3
|
||||
done
|
||||
bom=$(fetch https://repo1.maven.org/maven2/org/springframework/ai/spring-ai-bom/2.1.0/spring-ai-bom-2.1.0.pom) || exit 1
|
||||
{
|
||||
echo "# What happened to spring-ai-starter-model-azure-openai?"
|
||||
echo
|
||||
echo "A. Versions on Maven Central (maven-metadata.xml)"
|
||||
for a in spring-ai-starter-model-azure-openai spring-ai-starter-model-openai spring-ai-starter-model-bedrock-converse; do
|
||||
xml=${meta[$a]}
|
||||
printf ' %-45s newest listed version=%s\n' "$a" "$(grep -o '<version>[^<]*' <<<"$xml" | tail -1 | sed 's/<version>//')"
|
||||
done
|
||||
echo
|
||||
echo "B. Does the Spring AI 2.1.0 BOM manage the Azure starter?"
|
||||
for a in spring-ai-starter-model-azure-openai spring-ai-azure-openai spring-ai-starter-model-openai spring-ai-starter-model-bedrock-converse; do
|
||||
if grep -q "<artifactId>$a</artifactId>" <<<"$bom"; then r=managed; else r="NOT managed"; fi
|
||||
printf ' %-45s %s\n' "$a" "$r"
|
||||
done
|
||||
echo
|
||||
echo "C. Maven asked to resolve the Azure starter with no version under that BOM"
|
||||
cat > "$tmp/pom.xml" <<POM
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"><modelVersion>4.0.0</modelVersion>
|
||||
<groupId>x</groupId><artifactId>x</artifactId><version>1</version>
|
||||
<dependencyManagement><dependencies><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bom</artifactId><version>2.1.0</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
|
||||
<dependencies><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-model-azure-openai</artifactId></dependency></dependencies>
|
||||
</project>
|
||||
POM
|
||||
(cd "$tmp" && mvn -B -q validate 2>&1 | grep -E "ERROR.*(version|missing)" | sort -u | head -1 | sed -E 's/^\[ERROR\] *//; s#/tmp/[^ ]*/pom.xml#pom.xml#')
|
||||
} > "$out"
|
||||
grep -q "is missing" "$out" || { echo "maven did not report the missing version" >&2; exit 1; }
|
||||
cat "$out"
|
||||
rm -rf "$tmp"
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates every file under output/. The tests write them through the Transcript helper, so each figure in a
|
||||
# transcript is also an assertion: if a number stops being true, the build fails. Each scenario starts the real
|
||||
# application in a child JVM with an exact environment, so the full run takes several minutes.
|
||||
# No cloud account and no network access to AWS or Azure is needed; scripts/azure-starter-check.sh only reads Maven Central.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
rm -rf target output
|
||||
mvn -q -B test
|
||||
./scripts/azure-starter-check.sh > /dev/null
|
||||
ls output
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.ExitCodeGenerator;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Asks one question, N times, prints the answers and exits. Used by the scripts and the child-process tests. */
|
||||
@Component
|
||||
@Profile("!unit")
|
||||
class AskRunner implements CommandLineRunner {
|
||||
|
||||
private final ChatClient chatClient;
|
||||
private final ApplicationContext context;
|
||||
private final int calls;
|
||||
private final String question;
|
||||
|
||||
AskRunner(ChatClient chatClient, ApplicationContext context, @Value("${app.calls:1}") int calls,
|
||||
@Value("${app.question:Say hello in five words.}") String question) {
|
||||
this.chatClient = chatClient;
|
||||
this.context = context;
|
||||
this.calls = calls;
|
||||
this.question = question;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) {
|
||||
int exit = 0;
|
||||
for (int i = 1; i <= calls; i++) {
|
||||
try {
|
||||
String answer = chatClient.prompt().user(question).call().content();
|
||||
System.out.println("ANSWER " + i + ": " + answer);
|
||||
}
|
||||
catch (RuntimeException ex) {
|
||||
Throwable root = ex;
|
||||
while (root.getCause() != null) {
|
||||
root = root.getCause();
|
||||
}
|
||||
System.out.println("FAILED " + i + ": " + ex.getClass().getSimpleName() + " / root cause "
|
||||
+ root.getClass().getSimpleName() + ": " + firstLine(root.getMessage()));
|
||||
exit = 1;
|
||||
}
|
||||
}
|
||||
int code = exit;
|
||||
System.exit(SpringApplication.exit(context, (ExitCodeGenerator) () -> code));
|
||||
}
|
||||
|
||||
private static String firstLine(String s) {
|
||||
return s == null ? "" : s.lines().findFirst().orElse("");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.ai.chat.client.ChatClientRequest;
|
||||
import org.springframework.ai.chat.client.ChatClientResponse;
|
||||
import org.springframework.ai.chat.client.advisor.api.CallAdvisor;
|
||||
import org.springframework.ai.chat.client.advisor.api.CallAdvisorChain;
|
||||
import org.springframework.ai.chat.metadata.Usage;
|
||||
|
||||
/**
|
||||
* One structured line per model call: who called (the cloud principal, not an API key), which provider and model,
|
||||
* how long it took, how many tokens, and whether it failed. It never logs prompt text, completions, tokens or keys.
|
||||
* The line is written to the logger named {@code audit} so it can be routed to its own appender.
|
||||
*/
|
||||
public class AuditAdvisor implements CallAdvisor {
|
||||
|
||||
private static final Logger AUDIT = LoggerFactory.getLogger("audit");
|
||||
|
||||
private final String provider;
|
||||
private final String configuredModel;
|
||||
private final Supplier<String> principal;
|
||||
|
||||
public AuditAdvisor(String provider, String configuredModel, Supplier<String> principal) {
|
||||
this.provider = provider;
|
||||
this.configuredModel = configuredModel;
|
||||
this.principal = principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
|
||||
long start = System.nanoTime();
|
||||
String who = resolvePrincipal();
|
||||
try {
|
||||
ChatClientResponse response = chain.nextCall(request);
|
||||
var chatResponse = response.chatResponse();
|
||||
String model = chatResponse != null && !chatResponse.getMetadata().getModel().isBlank()
|
||||
? chatResponse.getMetadata().getModel() : configuredModel;
|
||||
Usage usage = chatResponse != null ? chatResponse.getMetadata().getUsage() : null;
|
||||
AUDIT.info("provider={} principal={} model={} outcome=OK inputTokens={} outputTokens={} ms={}",
|
||||
provider, who, model,
|
||||
usage != null ? usage.getPromptTokens() : null,
|
||||
usage != null ? usage.getCompletionTokens() : null,
|
||||
(System.nanoTime() - start) / 1_000_000);
|
||||
return response;
|
||||
}
|
||||
catch (RuntimeException ex) {
|
||||
AUDIT.warn("provider={} principal={} model={} outcome=FAILED error={} ms={}",
|
||||
provider, who, configuredModel, ex.getClass().getSimpleName(),
|
||||
(System.nanoTime() - start) / 1_000_000);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/** A failed identity lookup must not hide the call from the audit log, so it becomes "unresolved". */
|
||||
private String resolvePrincipal() {
|
||||
try {
|
||||
return principal.get();
|
||||
}
|
||||
catch (RuntimeException ex) {
|
||||
return "unresolved";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "auditAdvisor";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import com.azure.core.credential.AccessToken;
|
||||
import com.azure.core.credential.TokenCredential;
|
||||
import com.azure.core.credential.TokenRequestContext;
|
||||
import com.azure.identity.ManagedIdentityCredentialBuilder;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import org.springframework.ai.openai.OpenAiChatModel;
|
||||
import org.springframework.ai.openai.OpenAiChatOptions;
|
||||
import org.springframework.ai.openai.setup.AzureOpenAiCredentials;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.util.StringUtils;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* The explicit Azure setup: a managed identity credential we choose (system-assigned, or user-assigned when
|
||||
* {@code app.azure.client-id} is set) instead of letting DefaultAzureCredential probe a chain.
|
||||
*/
|
||||
@Configuration
|
||||
@Profile("azure")
|
||||
class AzureConfig {
|
||||
|
||||
static final String SCOPE = "https://cognitiveservices.azure.com/.default";
|
||||
|
||||
@Bean
|
||||
TokenCredential azureCredential(@Value("${app.azure.client-id:}") String clientId) {
|
||||
var builder = new ManagedIdentityCredentialBuilder();
|
||||
if (StringUtils.hasText(clientId)) {
|
||||
builder.clientId(clientId);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
OpenAiChatModel openAiChatModel(TokenCredential credential, @Value("${spring.ai.openai.base-url}") String baseUrl,
|
||||
@Value("${spring.ai.openai.chat.options.deployment-name}") String deployment) {
|
||||
OpenAiChatOptions options = OpenAiChatOptions.builder()
|
||||
.microsoftFoundry(true)
|
||||
.baseUrl(baseUrl)
|
||||
.deploymentName(deployment)
|
||||
.model(deployment)
|
||||
.credential(AzureOpenAiCredentials.from(credential))
|
||||
.build();
|
||||
return OpenAiChatModel.builder().options(options).build();
|
||||
}
|
||||
|
||||
/** Audit identity: the object id (oid) and tenant (tid) claims of the token the credential issues. */
|
||||
@Bean
|
||||
Supplier<String> principalSupplier(TokenCredential credential) {
|
||||
return new Supplier<>() {
|
||||
private volatile String who;
|
||||
|
||||
@Override
|
||||
public String get() {
|
||||
if (who == null) {
|
||||
AccessToken token = credential.getTokenSync(new TokenRequestContext().addScopes(SCOPE));
|
||||
who = describe(token.getToken());
|
||||
}
|
||||
return who;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads claims for labelling only. Nothing is trusted or validated here: Azure validates the token. */
|
||||
static String describe(String jwt) {
|
||||
String[] parts = jwt.split("\\.");
|
||||
if (parts.length < 2) {
|
||||
return "unknown";
|
||||
}
|
||||
JsonNode claims = JsonMapper.shared().readTree(Base64.getUrlDecoder().decode(parts[1]));
|
||||
return "oid=" + claims.path("oid").asString("?") + ",tid=" + claims.path("tid").asString("?");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
/** Properties-only Azure: Spring AI builds DefaultAzureCredential itself, so we cannot see the principal. */
|
||||
@Configuration
|
||||
@Profile("azure-default")
|
||||
class AzureDefaultConfig {
|
||||
|
||||
@Bean
|
||||
Supplier<String> principalSupplier() {
|
||||
return () -> "DefaultAzureCredential(unresolved)";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.providers.AwsRegionProvider;
|
||||
import software.amazon.awssdk.services.sts.StsClient;
|
||||
|
||||
/**
|
||||
* Bedrock needs no credential code at all: Spring AI's auto-configuration builds the AWS default credentials
|
||||
* provider chain. This class only adds the audit identity, by asking STS who the chain currently resolves to.
|
||||
*/
|
||||
@Configuration
|
||||
@Profile("bedrock")
|
||||
class BedrockConfig {
|
||||
|
||||
@Bean
|
||||
StsClient stsClient(AwsCredentialsProvider credentialsProvider, AwsRegionProvider regionProvider) {
|
||||
return StsClient.builder().credentialsProvider(credentialsProvider).region(regionProvider.getRegion()).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
Supplier<String> principalSupplier(StsClient sts) {
|
||||
return new Supplier<>() {
|
||||
private volatile String arn;
|
||||
|
||||
@Override
|
||||
public String get() {
|
||||
if (arn == null) {
|
||||
arn = sts.getCallerIdentity().arn();
|
||||
}
|
||||
return arn;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
import software.amazon.awssdk.regions.providers.AwsRegionProvider;
|
||||
import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain;
|
||||
|
||||
/**
|
||||
* Makes Bedrock honour AWS_REGION. Spring AI's own {@code AwsRegionProvider} bean is {@code @ConditionalOnMissingBean}
|
||||
* and its region property defaults to us-east-1, so without this bean the environment variable is never read.
|
||||
*/
|
||||
@Configuration
|
||||
@Profile("bedrock-region-env")
|
||||
class BedrockRegionFromEnvConfig {
|
||||
|
||||
@Bean
|
||||
AwsRegionProvider regionProvider() {
|
||||
return DefaultAwsRegionProviderChain.builder().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/** One ChatClient for whichever cloud the active profile configured, wrapped in the audit advisor. */
|
||||
@Configuration
|
||||
class ChatClientConfig {
|
||||
|
||||
@Bean
|
||||
ChatClient chatClient(ChatModel chatModel, @Value("${app.provider}") String provider,
|
||||
@Value("${app.model}") String model,
|
||||
Supplier<String> principalSupplier) {
|
||||
return ChatClient.builder(chatModel).defaultAdvisors(new AuditAdvisor(provider, model, principalSupplier)).build();
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* Entry point. Pick the cloud with a profile: {@code bedrock}, {@code azure} (explicit managed identity
|
||||
* credential) or {@code azure-default} (properties only, DefaultAzureCredential).
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class CloudProvidersApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CloudProvidersApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
app.provider=azure
|
||||
spring.ai.model.chat=openai
|
||||
spring.ai.openai.microsoft-foundry=true
|
||||
spring.ai.openai.base-url=${AZURE_OPENAI_ENDPOINT:https://my-resource.openai.azure.com/openai/v1}
|
||||
spring.ai.openai.chat.options.deployment-name=${AZURE_OPENAI_DEPLOYMENT:gpt-4o-mini}
|
||||
spring.ai.openai.chat.options.model=${AZURE_OPENAI_DEPLOYMENT:gpt-4o-mini}
|
||||
# No api-key and no credential: azure-identity on the classpath makes Spring AI use DefaultAzureCredential.
|
||||
app.model=${spring.ai.openai.chat.options.deployment-name}
|
||||
@@ -0,0 +1,6 @@
|
||||
app.provider=azure
|
||||
spring.ai.model.chat=openai
|
||||
spring.ai.openai.base-url=${AZURE_OPENAI_ENDPOINT:https://my-resource.openai.azure.com/openai/v1}
|
||||
spring.ai.openai.chat.options.deployment-name=${AZURE_OPENAI_DEPLOYMENT:gpt-4o-mini}
|
||||
# No spring.ai.openai.api-key: AzureConfig supplies a managed-identity credential.
|
||||
app.model=${spring.ai.openai.chat.options.deployment-name}
|
||||
@@ -0,0 +1,6 @@
|
||||
app.provider=bedrock
|
||||
spring.ai.model.chat=bedrock-converse
|
||||
# Example model id; not validated against a real account (see the README).
|
||||
spring.ai.bedrock.converse.chat.options.model=us.anthropic.claude-sonnet-4-5-20250929-v1:0
|
||||
# No access-key / secret-key / session-token anywhere: the default credentials provider chain supplies them.
|
||||
app.model=${spring.ai.bedrock.converse.chat.options.model}
|
||||
@@ -0,0 +1,13 @@
|
||||
spring.main.web-application-type=none
|
||||
spring.main.banner-mode=off
|
||||
logging.level.root=WARN
|
||||
logging.level.audit=INFO
|
||||
logging.pattern.console=%d{HH:mm:ss.SSS} %-5level %logger{0} - %msg%n
|
||||
# Every other modality defaults to the OpenAI model beans and fails at startup without an OpenAI key.
|
||||
# We only use chat, so switch the rest off (see output/07-startup-trap.txt for the failure).
|
||||
spring.ai.model.audio.speech=none
|
||||
spring.ai.model.audio.transcription=none
|
||||
spring.ai.model.decision=none
|
||||
spring.ai.model.embedding=none
|
||||
spring.ai.model.image=none
|
||||
spring.ai.model.moderation=none
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.cloudproviders.support.AppProcess;
|
||||
import com.ankurm.cloudproviders.support.LocalCloud;
|
||||
import com.ankurm.cloudproviders.support.Transcript;
|
||||
import com.ankurm.cloudproviders.support.Wire;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Azure OpenAI keyless auth through a managed identity, against the local stub. */
|
||||
class AzureTest {
|
||||
|
||||
/** The environment an App Service or Container Apps container gets, pointed at the stub. */
|
||||
static AppProcess managedIdentity(String profile, LocalCloud cloud) {
|
||||
return AppProcess.profile(profile)
|
||||
.env("IDENTITY_ENDPOINT", cloud.url() + "/msi/token")
|
||||
.env("IDENTITY_HEADER", LocalCloud.IDENTITY_HEADER)
|
||||
.env("AZURE_OPENAI_ENDPOINT", cloud.url() + "/openai/v1");
|
||||
}
|
||||
|
||||
private static String redacted(String jwt) {
|
||||
return jwt.substring(0, 6) + "..." + " (" + jwt.split("\\.").length + " segments, " + jwt.length() + " chars)";
|
||||
}
|
||||
|
||||
@Test
|
||||
void bothProfilesSendABearerTokenAndNoApiKey() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("07-azure-managed-identity.txt",
|
||||
"Azure OpenAI with a managed identity: no api-key, a bearer token from the identity endpoint")) {
|
||||
t.line("Environment: IDENTITY_ENDPOINT and IDENTITY_HEADER (what App Service injects), no AZURE_CLIENT_SECRET, no api-key.").blank();
|
||||
for (String profile : new String[] {"azure", "azure-default"}) {
|
||||
cloud.reset();
|
||||
var r = managedIdentity(profile, cloud).run();
|
||||
var msi = cloud.seen("msi");
|
||||
var chat = cloud.seen("azure-openai").getFirst();
|
||||
String jwt = Wire.bearer(chat);
|
||||
var claims = Wire.jwtClaims(jwt);
|
||||
t.line("profile %s (exit %d)", profile, r.exit());
|
||||
r.output().lines().filter(l -> l.contains("audit") || l.startsWith("ANSWER"))
|
||||
.forEach(l -> t.line(" %s", l.replaceAll("ms=\\d+", "ms=<n>").replaceFirst("^\\d\\d:\\d\\d:\\d\\d\\.\\d+ ", "")));
|
||||
t.line(" identity endpoint calls : %d", msi.size());
|
||||
t.line(" identity request query : %s", msi.getFirst().query().replace("%3A", ":").replace("%2F", "/"));
|
||||
t.line(" chat request path : POST %s", chat.path());
|
||||
t.line(" Authorization : Bearer %s", redacted(jwt));
|
||||
t.line(" token claim aud : %s", claims.path("aud").asString());
|
||||
t.line(" request body model : %s", tools.jackson.databind.json.JsonMapper.shared().readTree(chat.body()).path("model").asString());
|
||||
t.line(" api-key header : %s", chat.header("api-key"));
|
||||
t.blank();
|
||||
assertThat(r.exit()).isZero();
|
||||
assertThat(msi.getFirst().query()).contains("resource=https%3A%2F%2Fcognitiveservices.azure.com");
|
||||
assertThat(chat.header("api-key")).isNull();
|
||||
assertThat(jwt.split("\\.")).hasSize(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLeftoverApiKeyEnvironmentVariableTurnsEntraOff() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("07b-azure-leftover-api-key.txt",
|
||||
"Entra ID is configured, and OPENAI_API_KEY is also in the environment")) {
|
||||
var r = managedIdentity("azure-default", cloud).env("OPENAI_API_KEY", "sk-leftover-key-0000").run();
|
||||
var chat = cloud.seen("azure-openai").getFirst();
|
||||
t.line("profile azure-default, identity endpoint available, OPENAI_API_KEY=<leftover> set (exit %d)", r.exit());
|
||||
r.output().lines().filter(l -> l.contains("audit") || l.startsWith("ANSWER"))
|
||||
.forEach(l -> t.line(" %s", l.replaceAll("ms=\\d+", "ms=<n>").replaceFirst("^\\d\\d:\\d\\d:\\d\\d\\.\\d+ ", "")));
|
||||
t.line(" identity endpoint calls : %d", cloud.seen("msi").size());
|
||||
t.line(" api-key header : %s", chat.header("api-key") == null ? "null" : "<leftover value, sent as is>");
|
||||
t.line(" Authorization header : %s", chat.header("authorization"));
|
||||
assertThat(r.exit()).isZero();
|
||||
assertThat(cloud.seen("msi")).isEmpty();
|
||||
assertThat(chat.header("api-key")).isEqualTo("sk-leftover-key-0000");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shortLivedTokensAreFetchedAgainOnEveryCall() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("08-azure-token-refresh.txt",
|
||||
"How often is the identity endpoint called? Five chat calls, three token lifetimes")) {
|
||||
t.line("%-16s %-26s %s", "token lifetime", "profile azure", "profile azure-default");
|
||||
for (int ttl : new int[] {3600, 600, 240}) {
|
||||
String[] counts = new String[2];
|
||||
int i = 0;
|
||||
for (String profile : new String[] {"azure", "azure-default"}) {
|
||||
cloud.reset();
|
||||
cloud.msiTtlSeconds = ttl;
|
||||
var r = managedIdentity(profile, cloud).arg("--app.calls=5").run();
|
||||
assertThat(r.exit()).isZero();
|
||||
assertThat(cloud.seen("azure-openai")).hasSize(5);
|
||||
counts[i++] = cloud.seen("msi").size() + " identity calls";
|
||||
}
|
||||
t.line("%-16s %-26s %s", ttl + " s", counts[0], counts[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutAzureIdentityOnTheClasspathItFailsFast() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("09-azure-without-azure-identity.txt",
|
||||
"profile azure-default with azure-identity removed from the classpath")) {
|
||||
var r = managedIdentity("azure-default", cloud).classpathWithout("azure-identity").run();
|
||||
t.line("Classpath: the application's own classpath minus azure-identity-*.jar.").blank();
|
||||
r.output().lines().filter(l -> l.contains("Microsoft Foundry was detected")).limit(1)
|
||||
.forEach(l -> t.line("%s", l.substring(l.indexOf("Microsoft Foundry was detected")).replaceAll("^(.*?\\)).*$", "$1")));
|
||||
t.blank();
|
||||
t.line("exit code: %d, identity endpoint calls: %d, chat calls: %d", r.exit(), cloud.seen("msi").size(),
|
||||
cloud.seen("azure-openai").size());
|
||||
assertThat(r.exit()).isNotZero();
|
||||
assertThat(r.output()).contains("Microsoft Foundry was detected, but no credential was provided");
|
||||
assertThat(cloud.seen("azure-openai")).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWrongIdentityHeaderSurfacesAsAFailedCallThatIsAudited() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("10-azure-identity-failure.txt",
|
||||
"Managed identity not usable: the identity endpoint refuses the request")) {
|
||||
var r = managedIdentity("azure", cloud).env("IDENTITY_HEADER", "wrong-value").run();
|
||||
t.line("Environment: IDENTITY_HEADER does not match what the endpoint expects.").blank();
|
||||
r.output().lines().filter(l -> l.contains("audit") || l.startsWith("FAILED"))
|
||||
.forEach(l -> t.line("%s", l.replaceAll("ms=\\d+", "ms=<n>").replaceFirst("^\\d\\d:\\d\\d:\\d\\d\\.\\d+ ", "")));
|
||||
t.blank();
|
||||
t.line("identity endpoint calls: %d, chat calls that reached the stub: %d", cloud.seen("msi").size(),
|
||||
cloud.seen("azure-openai").size());
|
||||
assertThat(r.exit()).isNotZero();
|
||||
assertThat(cloud.seen("azure-openai")).isEmpty();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import com.ankurm.cloudproviders.support.AppProcess;
|
||||
import com.ankurm.cloudproviders.support.LocalCloud;
|
||||
import com.ankurm.cloudproviders.support.Transcript;
|
||||
import com.ankurm.cloudproviders.support.Wire;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Bedrock keyless auth through the AWS default credentials provider chain, against the local stub. */
|
||||
class BedrockTest {
|
||||
|
||||
/** The environment an EKS pod gets from IRSA, pointed at the stub instead of real endpoints. */
|
||||
static AppProcess irsa(LocalCloud cloud, Path tokenFile) {
|
||||
return irsa("bedrock", cloud, tokenFile);
|
||||
}
|
||||
|
||||
static AppProcess irsa(String profiles, LocalCloud cloud, Path tokenFile) {
|
||||
return AppProcess.profile(profiles)
|
||||
.env("AWS_ROLE_ARN", LocalCloud.ROLE_ARN)
|
||||
.env("AWS_WEB_IDENTITY_TOKEN_FILE", tokenFile.toString())
|
||||
.env("AWS_REGION", "us-east-1")
|
||||
.env("AWS_ENDPOINT_URL_STS", cloud.url())
|
||||
.env("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", cloud.url())
|
||||
.env("AWS_EC2_METADATA_DISABLED", "true");
|
||||
}
|
||||
|
||||
@Test
|
||||
void irsaSignsEveryCallWithRoleCredentials() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("01-bedrock-irsa.txt",
|
||||
"Bedrock with IRSA: no key in the application, the default chain finds the projected token")) {
|
||||
Path token = Wire.writeJwtFile("irsa", "system:serviceaccount:ai:spring-ai");
|
||||
var result = irsa(cloud, token).run();
|
||||
|
||||
t.line("Environment the pod gets (the only configuration the application receives):");
|
||||
t.line(" AWS_ROLE_ARN = %s", LocalCloud.ROLE_ARN);
|
||||
t.line(" AWS_WEB_IDENTITY_TOKEN_FILE = <projected service account token>");
|
||||
t.line(" (AWS_ENDPOINT_URL_* point at the local stub; on EKS they are absent)");
|
||||
t.line(" spring.ai.bedrock.aws.access-key / secret-key / session-token: not set").blank();
|
||||
t.line("Application output:");
|
||||
result.output().lines().filter(l -> l.contains("audit") || l.startsWith("ANSWER"))
|
||||
.forEach(l -> t.line(" %s", l.replaceAll("ms=\\d+", "ms=<n>").replaceFirst("^\\d\\d:\\d\\d:\\d\\d\\.\\d+ ", "")));
|
||||
t.blank();
|
||||
|
||||
var assume = cloud.seen("sts").stream()
|
||||
.filter(s -> s.body().contains("Action=AssumeRoleWithWebIdentity")).toList();
|
||||
var assumeRequest = assume.getFirst();
|
||||
t.line("STS received %d AssumeRoleWithWebIdentity call(s) (%d GetCallerIdentity for the audit identity)",
|
||||
assume.size(), Wire.stsCalls(cloud, "GetCallerIdentity"));
|
||||
t.line(" Authorization header on AssumeRoleWithWebIdentity: %s (this call is not signed)",
|
||||
assumeRequest.header("authorization"));
|
||||
t.line(" RoleArn = %s", Wire.form(assumeRequest, "RoleArn"));
|
||||
t.line(" RoleSessionName starts with = %s", Wire.form(assumeRequest, "RoleSessionName").substring(0, 13));
|
||||
t.line(" WebIdentityToken equals the token file content: %s",
|
||||
Wire.form(assumeRequest, "WebIdentityToken").equals(Files.readString(token)));
|
||||
t.blank();
|
||||
|
||||
var bedrock = cloud.seen("bedrock").getFirst();
|
||||
var sig = Wire.sigV4(bedrock);
|
||||
t.line("Bedrock received POST %s", bedrock.path());
|
||||
t.line(" signed by access key id : %s... (temporary: starts with ASIA)", sig.accessKeyId().substring(0, 12));
|
||||
t.line(" signing service / region: %s / %s", sig.service(), sig.region());
|
||||
t.line(" x-amz-security-token signed: %s", sig.signedSecurityToken());
|
||||
t.line(" X-Amz-Security-Token header present: %s", bedrock.header("x-amz-security-token") != null);
|
||||
|
||||
assertThat(result.exit()).isZero();
|
||||
assertThat(assume).hasSize(1);
|
||||
assertThat(assumeRequest.header("authorization")).isNull();
|
||||
assertThat(Wire.form(assumeRequest, "RoleArn")).isEqualTo(LocalCloud.ROLE_ARN);
|
||||
assertThat(Wire.form(assumeRequest, "WebIdentityToken")).isEqualTo(Files.readString(token));
|
||||
assertThat(sig.accessKeyId()).startsWith("ASIASTUB");
|
||||
assertThat(sig.service()).isEqualTo("bedrock");
|
||||
assertThat(sig.signedSecurityToken()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void awsRegionEnvironmentVariableIsIgnoredByDefault() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("02-bedrock-region-trap.txt",
|
||||
"Region: AWS_REGION=eu-west-1 is set, which region does Spring AI sign for?")) {
|
||||
Path token = Wire.writeJwtFile("region", "sa");
|
||||
var a = irsa(cloud, token).env("AWS_REGION", "eu-west-1").run();
|
||||
String envRegion = Wire.sigV4(cloud.seen("bedrock").getFirst()).region();
|
||||
cloud.reset();
|
||||
var b = irsa(cloud, token).env("AWS_REGION", "eu-west-1")
|
||||
.arg("--spring.ai.bedrock.aws.region=${AWS_REGION}").run();
|
||||
String propertyRegion = Wire.sigV4(cloud.seen("bedrock").getFirst()).region();
|
||||
cloud.reset();
|
||||
var c = irsa(cloud, token).env("AWS_REGION", "eu-west-1")
|
||||
.arg("--spring.ai.bedrock.aws.region=eu-west-1").run();
|
||||
String explicitRegion = Wire.sigV4(cloud.seen("bedrock").getFirst()).region();
|
||||
|
||||
cloud.reset();
|
||||
var d = irsa("bedrock,bedrock-region-env", cloud, token).env("AWS_REGION", "eu-west-1").run();
|
||||
String beanRegion = Wire.sigV4(cloud.seen("bedrock").getFirst()).region();
|
||||
|
||||
t.line("AWS_REGION=eu-west-1 in the environment in all four runs.").blank();
|
||||
t.line(" nothing else set -> Bedrock request signed for region %s", envRegion);
|
||||
t.line(" spring.ai.bedrock.aws.region=${AWS_REGION} -> Bedrock request signed for region %s", propertyRegion);
|
||||
t.line(" spring.ai.bedrock.aws.region=eu-west-1 -> Bedrock request signed for region %s", explicitRegion);
|
||||
t.line(" own AwsRegionProvider bean (DefaultAwsRegionProviderChain) -> Bedrock request signed for region %s", beanRegion);
|
||||
|
||||
assertThat(a.exit()).isZero();
|
||||
assertThat(b.exit()).isZero();
|
||||
assertThat(c.exit()).isZero();
|
||||
assertThat(envRegion).isEqualTo("us-east-1");
|
||||
assertThat(propertyRegion).isEqualTo("eu-west-1");
|
||||
assertThat(explicitRegion).isEqualTo("eu-west-1");
|
||||
assertThat(d.exit()).isZero();
|
||||
assertThat(beanRegion).isEqualTo("eu-west-1");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLeftoverKeyBeatsTheRole() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("03-bedrock-precedence.txt",
|
||||
"Precedence: IRSA is configured, and a static key is also present somewhere")) {
|
||||
Path token = Wire.writeJwtFile("prec", "sa");
|
||||
|
||||
var base = irsa(cloud, token).run();
|
||||
String viaRole = Wire.sigV4(cloud.seen("bedrock").getFirst()).accessKeyId();
|
||||
long baseAssume = Wire.stsCalls(cloud, "AssumeRoleWithWebIdentity");
|
||||
cloud.reset();
|
||||
|
||||
var env = irsa(cloud, token).env("AWS_ACCESS_KEY_ID", "AKIALEFTOVERENVKEY1")
|
||||
.env("AWS_SECRET_ACCESS_KEY", "leftover-env-secret").run();
|
||||
String viaEnv = Wire.sigV4(cloud.seen("bedrock").getFirst()).accessKeyId();
|
||||
long envAssume = Wire.stsCalls(cloud, "AssumeRoleWithWebIdentity");
|
||||
cloud.reset();
|
||||
|
||||
var prop = irsa(cloud, token).arg("--spring.ai.bedrock.aws.access-key=AKIALEFTOVERPROPKEY")
|
||||
.arg("--spring.ai.bedrock.aws.secret-key=leftover-property-secret").run();
|
||||
String viaProp = Wire.sigV4(cloud.seen("bedrock").getFirst()).accessKeyId();
|
||||
long propAssume = Wire.stsCalls(cloud, "AssumeRoleWithWebIdentity");
|
||||
|
||||
t.line("IRSA variables are set in all three runs. What signs the Bedrock request?").blank();
|
||||
t.line(" nothing else -> %-24s AssumeRoleWithWebIdentity calls: %d", viaRole, baseAssume);
|
||||
t.line(" AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY set -> %-24s AssumeRoleWithWebIdentity calls: %d", viaEnv, envAssume);
|
||||
t.line(" spring.ai.bedrock.aws.access-key/secret-key -> %-24s AssumeRoleWithWebIdentity calls: %d", viaProp, propAssume);
|
||||
|
||||
assertThat(base.exit()).isZero();
|
||||
assertThat(env.exit()).isZero();
|
||||
assertThat(prop.exit()).isZero();
|
||||
assertThat(viaRole).startsWith("ASIASTUB");
|
||||
assertThat(viaEnv).isEqualTo("AKIALEFTOVERENVKEY1");
|
||||
assertThat(viaProp).isEqualTo("AKIALEFTOVERPROPKEY");
|
||||
assertThat(baseAssume).isEqualTo(1);
|
||||
assertThat(envAssume).isZero();
|
||||
assertThat(propAssume).isZero();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noCredentialSourceFailsAndIsStillAudited() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("04-bedrock-no-credentials.txt",
|
||||
"Bedrock with no credential source at all (a laptop, or a pod whose service account is not annotated)")) {
|
||||
var r = AppProcess.profile("bedrock").env("AWS_EC2_METADATA_DISABLED", "true")
|
||||
.env("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", cloud.url()).run();
|
||||
t.line("Environment: AWS_EC2_METADATA_DISABLED=true, nothing else.").blank();
|
||||
r.output().lines().filter(l -> l.contains("audit") || l.startsWith("FAILED"))
|
||||
.forEach(l -> t.line("%s", l.replaceAll("ms=\\d+", "ms=<n>").replaceFirst("^\\d\\d:\\d\\d:\\d\\d\\.\\d+ ", "")));
|
||||
t.blank();
|
||||
t.line("Requests that reached the Bedrock stub: %d", cloud.seen("bedrock").size());
|
||||
|
||||
assertThat(r.exit()).isEqualTo(1);
|
||||
assertThat(r.output()).contains("outcome=FAILED").contains("principal=unresolved");
|
||||
assertThat(cloud.seen("bedrock")).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void temporaryCredentialsAreCachedUntilTheyAreNearExpiry() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("05-bedrock-credential-refresh.txt",
|
||||
"How often does the SDK go back to STS? Five Bedrock calls, three credential lifetimes")) {
|
||||
Path token = Wire.writeJwtFile("refresh", "sa");
|
||||
t.line("%-28s %-26s %s", "STS credential lifetime", "AssumeRoleWithWebIdentity", "distinct access key ids on Bedrock calls");
|
||||
for (int ttl : new int[] {3600, 300, 30}) {
|
||||
cloud.reset();
|
||||
cloud.stsTtlSeconds = ttl;
|
||||
var r = irsa(cloud, token).arg("--app.calls=5").run();
|
||||
long assume = Wire.stsCalls(cloud, "AssumeRoleWithWebIdentity");
|
||||
long keys = cloud.seen("bedrock").stream().map(s -> Wire.sigV4(s).accessKeyId()).distinct().count();
|
||||
t.line("%-28s %-26d %d (of %d calls)", ttl + " s", assume, keys, cloud.seen("bedrock").size());
|
||||
assertThat(r.exit()).isZero();
|
||||
assertThat(cloud.seen("bedrock")).hasSize(5);
|
||||
if (ttl == 3600) {
|
||||
assertThat(assume).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void podIdentityUsesTheContainerCredentialsEndpoint() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("06-bedrock-pod-identity.txt",
|
||||
"EKS Pod Identity: same application, a different environment, nothing changed in the code")) {
|
||||
Path token = Wire.writeJwtFile("podid", "pod-identity-token");
|
||||
var r = AppProcess.profile("bedrock")
|
||||
.env("AWS_CONTAINER_CREDENTIALS_FULL_URI", cloud.url() + "/pod-identity/credentials")
|
||||
.env("AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE", token.toString())
|
||||
.env("AWS_ENDPOINT_URL_STS", cloud.url())
|
||||
.env("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", cloud.url())
|
||||
.env("AWS_EC2_METADATA_DISABLED", "true").run();
|
||||
var agent = cloud.seen("pod-identity").getFirst();
|
||||
var sig = Wire.sigV4(cloud.seen("bedrock").getFirst());
|
||||
t.line("Environment: AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE (what the Pod Identity webhook injects)");
|
||||
t.line(" no AWS_ROLE_ARN, no AWS_WEB_IDENTITY_TOKEN_FILE").blank();
|
||||
r.output().lines().filter(l -> l.startsWith("ANSWER")).forEach(l -> t.line("%s", l));
|
||||
t.line("Credentials endpoint calls : %d", cloud.seen("pod-identity").size());
|
||||
t.line(" Authorization header equals the token file : %s", agent.header("authorization").equals(Files.readString(token)));
|
||||
t.line("AssumeRoleWithWebIdentity calls : %d", Wire.stsCalls(cloud, "AssumeRoleWithWebIdentity"));
|
||||
t.line("Bedrock request signed by : %s...", sig.accessKeyId().substring(0, 12));
|
||||
|
||||
assertThat(r.exit()).isZero();
|
||||
assertThat(agent.header("authorization")).isEqualTo(Files.readString(token));
|
||||
assertThat(Wire.stsCalls(cloud, "AssumeRoleWithWebIdentity")).isZero();
|
||||
assertThat(sig.accessKeyId()).startsWith("ASIAPODID");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.ankurm.cloudproviders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.cloudproviders.support.AppProcess;
|
||||
import com.ankurm.cloudproviders.support.LocalCloud;
|
||||
import com.ankurm.cloudproviders.support.Transcript;
|
||||
import com.ankurm.cloudproviders.support.Wire;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Traps and checks that are not specific to one cloud. */
|
||||
class CommonTest {
|
||||
|
||||
@Test
|
||||
void otherModalitiesStillDefaultToOpenAi() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("11-startup-trap.txt",
|
||||
"Only chat is used, but the OpenAI starter is on the classpath: what starts?")) {
|
||||
Path token = Wire.writeJwtFile("trap", "sa");
|
||||
var normal = BedrockTest.irsa(cloud, token).run();
|
||||
var trap = BedrockTest.irsa(cloud, token).arg("--spring.ai.model.audio.speech=openai").run();
|
||||
t.line("profile bedrock, spring.ai.model.chat=bedrock-converse, no OpenAI key.").blank();
|
||||
t.line("with spring.ai.model.audio.speech=none (this module's setting): exit %d", normal.exit());
|
||||
t.line("with spring.ai.model.audio.speech unset (the default, here set to its default value openai): exit %d", trap.exit());
|
||||
trap.output().lines().filter(l -> l.contains("Factory method 'openAiSdkAudioSpeechModel' threw exception")).limit(1)
|
||||
.forEach(l -> t.line(" %s", l.substring(l.indexOf("Error creating bean with name"))));
|
||||
assertThat(normal.exit()).isZero();
|
||||
assertThat(trap.exit()).isNotZero();
|
||||
assertThat(trap.output()).contains("At least one credential source must be specified");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretsAndTheAuditLogAtDefaultAndDebugLevels() throws Exception {
|
||||
try (LocalCloud cloud = new LocalCloud(); Transcript t = new Transcript("12-audit-and-secret-hygiene.txt",
|
||||
"Audit lines, and a search of the whole log for every secret the run handled")) {
|
||||
Path token = Wire.writeJwtFile("hyg", "system:serviceaccount:ai:spring-ai");
|
||||
String webIdentity = Files.readString(token);
|
||||
List<String> awsSecrets = List.of("stub-secret-access-key-1", "stub-session-token-1", webIdentity);
|
||||
|
||||
var awsDefault = BedrockTest.irsa(cloud, token).arg("--app.calls=2").run();
|
||||
cloud.reset();
|
||||
var awsDebug = BedrockTest.irsa(cloud, token).arg("--logging.level.software.amazon.awssdk=DEBUG")
|
||||
.arg("--logging.level.org.springframework.ai=DEBUG").arg("--app.calls=2").run();
|
||||
cloud.reset();
|
||||
var az = AzureTest.managedIdentity("azure", cloud)
|
||||
.arg("--logging.level.com.azure=DEBUG").arg("--logging.level.com.microsoft.aad=DEBUG")
|
||||
.arg("--logging.level.okhttp3=DEBUG").arg("--logging.level.org.springframework.ai=DEBUG")
|
||||
.arg("--app.calls=2").run();
|
||||
String jwt = Wire.bearer(cloud.seen("azure-openai").getFirst());
|
||||
|
||||
t.line("Audit lines from the Bedrock run (two calls, default log levels):");
|
||||
awsDefault.output().lines().filter(l -> l.contains(" audit - ")).forEach(l -> t.line(" %s",
|
||||
l.replaceAll("ms=\\d+", "ms=<n>").replaceFirst("^\\d\\d:\\d\\d:\\d\\d\\.\\d+ ", "")));
|
||||
t.line("Audit lines from the Azure run (two calls, DEBUG on com.azure, MSAL, okhttp, Spring AI):");
|
||||
az.output().lines().filter(l -> l.contains(" audit - ")).forEach(l -> t.line(" %s",
|
||||
l.replaceAll("ms=\\d+", "ms=<n>").replaceFirst("^\\d\\d:\\d\\d:\\d\\d\\.\\d+ ", "")));
|
||||
t.blank();
|
||||
t.line("Searched each whole log for every secret the run handled:").blank();
|
||||
t.line("%-34s %-22s %-34s %s", "", "Bedrock, default levels", "Bedrock, DEBUG on awssdk + Spring AI", "Azure, DEBUG");
|
||||
for (String s : awsSecrets) {
|
||||
t.line("%-34s %-22s %-34s %s", label(s), found(awsDefault.output(), s), found(awsDebug.output(), s), "-");
|
||||
}
|
||||
t.line("%-34s %-22s %-34s %s", "Azure access token (JWT)", "-", "-", found(az.output(), jwt));
|
||||
t.line("%-34s %-22s %-34s %s", "Azure token payload segment", "-", "-", found(az.output(), jwt.split("\\.")[1]));
|
||||
t.line("%-34s %-22s %-34s %s", "IDENTITY_HEADER value", "-", "-", found(az.output(), LocalCloud.IDENTITY_HEADER));
|
||||
t.line("%-34s %-22s %-34s %s", "Prompt text", found(awsDefault.output(), "Say hello in five words."),
|
||||
found(awsDebug.output(), "Say hello in five words."), found(az.output(), "Say hello in five words."));
|
||||
t.blank();
|
||||
t.line("Log size: Bedrock default %d lines, Bedrock DEBUG %d lines, Azure DEBUG %d lines",
|
||||
awsDefault.output().lines().count(), awsDebug.output().lines().count(), az.output().lines().count());
|
||||
var ctx = awsDebug.output().lines().toList();
|
||||
for (int i = 0; i < ctx.size(); i++) {
|
||||
if (ctx.get(i).contains("x-amz-security-token:stub-session-token-1")) {
|
||||
int start = i;
|
||||
while (start > 0 && !ctx.get(start).contains("AWS4 Canonical Request")) {
|
||||
start--;
|
||||
}
|
||||
t.line("The session token in the DEBUG log comes from the SigV4 signer's canonical request:");
|
||||
t.line(" %s", ctx.get(start).replaceFirst("^\\d\\d:\\d\\d:\\d\\d\\.\\d+ ", ""));
|
||||
t.line(" ...");
|
||||
t.line(" %s", ctx.get(i));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(awsDefault.output().lines().filter(l -> l.contains(" audit - ")).count()).isEqualTo(2);
|
||||
assertThat(az.output().lines().filter(l -> l.contains(" audit - ")).count()).isEqualTo(2);
|
||||
for (String s : awsSecrets) {
|
||||
assertThat(awsDefault.output()).doesNotContain(s);
|
||||
}
|
||||
assertThat(awsDebug.output()).doesNotContain("stub-secret-access-key-1").doesNotContain(webIdentity);
|
||||
assertThat(awsDebug.output()).contains("x-amz-security-token:stub-session-token-1");
|
||||
assertThat(az.output()).doesNotContain(jwt).doesNotContain(LocalCloud.IDENTITY_HEADER);
|
||||
}
|
||||
}
|
||||
|
||||
private static String found(String log, String secret) {
|
||||
return log.contains(secret) ? "FOUND" : "not found";
|
||||
}
|
||||
|
||||
private static String label(String s) {
|
||||
return s.startsWith("stub-secret") ? "STS secret access key" : s.startsWith("stub-session") ? "STS session token"
|
||||
: "Web identity token (projected)";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.ankurm.cloudproviders.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Runs the real application in a child JVM with an exact environment, the way a pod or an App Service container
|
||||
* would see it. The child inherits nothing from the build machine: no proxy variables, no AWS_* or AZURE_*.
|
||||
*/
|
||||
public final class AppProcess {
|
||||
|
||||
public record Result(int exit, String output) {
|
||||
public List<String> lines(String contains) {
|
||||
return output.lines().filter(l -> l.contains(contains)).toList();
|
||||
}
|
||||
}
|
||||
|
||||
private final Map<String, String> env = new LinkedHashMap<>();
|
||||
private final List<String> args = new ArrayList<>();
|
||||
private String classpath = System.getProperty("java.class.path");
|
||||
|
||||
public static AppProcess profile(String profile) {
|
||||
AppProcess p = new AppProcess();
|
||||
p.args.add("--spring.profiles.active=" + profile);
|
||||
return p;
|
||||
}
|
||||
|
||||
public AppProcess env(String key, String value) {
|
||||
env.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public AppProcess arg(String arg) {
|
||||
args.add(arg);
|
||||
return this;
|
||||
}
|
||||
|
||||
public AppProcess classpathWithout(String jarPrefix) {
|
||||
classpath = java.util.Arrays.stream(classpath.split(java.io.File.pathSeparator))
|
||||
.filter(e -> !Path.of(e).getFileName().toString().startsWith(jarPrefix))
|
||||
.collect(Collectors.joining(java.io.File.pathSeparator));
|
||||
return this;
|
||||
}
|
||||
|
||||
public Result run() {
|
||||
List<String> cmd = new ArrayList<>();
|
||||
cmd.add(Path.of(System.getProperty("java.home"), "bin", "java").toString());
|
||||
cmd.add("-Duser.timezone=UTC");
|
||||
cmd.add("-cp");
|
||||
cmd.add(classpath);
|
||||
cmd.add("com.ankurm.cloudproviders.CloudProvidersApplication");
|
||||
cmd.addAll(args);
|
||||
ProcessBuilder pb = new ProcessBuilder(cmd).redirectErrorStream(true);
|
||||
pb.environment().clear();
|
||||
pb.environment().put("PATH", System.getenv("PATH"));
|
||||
pb.environment().put("HOME", "/nonexistent-home");
|
||||
pb.environment().putAll(env);
|
||||
try {
|
||||
Process proc = pb.start();
|
||||
byte[] out = proc.getInputStream().readAllBytes();
|
||||
if (!proc.waitFor(120, TimeUnit.SECONDS)) {
|
||||
proc.destroyForcibly();
|
||||
}
|
||||
return new Result(proc.exitValue(), new String(out, StandardCharsets.UTF_8));
|
||||
}
|
||||
catch (IOException | InterruptedException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package com.ankurm.cloudproviders.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
/**
|
||||
* One local HTTP server standing in for four cloud endpoints: AWS STS, Bedrock Runtime, the Azure managed identity
|
||||
* token endpoint (App Service style) and an Azure OpenAI chat-completions endpoint. It records every request so a
|
||||
* test can assert what the real Spring AI and cloud SDK code sent. Everything it answers is invented.
|
||||
*/
|
||||
public final class LocalCloud implements AutoCloseable {
|
||||
|
||||
public record Seen(String service, String method, String path, String query, Map<String, String> headers,
|
||||
String body) {
|
||||
public String header(String name) {
|
||||
return headers.get(name.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
public static final String IDENTITY_HEADER = "local-identity-header-value";
|
||||
public static final String ROLE_ARN = "arn:aws:iam::111122223333:role/spring-ai-bedrock";
|
||||
public static final String ASSUMED_ARN = "arn:aws:sts::111122223333:assumed-role/spring-ai-bedrock/pod-session";
|
||||
|
||||
private final HttpServer server;
|
||||
private final List<Seen> seen = new CopyOnWriteArrayList<>();
|
||||
private final AtomicInteger stsIssued = new AtomicInteger();
|
||||
private final AtomicInteger msiIssued = new AtomicInteger();
|
||||
|
||||
/** Lifetime of the temporary AWS credentials STS hands out. */
|
||||
public volatile int stsTtlSeconds = 3600;
|
||||
/** Lifetime of the Azure access tokens the managed identity endpoint hands out. */
|
||||
public volatile int msiTtlSeconds = 3600;
|
||||
|
||||
public LocalCloud() {
|
||||
try {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
server.createContext("/", this::handle);
|
||||
server.start();
|
||||
}
|
||||
|
||||
public String url() {
|
||||
return "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
}
|
||||
|
||||
public List<Seen> seen() {
|
||||
return seen;
|
||||
}
|
||||
|
||||
public List<Seen> seen(String service) {
|
||||
return seen.stream().filter(s -> s.service().equals(service)).toList();
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
seen.clear();
|
||||
stsIssued.set(0);
|
||||
msiIssued.set(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
private void handle(HttpExchange ex) throws IOException {
|
||||
URI uri = ex.getRequestURI();
|
||||
String path = uri.getPath();
|
||||
String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
|
||||
Map<String, String> headers = new TreeMap<>();
|
||||
ex.getRequestHeaders().forEach((k, v) -> headers.put(k.toLowerCase(), String.join(",", v)));
|
||||
|
||||
String service;
|
||||
String contentType = "application/json";
|
||||
String out;
|
||||
int status = 200;
|
||||
if (path.startsWith("/model/")) {
|
||||
service = "bedrock";
|
||||
out = """
|
||||
{"output":{"message":{"role":"assistant","content":[{"text":"Hello from the Bedrock stub."}]}},
|
||||
"stopReason":"end_turn","usage":{"inputTokens":12,"outputTokens":7,"totalTokens":19},
|
||||
"metrics":{"latencyMs":3}}""";
|
||||
}
|
||||
else if (path.startsWith("/pod-identity/")) {
|
||||
service = "pod-identity";
|
||||
out = podIdentityCredentials(headers.get("authorization"));
|
||||
}
|
||||
else if (path.startsWith("/msi/")) {
|
||||
service = "msi";
|
||||
if (!IDENTITY_HEADER.equals(headers.get("x-identity-header"))) {
|
||||
status = 401;
|
||||
out = "{\"error\":\"bad identity header\"}";
|
||||
}
|
||||
else {
|
||||
out = msiToken();
|
||||
}
|
||||
}
|
||||
else if (path.contains("/chat/completions")) {
|
||||
service = "azure-openai";
|
||||
out = """
|
||||
{"id":"chatcmpl-stub","object":"chat.completion","created":1,"model":"gpt-4o-mini",
|
||||
"choices":[{"index":0,"message":{"role":"assistant","content":"Hello from the Azure stub."},
|
||||
"finish_reason":"stop"}],
|
||||
"usage":{"prompt_tokens":11,"completion_tokens":6,"total_tokens":17}}""";
|
||||
}
|
||||
else if (body.contains("Action=AssumeRoleWithWebIdentity")) {
|
||||
service = "sts";
|
||||
contentType = "text/xml";
|
||||
out = assumeRole();
|
||||
}
|
||||
else if (body.contains("Action=GetCallerIdentity")) {
|
||||
service = "sts";
|
||||
contentType = "text/xml";
|
||||
out = """
|
||||
<GetCallerIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
|
||||
<GetCallerIdentityResult><Arn>%s</Arn><UserId>AROAEXAMPLE:pod-session</UserId>
|
||||
<Account>111122223333</Account></GetCallerIdentityResult>
|
||||
<ResponseMetadata><RequestId>stub</RequestId></ResponseMetadata>
|
||||
</GetCallerIdentityResponse>""".formatted(ASSUMED_ARN);
|
||||
}
|
||||
else {
|
||||
service = "unknown";
|
||||
status = 404;
|
||||
out = "{}";
|
||||
}
|
||||
seen.add(new Seen(service, ex.getRequestMethod(), path, uri.getRawQuery(), headers, body));
|
||||
byte[] bytes = out.getBytes(StandardCharsets.UTF_8);
|
||||
ex.getResponseHeaders().add("Content-Type", contentType);
|
||||
ex.sendResponseHeaders(status, bytes.length);
|
||||
ex.getResponseBody().write(bytes);
|
||||
ex.close();
|
||||
}
|
||||
|
||||
private String assumeRole() {
|
||||
int n = stsIssued.incrementAndGet();
|
||||
Instant expiry = Instant.now().plusSeconds(stsTtlSeconds);
|
||||
return """
|
||||
<AssumeRoleWithWebIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
|
||||
<AssumeRoleWithWebIdentityResult>
|
||||
<Credentials>
|
||||
<AccessKeyId>ASIASTUB%07d</AccessKeyId>
|
||||
<SecretAccessKey>stub-secret-access-key-%d</SecretAccessKey>
|
||||
<SessionToken>stub-session-token-%d</SessionToken>
|
||||
<Expiration>%s</Expiration>
|
||||
</Credentials>
|
||||
<AssumedRoleUser><AssumedRoleId>AROAEXAMPLE:pod-session</AssumedRoleId><Arn>%s</Arn></AssumedRoleUser>
|
||||
</AssumeRoleWithWebIdentityResult>
|
||||
<ResponseMetadata><RequestId>stub</RequestId></ResponseMetadata>
|
||||
</AssumeRoleWithWebIdentityResponse>""".formatted(n, n, n, expiry, ASSUMED_ARN);
|
||||
}
|
||||
|
||||
/** EKS Pod Identity agent answer: the container credentials format. Requires the projected token as the header. */
|
||||
private String podIdentityCredentials(String authorization) {
|
||||
int n = stsIssued.incrementAndGet();
|
||||
Instant expiry = Instant.now().plusSeconds(stsTtlSeconds);
|
||||
return "{\"AccessKeyId\":\"ASIAPODID%06d\",\"SecretAccessKey\":\"stub-pod-secret-%d\",\"Token\":\"stub-pod-token-%d\","
|
||||
.formatted(n, n, n) + "\"Expiration\":\"" + expiry + "\",\"AccountId\":\"111122223333\"}";
|
||||
}
|
||||
|
||||
private String msiToken() {
|
||||
int n = msiIssued.incrementAndGet();
|
||||
long exp = Instant.now().getEpochSecond() + msiTtlSeconds;
|
||||
String header = b64("{\"alg\":\"none\",\"typ\":\"JWT\"}");
|
||||
String payload = b64("{\"oid\":\"00000000-0000-0000-0000-00000000a11c\",\"tid\":\"11111111-2222-3333-4444-555555555555\","
|
||||
+ "\"aud\":\"https://cognitiveservices.azure.com\",\"exp\":" + exp + ",\"n\":" + n + "}");
|
||||
String jwt = header + "." + payload + ".stub-signature";
|
||||
return "{\"access_token\":\"" + jwt + "\",\"expires_on\":\"" + exp
|
||||
+ "\",\"resource\":\"https://cognitiveservices.azure.com\",\"token_type\":\"Bearer\"}";
|
||||
}
|
||||
|
||||
private static String b64(String s) {
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(s.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ankurm.cloudproviders.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Writes a numbered transcript under {@code output/} (repository root, not {@code docs/}) and
|
||||
* echoes it to the console. Every console block quoted in the article comes out of one of these
|
||||
* files verbatim.
|
||||
*/
|
||||
public final class Transcript implements AutoCloseable {
|
||||
|
||||
private final Path path;
|
||||
private final StringWriter buffer = new StringWriter();
|
||||
private final PrintWriter out = new PrintWriter(buffer);
|
||||
|
||||
public Transcript(String fileName, String title) {
|
||||
this.path = Path.of("output", fileName);
|
||||
out.println("# " + title);
|
||||
out.println();
|
||||
}
|
||||
|
||||
public Transcript line(String format, Object... args) {
|
||||
out.println(args.length == 0 ? format : String.format(format, args));
|
||||
return this;
|
||||
}
|
||||
|
||||
public Transcript blank() {
|
||||
out.println();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
out.flush();
|
||||
try {
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, buffer.toString());
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("could not write " + path, e);
|
||||
}
|
||||
System.out.print(buffer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.ankurm.cloudproviders.support;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Small readers for what the stub recorded: SigV4 headers, JWT claims, STS form bodies. */
|
||||
public final class Wire {
|
||||
|
||||
private Wire() {
|
||||
}
|
||||
|
||||
/** The parts of an AWS Signature V4 Authorization header that identify who signed and for what. */
|
||||
public record SigV4(String accessKeyId, String region, String service, boolean signedSecurityToken) {
|
||||
}
|
||||
|
||||
private static final Pattern CRED = Pattern.compile("Credential=([^/]+)/(\\d{8})/([^/]+)/([^/]+)/aws4_request");
|
||||
|
||||
public static SigV4 sigV4(LocalCloud.Seen seen) {
|
||||
String auth = seen.header("authorization");
|
||||
if (auth == null) {
|
||||
return null;
|
||||
}
|
||||
Matcher m = CRED.matcher(auth);
|
||||
if (!m.find()) {
|
||||
throw new IllegalStateException("not SigV4: " + auth);
|
||||
}
|
||||
return new SigV4(m.group(1), m.group(3), m.group(4), auth.contains("x-amz-security-token"));
|
||||
}
|
||||
|
||||
public static String form(LocalCloud.Seen seen, String field) {
|
||||
for (String pair : seen.body().split("&")) {
|
||||
String[] kv = pair.split("=", 2);
|
||||
if (kv[0].equals(field)) {
|
||||
return java.net.URLDecoder.decode(kv.length > 1 ? kv[1] : "", StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Returns the three-segment JWT carried by an {@code Authorization: Bearer ...} header. */
|
||||
public static String bearer(LocalCloud.Seen seen) {
|
||||
String auth = seen.header("authorization");
|
||||
return auth != null && auth.startsWith("Bearer ") ? auth.substring("Bearer ".length()) : null;
|
||||
}
|
||||
|
||||
public static JsonNode jwtClaims(String jwt) {
|
||||
String[] parts = jwt.split("\\.");
|
||||
return JsonMapper.shared().readTree(Base64.getUrlDecoder().decode(parts[1]));
|
||||
}
|
||||
|
||||
/** Counts STS calls by Action. */
|
||||
public static long stsCalls(LocalCloud cloud, String action) {
|
||||
return cloud.seen("sts").stream().filter(s -> s.body().contains("Action=" + action)).count();
|
||||
}
|
||||
|
||||
public static List<LocalCloud.Seen> signedBy(LocalCloud cloud, String service) {
|
||||
return cloud.seen(service);
|
||||
}
|
||||
|
||||
public static Path writeJwtFile(String prefix, String subject) {
|
||||
try {
|
||||
Path f = Files.createTempFile(prefix, ".jwt");
|
||||
String h = Base64.getUrlEncoder().withoutPadding().encodeToString("{\"alg\":\"none\"}".getBytes());
|
||||
String p = Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(("{\"sub\":\"" + subject + "\"}").getBytes());
|
||||
Files.writeString(f, h + "." + p + ".projected-token-signature");
|
||||
return f;
|
||||
}
|
||||
catch (java.io.IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<String, String> noProxyEnv() {
|
||||
return Map.of();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user