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:
Ankur
2026-11-29 13:25:58 +05:30
co-authored by Claude Sonnet 5.5
parent 98ed878675
commit 8f69e7bf50
46 changed files with 1729 additions and 0 deletions
@@ -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;
}
};
}
}
@@ -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();
}
}
@@ -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();
}
}