|
| 1 | +package com.infisical.sdk.auth; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.infisical.sdk.models.AwsAuthParameters; |
| 6 | +import java.net.URI; |
| 7 | +import java.net.URLEncoder; |
| 8 | +import java.nio.charset.StandardCharsets; |
| 9 | +import java.time.Clock; |
| 10 | +import java.time.Instant; |
| 11 | +import java.time.ZoneOffset; |
| 12 | +import java.util.Base64; |
| 13 | +import java.util.List; |
| 14 | +import java.util.Map; |
| 15 | +import java.util.stream.Collectors; |
| 16 | +import lombok.Builder; |
| 17 | +import lombok.Data; |
| 18 | +import lombok.NonNull; |
| 19 | +import software.amazon.awssdk.auth.credentials.AwsCredentials; |
| 20 | +import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; |
| 21 | +import software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider; |
| 22 | +import software.amazon.awssdk.http.ContentStreamProvider; |
| 23 | +import software.amazon.awssdk.http.SdkHttpFullRequest; |
| 24 | +import software.amazon.awssdk.http.SdkHttpMethod; |
| 25 | +import software.amazon.awssdk.http.SdkHttpRequest; |
| 26 | +import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner; |
| 27 | +import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; |
| 28 | +import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; |
| 29 | +import software.amazon.awssdk.regions.Region; |
| 30 | +import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; |
| 31 | + |
| 32 | +@Data |
| 33 | +@Builder |
| 34 | +public class AwsAuthProvider { |
| 35 | + private static final ObjectMapper objectMapper = new ObjectMapper(); |
| 36 | + |
| 37 | + @NonNull @Builder.Default private final String serviceName = "sts"; |
| 38 | + @NonNull @Builder.Default private final SdkHttpMethod httpMethod = SdkHttpMethod.POST; |
| 39 | + @NonNull @Builder.Default private final String endpointTemplate = "https://sts.%s.amazonaws.com"; |
| 40 | + |
| 41 | + @NonNull @Builder.Default |
| 42 | + private final String contentType = "application/x-www-form-urlencoded; charset=utf-8"; |
| 43 | + |
| 44 | + @NonNull @Builder.Default |
| 45 | + private final Map<String, List<String>> params = |
| 46 | + Map.ofEntries( |
| 47 | + Map.entry("Action", List.of("GetCallerIdentity")), |
| 48 | + Map.entry("Version", List.of("2011-06-15"))); |
| 49 | + |
| 50 | + private final Instant overrideInstant; |
| 51 | + |
| 52 | + /** |
| 53 | + * Create AwsAuthLoginInput from given AWS credentials. |
| 54 | + * |
| 55 | + * @param region region of AWS identity |
| 56 | + * @param credentials AWS credentials for creating the login input |
| 57 | + * @param sessionToken Session token for creating the login input |
| 58 | + * @return the AwsAuthLoginInput created from the given credentials for exchanging access token |
| 59 | + */ |
| 60 | + public AwsAuthParameters fromCredentials( |
| 61 | + String region, AwsCredentials credentials, String sessionToken) { |
| 62 | + final AwsV4HttpSigner signer = AwsV4HttpSigner.create(); |
| 63 | + final String iamRequestURL = endpointTemplate.formatted(region); |
| 64 | + final String iamRequestBody = encodeParameters(params); |
| 65 | + final SdkHttpFullRequest.Builder requestBuilder = |
| 66 | + SdkHttpFullRequest.builder() |
| 67 | + .uri(URI.create(iamRequestURL)) |
| 68 | + .method(httpMethod) |
| 69 | + .appendHeader("Content-Type", contentType); |
| 70 | + if (sessionToken != null) { |
| 71 | + requestBuilder.appendHeader("X-Amz-Security-Token", sessionToken); |
| 72 | + } |
| 73 | + final SdkHttpFullRequest request = requestBuilder.build(); |
| 74 | + final SdkHttpRequest signedRequest = |
| 75 | + signer |
| 76 | + .sign( |
| 77 | + signingRequest -> { |
| 78 | + var req = |
| 79 | + signingRequest |
| 80 | + .request(request) |
| 81 | + .identity(credentials) |
| 82 | + .payload( |
| 83 | + ContentStreamProvider.fromByteArray( |
| 84 | + iamRequestBody.getBytes(StandardCharsets.UTF_8))) |
| 85 | + .putProperty(AwsV4FamilyHttpSigner.SERVICE_SIGNING_NAME, serviceName) |
| 86 | + .putProperty(AwsV4HttpSigner.REGION_NAME, region); |
| 87 | + if (overrideInstant != null) { |
| 88 | + req.putProperty( |
| 89 | + HttpSigner.SIGNING_CLOCK, Clock.fixed(overrideInstant, ZoneOffset.UTC)); |
| 90 | + } |
| 91 | + }) |
| 92 | + .request(); |
| 93 | + final Map<String, String> requestHeaders = |
| 94 | + signedRequest.headers().entrySet().stream() |
| 95 | + .map(entry -> Map.entry(entry.getKey(), entry.getValue().getFirst())) |
| 96 | + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); |
| 97 | + requestHeaders.put("Content-Length", String.valueOf(iamRequestBody.length())); |
| 98 | + final String encodedHeader; |
| 99 | + try { |
| 100 | + encodedHeader = |
| 101 | + Base64.getEncoder() |
| 102 | + .encodeToString( |
| 103 | + objectMapper.writeValueAsString(requestHeaders).getBytes(StandardCharsets.UTF_8)); |
| 104 | + } catch (JsonProcessingException e) { |
| 105 | + throw new RuntimeException(e); |
| 106 | + } |
| 107 | + final String encodedBody = |
| 108 | + Base64.getEncoder().encodeToString(iamRequestBody.getBytes(StandardCharsets.UTF_8)); |
| 109 | + return AwsAuthParameters.builder() |
| 110 | + .iamHttpRequestMethod(httpMethod.name()) |
| 111 | + .iamRequestHeaders(encodedHeader) |
| 112 | + .iamRequestBody(encodedBody) |
| 113 | + .build(); |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Create AwsAuthLoginInput from the instance profile in the current environment. |
| 118 | + * |
| 119 | + * @return the AwsAuthLoginInput created from the current instance profile for exchanging access |
| 120 | + * token |
| 121 | + */ |
| 122 | + public AwsAuthParameters fromInstanceProfile() { |
| 123 | + try (InstanceProfileCredentialsProvider provider = |
| 124 | + InstanceProfileCredentialsProvider.create()) { |
| 125 | + final AwsSessionCredentials credentials = |
| 126 | + (AwsSessionCredentials) provider.resolveCredentials(); |
| 127 | + final DefaultAwsRegionProviderChain regionProvider = |
| 128 | + DefaultAwsRegionProviderChain.builder().build(); |
| 129 | + final Region region = regionProvider.getRegion(); |
| 130 | + final String sessionToken = credentials.sessionToken(); |
| 131 | + return fromCredentials(region.id(), credentials, sessionToken); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + /** |
| 136 | + * Encode given parameters with URL encoding for the body of form posting request. |
| 137 | + * |
| 138 | + * @param params parameters mapping key to values to encode |
| 139 | + * @return URL-encoded string of the parameters |
| 140 | + */ |
| 141 | + public static String encodeParameters(Map<String, List<String>> params) { |
| 142 | + return params.entrySet().stream() |
| 143 | + .flatMap(entry -> entry.getValue().stream().map(item -> Map.entry(entry.getKey(), item))) |
| 144 | + // Notice: this is not really needed for real world usage, but it makes the |
| 145 | + // body encoded in a deterministic order, so that unit test is much easier |
| 146 | + .sorted(Map.Entry.comparingByKey()) |
| 147 | + .map( |
| 148 | + entry -> |
| 149 | + String.format( |
| 150 | + "%s=%s", |
| 151 | + URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8), |
| 152 | + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8))) |
| 153 | + .collect(Collectors.joining("&")); |
| 154 | + } |
| 155 | + |
| 156 | + public static AwsAuthProvider defaultProvider() { |
| 157 | + return builder().build(); |
| 158 | + } |
| 159 | +} |
0 commit comments