|
| 1 | +// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import 'dart:convert'; |
| 6 | +import 'dart:io'; |
| 7 | + |
| 8 | +import 'package:http/http.dart' as http; |
| 9 | + |
| 10 | +import 'exceptions.dart'; |
| 11 | +import 'utils.dart'; |
| 12 | + |
| 13 | +/// Signs data using the IAM Credentials API's signBlob endpoint. |
| 14 | +/// |
| 15 | +/// This is useful when running on Cloud Run or Google Compute Engine with |
| 16 | +/// Application Default Credentials, where there's no private key available |
| 17 | +/// locally. Instead of signing locally, this class uses the IAM service to |
| 18 | +/// perform signing operations. |
| 19 | +/// |
| 20 | +/// Does not close the [http.Client] passed to the constructor. |
| 21 | +/// |
| 22 | +/// See: https://docs.cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob |
| 23 | +/// |
| 24 | +/// Example usage: |
| 25 | +/// ```dart |
| 26 | +/// import 'dart:convert'; |
| 27 | +/// import 'package:googleapis_auth/googleapis_auth.dart'; |
| 28 | +/// |
| 29 | +/// // Get an authenticated client (e.g., via metadata server) |
| 30 | +/// final authClient = await clientViaMetadataServer(); |
| 31 | +/// |
| 32 | +/// // Create an IAMSigner with explicit service account email |
| 33 | +/// final signer = IAMSigner( |
| 34 | +/// authClient, |
| 35 | +/// serviceAccountEmail: 'my-service@project.iam.gserviceaccount.com', |
| 36 | +/// ); |
| 37 | +/// |
| 38 | +/// // Or let it fetch the email from metadata server |
| 39 | +/// final signer = IAMSigner(authClient); |
| 40 | +/// |
| 41 | +/// // Sign some data |
| 42 | +/// final data = utf8.encode('data to sign'); |
| 43 | +/// final signature = await signer.sign(data); |
| 44 | +/// ``` |
| 45 | +class IAMSigner { |
| 46 | + final http.Client _client; |
| 47 | + final String? _serviceAccountEmail; |
| 48 | + final String _endpoint; |
| 49 | + |
| 50 | + String? _cachedEmail; |
| 51 | + |
| 52 | + /// Creates an [IAMSigner] instance. |
| 53 | + /// |
| 54 | + /// [client] is used for making HTTP requests to the metadata server and |
| 55 | + /// IAM API. |
| 56 | + /// |
| 57 | + /// [serviceAccountEmail] is the optional service account email to use for |
| 58 | + /// signing. If not provided, it will be fetched from the GCE metadata server. |
| 59 | + /// |
| 60 | + /// [endpoint] specifies the IAM Credentials API endpoint. |
| 61 | + /// Defaults to `https://iamcredentials.googleapis.com`. |
| 62 | + IAMSigner( |
| 63 | + http.Client client, { |
| 64 | + String? serviceAccountEmail, |
| 65 | + String endpoint = 'https://iamcredentials.$defaultUniverseDomain', |
| 66 | + }) : _client = client, |
| 67 | + _serviceAccountEmail = serviceAccountEmail, |
| 68 | + _endpoint = endpoint; |
| 69 | + |
| 70 | + /// Returns the service account email. |
| 71 | + /// |
| 72 | + /// If an email was provided in the constructor, returns that email. |
| 73 | + /// Otherwise, queries the GCE metadata server to retrieve the default |
| 74 | + /// service account email. |
| 75 | + Future<String> getServiceAccountEmail() async { |
| 76 | + if (_serviceAccountEmail != null) { |
| 77 | + return _serviceAccountEmail; |
| 78 | + } |
| 79 | + |
| 80 | + if (_cachedEmail != null) { |
| 81 | + return _cachedEmail!; |
| 82 | + } |
| 83 | + |
| 84 | + final metadataHost = |
| 85 | + Platform.environment[gceMetadataHostEnvVar] ?? defaultMetadataHost; |
| 86 | + final emailUrl = Uri.parse( |
| 87 | + 'http://$metadataHost/computeMetadata/v1/instance/service-accounts/default/email', |
| 88 | + ); |
| 89 | + |
| 90 | + final response = await _client.get(emailUrl, headers: metadataFlavorHeader); |
| 91 | + if (response.statusCode != 200) { |
| 92 | + throw ServerRequestFailedException( |
| 93 | + 'Failed to get service account email from metadata server.', |
| 94 | + statusCode: response.statusCode, |
| 95 | + responseContent: response.body, |
| 96 | + ); |
| 97 | + } |
| 98 | + |
| 99 | + _cachedEmail = response.body.trim(); |
| 100 | + return _cachedEmail!; |
| 101 | + } |
| 102 | + |
| 103 | + /// Signs the given [data] using the IAM Credentials API. |
| 104 | + /// |
| 105 | + /// Returns the signature as a String (base64-encoded). |
| 106 | + /// |
| 107 | + /// Throws a [ServerRequestFailedException] if the signing operation fails. |
| 108 | + Future<String> sign(List<int> data) async { |
| 109 | + final email = await getServiceAccountEmail(); |
| 110 | + final encodedEmail = Uri.encodeComponent(email); |
| 111 | + |
| 112 | + final signBlobUrl = Uri.parse( |
| 113 | + '$_endpoint/v1/projects/-/serviceAccounts/$encodedEmail:signBlob', |
| 114 | + ); |
| 115 | + |
| 116 | + final requestBody = jsonEncode({'payload': base64Encode(data)}); |
| 117 | + final request = http.Request('POST', signBlobUrl) |
| 118 | + ..headers['Content-Type'] = 'application/json' |
| 119 | + ..body = requestBody; |
| 120 | + |
| 121 | + final responseJson = await _client.requestJson( |
| 122 | + request, |
| 123 | + 'Failed to sign blob via IAM.', |
| 124 | + ); |
| 125 | + |
| 126 | + return switch (responseJson) { |
| 127 | + {'signedBlob': final String signedBlob} => signedBlob, |
| 128 | + _ => throw ServerRequestFailedException( |
| 129 | + 'IAM signBlob response missing signedBlob field.', |
| 130 | + responseContent: responseJson, |
| 131 | + ), |
| 132 | + }; |
| 133 | + } |
| 134 | +} |
0 commit comments