| | | 1 | | using System.Runtime.ExceptionServices; |
| | | 2 | | using AsiBackbone.Core.Signing; |
| | | 3 | | |
| | | 4 | | namespace AsiBackbone.Signing.ManagedKey; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Provides managed-key signing for AsiBackbone signing abstractions through a host-owned managed-key client. |
| | | 8 | | /// </summary> |
| | | 9 | | /// <remarks> |
| | | 10 | | /// This service signs precomputed hashes only. It never requests or handles raw private key material. |
| | | 11 | | /// </remarks> |
| | | 12 | | public sealed class ManagedKeySigningService : IAsiBackboneSigningService |
| | | 13 | | { |
| | | 14 | | private const string ProviderKind = "managed-key"; |
| | | 15 | | |
| | | 16 | | private readonly ManagedKeySigningOptions options; |
| | | 17 | | private readonly IManagedKeySigningClient client; |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Initializes a new instance of the <see cref="ManagedKeySigningService" /> class. |
| | | 21 | | /// </summary> |
| | 10 | 22 | | public ManagedKeySigningService(ManagedKeySigningOptions options, IManagedKeySigningClient client) |
| | | 23 | | { |
| | 10 | 24 | | ArgumentNullException.ThrowIfNull(options); |
| | 10 | 25 | | ArgumentNullException.ThrowIfNull(client); |
| | | 26 | | |
| | 10 | 27 | | options.Validate(); |
| | 10 | 28 | | this.options = options; |
| | 10 | 29 | | this.client = client; |
| | 10 | 30 | | } |
| | | 31 | | |
| | | 32 | | /// <inheritdoc /> |
| | | 33 | | public async ValueTask<SigningResult> SignAsync( |
| | | 34 | | SigningRequest request, |
| | | 35 | | CancellationToken cancellationToken = default) |
| | | 36 | | { |
| | 8 | 37 | | ArgumentNullException.ThrowIfNull(request); |
| | 8 | 38 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 39 | | |
| | 8 | 40 | | string? validationFailure = ValidateSigningRequest(request); |
| | 8 | 41 | | if (validationFailure is not null) |
| | | 42 | | { |
| | 4 | 43 | | return CreateUnsignedFailureResult(request, validationFailure, validationFailure, retryAttempts: 0); |
| | | 44 | | } |
| | | 45 | | |
| | 4 | 46 | | int attempt = 0; |
| | | 47 | | |
| | | 48 | | while (true) |
| | | 49 | | { |
| | | 50 | | try |
| | | 51 | | { |
| | 6 | 52 | | ManagedKeySignResult managedResult = await client |
| | 6 | 53 | | .SignAsync(CreateManagedKeyRequest(request), cancellationToken) |
| | 6 | 54 | | .ConfigureAwait(false); |
| | | 55 | | |
| | 4 | 56 | | return CreateSignedResult(request, managedResult, attempt); |
| | | 57 | | } |
| | 2 | 58 | | catch (ManagedKeySigningException exception) when (exception.IsRetryable && attempt < options.MaxRetryAttemp |
| | | 59 | | { |
| | 2 | 60 | | attempt++; |
| | 2 | 61 | | await DelayForRetryAsync(cancellationToken).ConfigureAwait(false); |
| | 2 | 62 | | } |
| | 0 | 63 | | catch (ManagedKeySigningException exception) |
| | | 64 | | { |
| | 0 | 65 | | return HandleFailure(request, exception.FailureCode, exception.Message, attempt, exception); |
| | | 66 | | } |
| | 0 | 67 | | catch (TimeoutException exception) |
| | | 68 | | { |
| | 0 | 69 | | return HandleFailure(request, "managedkey.signing.provider-unavailable", exception.GetType().Name, attem |
| | | 70 | | } |
| | 0 | 71 | | catch (InvalidOperationException exception) |
| | | 72 | | { |
| | 0 | 73 | | return HandleFailure(request, "managedkey.signing.failed", exception.GetType().Name, attempt, exception) |
| | | 74 | | } |
| | 0 | 75 | | catch (NotSupportedException exception) |
| | | 76 | | { |
| | 0 | 77 | | return HandleFailure(request, "managedkey.signing.unsupported", exception.GetType().Name, attempt, excep |
| | | 78 | | } |
| | | 79 | | } |
| | 8 | 80 | | } |
| | | 81 | | |
| | | 82 | | private SigningResult HandleFailure( |
| | | 83 | | SigningRequest request, |
| | | 84 | | string failureCode, |
| | | 85 | | string failureMessage, |
| | | 86 | | int retryAttempts, |
| | | 87 | | Exception exception) |
| | | 88 | | { |
| | 0 | 89 | | if (!options.ReturnUnsignedOnFailure) |
| | | 90 | | { |
| | 0 | 91 | | ExceptionDispatchInfo.Capture(exception).Throw(); |
| | | 92 | | } |
| | | 93 | | |
| | 0 | 94 | | return CreateUnsignedFailureResult(request, failureCode, failureMessage, retryAttempts); |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | private ManagedKeySignRequest CreateManagedKeyRequest(SigningRequest request) |
| | | 98 | | { |
| | 6 | 99 | | return new ManagedKeySignRequest( |
| | 6 | 100 | | request.SigningHash, |
| | 6 | 101 | | NormalizeHashAlgorithm(request.HashAlgorithm), |
| | 6 | 102 | | NormalizeRequired(options.SignatureAlgorithm, ManagedKeySigningOptions.DefaultSignatureAlgorithm), |
| | 6 | 103 | | ResolveKeyId(request), |
| | 6 | 104 | | ResolveKeyVersion(request), |
| | 6 | 105 | | request.Purpose, |
| | 6 | 106 | | request.Metadata); |
| | | 107 | | } |
| | | 108 | | |
| | | 109 | | private SigningResult CreateSignedResult( |
| | | 110 | | SigningRequest request, |
| | | 111 | | ManagedKeySignResult managedResult, |
| | | 112 | | int retryAttempts) |
| | | 113 | | { |
| | 4 | 114 | | string resolvedKeyVersion = managedResult.KeyVersion ?? ResolveKeyVersion(request) ?? string.Empty; |
| | 4 | 115 | | Dictionary<string, string> metadata = CreateBaseMetadata(request, retryAttempts); |
| | 4 | 116 | | metadata["signing_status"] = "signed"; |
| | | 117 | | |
| | 4 | 118 | | if (managedResult.ProviderOperationId is not null) |
| | | 119 | | { |
| | 4 | 120 | | metadata["provider_operation_id"] = managedResult.ProviderOperationId; |
| | | 121 | | } |
| | | 122 | | |
| | 24 | 123 | | foreach (KeyValuePair<string, string> item in managedResult.Metadata) |
| | | 124 | | { |
| | 8 | 125 | | if (!IsSafeProviderMetadataKey(item.Key)) |
| | | 126 | | { |
| | | 127 | | continue; |
| | | 128 | | } |
| | | 129 | | |
| | 4 | 130 | | metadata[item.Key.Trim()] = item.Value?.Trim() ?? string.Empty; |
| | | 131 | | } |
| | | 132 | | |
| | 4 | 133 | | var signingMetadata = SigningMetadata.Create( |
| | 4 | 134 | | signingHash: request.SigningHash, |
| | 4 | 135 | | hashAlgorithm: NormalizeHashAlgorithm(request.HashAlgorithm), |
| | 4 | 136 | | signature: managedResult.Signature, |
| | 4 | 137 | | signatureAlgorithm: managedResult.SignatureAlgorithm, |
| | 4 | 138 | | keyId: managedResult.KeyId, |
| | 4 | 139 | | keyVersion: string.IsNullOrWhiteSpace(resolvedKeyVersion) ? null : resolvedKeyVersion, |
| | 4 | 140 | | provider: NormalizeRequired(options.ProviderName, ManagedKeySigningOptions.DefaultProviderName), |
| | 4 | 141 | | signedUtc: managedResult.SignedUtc, |
| | 4 | 142 | | metadata: metadata); |
| | | 143 | | |
| | 4 | 144 | | return SigningResult.FromMetadata(signingMetadata); |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | private SigningResult CreateUnsignedFailureResult( |
| | | 148 | | SigningRequest request, |
| | | 149 | | string failureCode, |
| | | 150 | | string failureMessage, |
| | | 151 | | int retryAttempts) |
| | | 152 | | { |
| | 4 | 153 | | Dictionary<string, string> metadata = CreateBaseMetadata(request, retryAttempts); |
| | 4 | 154 | | metadata["signing_status"] = "failed"; |
| | 4 | 155 | | metadata["failure_code"] = failureCode; |
| | 4 | 156 | | metadata["failure_message"] = failureMessage; |
| | | 157 | | |
| | 4 | 158 | | var signingMetadata = SigningMetadata.Create( |
| | 4 | 159 | | signingHash: request.SigningHash, |
| | 4 | 160 | | hashAlgorithm: NormalizeHashAlgorithm(request.HashAlgorithm), |
| | 4 | 161 | | keyId: ResolveKeyId(request), |
| | 4 | 162 | | keyVersion: ResolveKeyVersion(request), |
| | 4 | 163 | | provider: NormalizeRequired(options.ProviderName, ManagedKeySigningOptions.DefaultProviderName), |
| | 4 | 164 | | metadata: metadata); |
| | | 165 | | |
| | 4 | 166 | | return SigningResult.FromMetadata(signingMetadata); |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | private Dictionary<string, string> CreateBaseMetadata(SigningRequest request, int retryAttempts) |
| | | 170 | | { |
| | 8 | 171 | | Dictionary<string, string> metadata = new(StringComparer.Ordinal) |
| | 8 | 172 | | { |
| | 8 | 173 | | ["provider_kind"] = ProviderKind, |
| | 8 | 174 | | ["remote_key_material"] = "true", |
| | 8 | 175 | | ["raw_private_key_loaded"] = "false", |
| | 8 | 176 | | ["retry_attempts"] = retryAttempts.ToString(System.Globalization.CultureInfo.InvariantCulture), |
| | 8 | 177 | | ["signature_algorithm"] = NormalizeRequired(options.SignatureAlgorithm, ManagedKeySigningOptions.DefaultSign |
| | 8 | 178 | | }; |
| | | 179 | | |
| | 8 | 180 | | if (request.Purpose is not null) |
| | | 181 | | { |
| | 8 | 182 | | metadata["purpose"] = request.Purpose; |
| | | 183 | | } |
| | | 184 | | |
| | 24 | 185 | | foreach (KeyValuePair<string, string> item in request.Metadata) |
| | | 186 | | { |
| | 4 | 187 | | if (string.IsNullOrWhiteSpace(item.Key)) |
| | | 188 | | { |
| | | 189 | | continue; |
| | | 190 | | } |
| | | 191 | | |
| | 4 | 192 | | metadata[item.Key.Trim()] = item.Value?.Trim() ?? string.Empty; |
| | | 193 | | } |
| | | 194 | | |
| | 8 | 195 | | return metadata; |
| | | 196 | | } |
| | | 197 | | |
| | | 198 | | private string? ValidateSigningRequest(SigningRequest request) |
| | | 199 | | { |
| | 8 | 200 | | if (!IsSupportedHashAlgorithm(request.HashAlgorithm)) |
| | | 201 | | { |
| | 2 | 202 | | return "managedkey.signing.hash-algorithm-unsupported"; |
| | | 203 | | } |
| | | 204 | | |
| | 6 | 205 | | string configuredKeyId = NormalizeRequired(options.KeyId, string.Empty); |
| | 6 | 206 | | if (request.KeyId is not null && !string.Equals(request.KeyId, configuredKeyId, StringComparison.Ordinal)) |
| | | 207 | | { |
| | 0 | 208 | | return "managedkey.signing.key-mismatch"; |
| | | 209 | | } |
| | | 210 | | |
| | 6 | 211 | | string? configuredKeyVersion = NormalizeOptional(options.KeyVersion); |
| | 6 | 212 | | return options.RequireKeyVersion && request.KeyVersion is null && configuredKeyVersion is null |
| | 6 | 213 | | ? "managedkey.signing.key-version-missing" |
| | 6 | 214 | | : request.KeyVersion is not null |
| | 6 | 215 | | && configuredKeyVersion is not null |
| | 6 | 216 | | && !string.Equals(request.KeyVersion, configuredKeyVersion, StringComparison.Ordinal) |
| | 6 | 217 | | ? "managedkey.signing.key-version-mismatch" |
| | 6 | 218 | | : null; |
| | | 219 | | } |
| | | 220 | | |
| | | 221 | | private string ResolveKeyId(SigningRequest request) |
| | | 222 | | { |
| | 10 | 223 | | return request.KeyId ?? NormalizeRequired(options.KeyId, string.Empty); |
| | | 224 | | } |
| | | 225 | | |
| | | 226 | | private string? ResolveKeyVersion(SigningRequest request) |
| | | 227 | | { |
| | 10 | 228 | | return request.KeyVersion ?? NormalizeOptional(options.KeyVersion); |
| | | 229 | | } |
| | | 230 | | |
| | | 231 | | private string NormalizeHashAlgorithm(string? hashAlgorithm) |
| | | 232 | | { |
| | 30 | 233 | | string normalized = string.IsNullOrWhiteSpace(hashAlgorithm) |
| | 30 | 234 | | ? options.HashAlgorithm |
| | 30 | 235 | | : hashAlgorithm.Trim(); |
| | | 236 | | |
| | 30 | 237 | | return normalized.Equals("SHA256", StringComparison.OrdinalIgnoreCase) |
| | 30 | 238 | | ? ManagedKeySigningOptions.DefaultHashAlgorithm |
| | 30 | 239 | | : normalized.Equals(ManagedKeySigningOptions.DefaultHashAlgorithm, StringComparison.OrdinalIgnoreCase) |
| | 30 | 240 | | ? ManagedKeySigningOptions.DefaultHashAlgorithm |
| | 30 | 241 | | : normalized; |
| | | 242 | | } |
| | | 243 | | |
| | | 244 | | private bool IsSupportedHashAlgorithm(string? hashAlgorithm) |
| | | 245 | | { |
| | 8 | 246 | | return NormalizeHashAlgorithm(hashAlgorithm).Equals( |
| | 8 | 247 | | NormalizeHashAlgorithm(options.HashAlgorithm), |
| | 8 | 248 | | StringComparison.OrdinalIgnoreCase); |
| | | 249 | | } |
| | | 250 | | |
| | | 251 | | private async ValueTask DelayForRetryAsync(CancellationToken cancellationToken) |
| | | 252 | | { |
| | 2 | 253 | | if (options.RetryDelay > TimeSpan.Zero) |
| | | 254 | | { |
| | 0 | 255 | | await Task.Delay(options.RetryDelay, cancellationToken).ConfigureAwait(false); |
| | | 256 | | } |
| | 2 | 257 | | } |
| | | 258 | | |
| | | 259 | | private static bool IsSafeProviderMetadataKey(string key) |
| | | 260 | | { |
| | 8 | 261 | | return !string.IsNullOrWhiteSpace(key) |
| | 8 | 262 | | && !key.Contains("secret", StringComparison.OrdinalIgnoreCase) |
| | 8 | 263 | | && !key.Contains("token", StringComparison.OrdinalIgnoreCase) |
| | 8 | 264 | | && !key.Contains("credential", StringComparison.OrdinalIgnoreCase) |
| | 8 | 265 | | && !key.Contains("private", StringComparison.OrdinalIgnoreCase) |
| | 8 | 266 | | && !key.Contains("connection", StringComparison.OrdinalIgnoreCase); |
| | | 267 | | } |
| | | 268 | | |
| | | 269 | | private static string NormalizeRequired(string? value, string fallback) |
| | | 270 | | { |
| | 28 | 271 | | return string.IsNullOrWhiteSpace(value) ? fallback : value.Trim(); |
| | | 272 | | } |
| | | 273 | | |
| | | 274 | | private static string? NormalizeOptional(string? value) |
| | | 275 | | { |
| | 8 | 276 | | return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); |
| | | 277 | | } |
| | | 278 | | } |