|
| 1 | +// Licensed to Elasticsearch B.V under one or more agreements. |
| 2 | +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. |
| 3 | +// See the LICENSE file in the project root for more information |
| 4 | + |
| 5 | +using System.Security.Cryptography; |
| 6 | +using System.Text; |
| 7 | +using System.Text.Json; |
| 8 | +using System.Text.Json.Serialization; |
| 9 | + |
| 10 | +namespace Documentation.Builder.Http; |
| 11 | + |
| 12 | +internal readonly record struct ServiceAccountKey( |
| 13 | + string Type, |
| 14 | + string ProjectId, |
| 15 | + string PrivateKeyId, |
| 16 | + string PrivateKey, |
| 17 | + string ClientEmail, |
| 18 | + string ClientId, |
| 19 | + string AuthUri, |
| 20 | + string TokenUri, |
| 21 | + string AuthProviderX509CertUrl, |
| 22 | + string ClientX509CertUrl |
| 23 | +); |
| 24 | + |
| 25 | +internal readonly record struct JwtHeader(string Alg, string Typ, string Kid); |
| 26 | + |
| 27 | +internal readonly record struct JwtPayload( |
| 28 | + string Iss, |
| 29 | + string Sub, |
| 30 | + string Aud, |
| 31 | + long Iat, |
| 32 | + long Exp, |
| 33 | + string TargetAudience |
| 34 | +); |
| 35 | + |
| 36 | +[JsonSerializable(typeof(ServiceAccountKey))] |
| 37 | +[JsonSerializable(typeof(JwtPayload))] |
| 38 | +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower)] |
| 39 | +internal sealed partial class GcpJsonContext : JsonSerializerContext { } |
| 40 | + |
| 41 | +[JsonSerializable(typeof(JwtHeader))] |
| 42 | +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] |
| 43 | +internal sealed partial class JwtHeaderJsonContext : JsonSerializerContext { } |
| 44 | + |
| 45 | +// This is a custom implementation to create an ID token for GCP. |
| 46 | +// Because Google.Api.Auth.OAuth2 is not compatible with AOT |
| 47 | +public static class GcpIdTokenGenerator |
| 48 | +{ |
| 49 | + |
| 50 | + public static async Task<string> GenerateIdTokenAsync(string serviceAccountKeyPath, string targetAudience, CancellationToken cancellationToken = default) |
| 51 | + { |
| 52 | + // Read and parse service account key file using System.Text.Json source generation (AOT compatible) |
| 53 | + var serviceAccountJson = await File.ReadAllTextAsync(serviceAccountKeyPath, cancellationToken); |
| 54 | + var serviceAccount = JsonSerializer.Deserialize(serviceAccountJson, GcpJsonContext.Default.ServiceAccountKey); |
| 55 | + |
| 56 | + // Create JWT header |
| 57 | + var header = new JwtHeader("RS256", "JWT", serviceAccount.PrivateKeyId); |
| 58 | + var headerJson = JsonSerializer.Serialize(header, JwtHeaderJsonContext.Default.JwtHeader); |
| 59 | + var headerBase64 = Base64UrlEncode(Encoding.UTF8.GetBytes(headerJson)); |
| 60 | + |
| 61 | + // Create JWT payload |
| 62 | + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); |
| 63 | + var payload = new JwtPayload( |
| 64 | + serviceAccount.ClientEmail, |
| 65 | + serviceAccount.ClientEmail, |
| 66 | + "https://oauth2.googleapis.com/token", |
| 67 | + now, |
| 68 | + now + 3600, // 1 hour expiration |
| 69 | + targetAudience |
| 70 | + ); |
| 71 | + |
| 72 | + var payloadJson = JsonSerializer.Serialize(payload, GcpJsonContext.Default.JwtPayload); |
| 73 | + var payloadBase64 = Base64UrlEncode(Encoding.UTF8.GetBytes(payloadJson)); |
| 74 | + |
| 75 | + // Create signature |
| 76 | + var message = $"{headerBase64}.{payloadBase64}"; |
| 77 | + var messageBytes = Encoding.UTF8.GetBytes(message); |
| 78 | + |
| 79 | + // Parse the private key (removing PEM headers/footers and decoding) |
| 80 | + var privateKeyPem = serviceAccount.PrivateKey |
| 81 | + .Replace("-----BEGIN PRIVATE KEY-----", "") |
| 82 | + .Replace("-----END PRIVATE KEY-----", "") |
| 83 | + .Replace("\n", "") |
| 84 | + .Replace("\r", ""); |
| 85 | + var privateKeyBytes = Convert.FromBase64String(privateKeyPem); |
| 86 | + |
| 87 | + // Create RSA instance and sign |
| 88 | + using var rsa = RSA.Create(); |
| 89 | + rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _); |
| 90 | + var signature = rsa.SignData(messageBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); |
| 91 | + var signatureBase64 = Base64UrlEncode(signature); |
| 92 | + |
| 93 | + var jwt = $"{message}.{signatureBase64}"; |
| 94 | + |
| 95 | + // Exchange JWT for ID token |
| 96 | + return await ExchangeJwtForIdToken(jwt, targetAudience, cancellationToken); |
| 97 | + } |
| 98 | + |
| 99 | + private static async Task<string> ExchangeJwtForIdToken(string jwt, string targetAudience, CancellationToken cancellationToken) |
| 100 | + { |
| 101 | + using var httpClient = new HttpClient(); |
| 102 | + |
| 103 | + var requestContent = new FormUrlEncodedContent([ |
| 104 | + new KeyValuePair<string, string>("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"), |
| 105 | + new KeyValuePair<string, string>("assertion", jwt), |
| 106 | + new KeyValuePair<string, string>("target_audience", targetAudience) |
| 107 | + ]); |
| 108 | + |
| 109 | + var response = await httpClient.PostAsync("https://oauth2.googleapis.com/token", requestContent, cancellationToken); |
| 110 | + _ = response.EnsureSuccessStatusCode(); |
| 111 | + |
| 112 | + var responseJson = await response.Content.ReadAsStringAsync(cancellationToken); |
| 113 | + using var document = JsonDocument.Parse(responseJson); |
| 114 | + |
| 115 | + if (document.RootElement.TryGetProperty("id_token", out var idTokenElement)) |
| 116 | + { |
| 117 | + return idTokenElement.GetString() ?? throw new InvalidOperationException("ID token is null"); |
| 118 | + } |
| 119 | + |
| 120 | + throw new InvalidOperationException("No id_token found in response"); |
| 121 | + } |
| 122 | + |
| 123 | + private static string Base64UrlEncode(byte[] input) |
| 124 | + { |
| 125 | + var base64 = Convert.ToBase64String(input); |
| 126 | + // Convert base64 to base64url encoding |
| 127 | + return base64.Replace('+', '-').Replace('/', '_').TrimEnd('='); |
| 128 | + } |
| 129 | +} |
0 commit comments