< Summary

Information
Class: AsiBackbone.Signing.LocalDevelopment.LocalDevelopmentSigningService
Assembly: AsiBackbone.Signing.LocalDevelopment
File(s): /home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Signing.LocalDevelopment/LocalDevelopmentSigningService.cs
Line coverage
94%
Covered lines: 175
Uncovered lines: 10
Coverable lines: 185
Total lines: 425
Line coverage: 94.5%
Branch coverage
89%
Covered branches: 59
Total branches: 66
Branch coverage: 89.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)100%22100%
.ctor()100%11100%
.ctor(...)100%11100%
SignAsync(...)83.33%6696.55%
VerifyAsync(...)100%161690.38%
Dispose()100%22100%
CreateRsa(...)50%2266.67%
ImportRsa(...)100%44100%
NormalizeRequired(...)50%22100%
NormalizeHashAlgorithm(...)100%44100%
IsSupportedHashAlgorithm(...)100%11100%
FixedTimeHashEquals(...)66.67%66100%
ValidateSigningRequest(...)100%1212100%
CreateUnsignedFailureResult(...)100%11100%
CreateBaseMetadata(...)80%1010100%
ThrowIfDisposed()100%11100%

File(s)

/home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Signing.LocalDevelopment/LocalDevelopmentSigningService.cs

#LineLine coverage
 1using System.Security.Cryptography;
 2using System.Text;
 3using AsiBackbone.Core.Signing;
 4
 5namespace AsiBackbone.Signing.LocalDevelopment;
 6
 7/// <summary>
 8/// Provides local-development RSA signing and verification for AsiBackbone signing abstractions.
 9/// </summary>
 10/// <remarks>
 11/// This service generates an in-process RSA key for samples and tests, or uses the key configured through
 12/// <see cref="LocalDevelopmentSigningOptions.RsaKeyPem" /> when one is supplied. It is not a production managed-key pro
 13/// </remarks>
 14public sealed class LocalDevelopmentSigningService : IGovernanceSigningService, IGovernanceSignatureVerificationService,
 15{
 16    private const string SupportedHashAlgorithm = "SHA-256";
 117    private static readonly Encoding SigningEncoding = Encoding.UTF8;
 18
 19    private readonly LocalDevelopmentSigningOptions options;
 20    private readonly TimeProvider timeProvider;
 21    private readonly RSA rsa;
 4822    private readonly Lock rsaSync = new();
 23    private readonly int keySizeBits;
 24    private bool disposed;
 25
 26    /// <summary>
 27    /// Initializes a new instance of the <see cref="LocalDevelopmentSigningService" /> class with default local-develop
 28    /// </summary>
 29    public LocalDevelopmentSigningService()
 1630        : this(LocalDevelopmentSigningOptions.Create())
 31    {
 1632    }
 33
 34    /// <summary>
 35    /// Initializes a new instance of the <see cref="LocalDevelopmentSigningService" /> class.
 36    /// </summary>
 37    /// <exception cref="InvalidOperationException">
 38    /// Thrown when the configured RSA key size is below the supported minimum or is not supported by the platform RSA
 39    /// provider.
 40    /// </exception>
 41    public LocalDevelopmentSigningService(LocalDevelopmentSigningOptions options)
 4342        : this(options, TimeProvider.System)
 43    {
 3344    }
 45
 46    /// <summary>
 47    /// Initializes a new instance of the <see cref="LocalDevelopmentSigningService" /> class with an explicit clock.
 48    /// </summary>
 49    /// <param name="options">The local-development signing options. A snapshot is taken, so later changes to this insta
 50    /// <param name="timeProvider">The clock used to record the signing time in signing metadata.</param>
 51    /// <exception cref="InvalidOperationException">
 52    /// Thrown when the configured RSA key size is below the supported minimum or is not supported by the platform RSA
 53    /// provider.
 54    /// </exception>
 4855    public LocalDevelopmentSigningService(LocalDevelopmentSigningOptions options, TimeProvider timeProvider)
 56    {
 4857        ArgumentNullException.ThrowIfNull(options);
 4858        ArgumentNullException.ThrowIfNull(timeProvider);
 59
 60        // Validate the snapshot rather than the caller's instance, so the values that were checked are the values used.
 4861        LocalDevelopmentSigningOptions snapshot = options.Snapshot();
 4862        snapshot.Validate();
 63
 4364        this.options = snapshot;
 4365        this.timeProvider = timeProvider;
 4366        rsa = string.IsNullOrWhiteSpace(snapshot.RsaKeyPem)
 4367            ? CreateRsa(snapshot.KeySizeBits)
 4368            : ImportRsa(snapshot.RsaKeyPem);
 3869        keySizeBits = rsa.KeySize;
 3870    }
 71
 72    /// <inheritdoc />
 73    public ValueTask<SigningResult> SignAsync(
 74        SigningRequest request,
 75        CancellationToken cancellationToken = default)
 76    {
 4777        ArgumentNullException.ThrowIfNull(request);
 4778        cancellationToken.ThrowIfCancellationRequested();
 79
 4780        string? validationFailure = ValidateSigningRequest(request);
 4781        if (validationFailure is not null)
 82        {
 83            // A host that set ReturnUnsignedOnFailure to false asked to be told when signing did not happen. Returning
 84            // unsigned metadata regardless meant a request-validation failure still produced an artifact whose IsSigned
 85            // was false and that no exception announced.
 2186            return options.ReturnUnsignedOnFailure
 2187                ? ValueTask.FromResult(CreateUnsignedFailureResult(request, validationFailure, validationFailure))
 2188                : throw new InvalidOperationException(
 2189                    $"Local-development signing rejected the signing request: {validationFailure}.");
 90        }
 91
 92        try
 2693        {
 94            lock (rsaSync)
 95            {
 2696                ThrowIfDisposed();
 97
 98                // Sign the exact input Core supplied. For requests built by GovernanceArtifactSigner this is the versio
 99                // input that binds the signing policy context; for requests built without one it is the hash text.
 26100                byte[] signature = rsa.SignData(request.SignatureInput.Span, HashAlgorithmName.SHA256, RSASignaturePaddi
 101
 25102                Dictionary<string, string> metadata = CreateBaseMetadata(request);
 25103                metadata["signing_status"] = "signed";
 104
 25105                var signingMetadata = SigningMetadata.Create(
 25106                    signingHash: request.SigningHash,
 25107                    hashAlgorithm: NormalizeHashAlgorithm(request.HashAlgorithm),
 25108                    signature: Convert.ToBase64String(signature),
 25109                    signatureAlgorithm: NormalizeRequired(options.SignatureAlgorithm, LocalDevelopmentSigningOptions.Def
 25110                    keyId: NormalizeRequired(options.KeyId, LocalDevelopmentSigningOptions.DefaultKeyId),
 25111                    keyVersion: NormalizeRequired(options.KeyVersion, LocalDevelopmentSigningOptions.DefaultKeyVersion),
 25112                    provider: NormalizeRequired(options.ProviderName, LocalDevelopmentSigningOptions.DefaultProviderName
 25113                    signedUtc: timeProvider.GetUtcNow(),
 25114                    metadata: metadata);
 115
 25116                return ValueTask.FromResult(SigningResult.FromMetadata(signingMetadata));
 117            }
 118        }
 1119        catch (Exception exception) when (exception is CryptographicException or ObjectDisposedException or InvalidOpera
 120        {
 1121            if (!options.ReturnUnsignedOnFailure)
 122            {
 0123                throw;
 124            }
 125
 1126            return ValueTask.FromResult(CreateUnsignedFailureResult(request, "localdev.signing.failed", exception.GetTyp
 127        }
 26128    }
 129
 130    /// <inheritdoc />
 131    public ValueTask<SignatureVerificationResult> VerifyAsync(
 132        SignatureVerificationRequest request,
 133        CancellationToken cancellationToken = default)
 134    {
 19135        ArgumentNullException.ThrowIfNull(request);
 19136        cancellationToken.ThrowIfCancellationRequested();
 137
 19138        SigningMetadata metadata = request.SigningMetadata;
 139
 19140        if (!metadata.HasSignature)
 141        {
 1142            return ValueTask.FromResult(SignatureVerificationResult.MissingSignature("The local-development verifier rec
 143        }
 144
 18145        if (!FixedTimeHashEquals(request.SigningHash, metadata.SigningHash))
 146        {
 2147            return ValueTask.FromResult(SignatureVerificationResult.Failed(
 2148                "localdev.signature.hash-mismatch",
 2149                SignatureVerificationCategory.HashMismatch,
 2150                "The verification hash does not match the hash recorded in signing metadata."));
 151        }
 152
 16153        if (!IsSupportedHashAlgorithm(metadata.HashAlgorithm))
 154        {
 1155            return ValueTask.FromResult(SignatureVerificationResult.Failed(
 1156                "localdev.signature.hash-algorithm-unsupported",
 1157                SignatureVerificationCategory.UnsupportedAlgorithm,
 1158                "The local-development verifier supports SHA-256 signing metadata only."));
 159        }
 160
 15161        if (!string.Equals(metadata.SignatureAlgorithm, NormalizeRequired(options.SignatureAlgorithm, LocalDevelopmentSi
 162        {
 1163            return ValueTask.FromResult(SignatureVerificationResult.Failed(
 1164                "localdev.signature.algorithm-mismatch",
 1165                SignatureVerificationCategory.UnsupportedAlgorithm,
 1166                "The signature algorithm does not match the configured local-development provider."));
 167        }
 168
 14169        if (!string.Equals(metadata.KeyId, NormalizeRequired(options.KeyId, LocalDevelopmentSigningOptions.DefaultKeyId)
 14170            || !string.Equals(metadata.KeyVersion, NormalizeRequired(options.KeyVersion, LocalDevelopmentSigningOptions.
 171        {
 2172            return ValueTask.FromResult(SignatureVerificationResult.Failed(
 2173                "localdev.signature.key-mismatch",
 2174                SignatureVerificationCategory.UnknownKeyVersion,
 2175                "The signature key reference does not match the configured local-development provider."));
 176        }
 177
 178        // The provider label is not part of the signature input, so it is authenticated only by this verifier refusing 
 179        // label it does not own. Accepting any label let an artifact signed here claim another provider's identity.
 12180        if (!string.Equals(metadata.Provider, NormalizeRequired(options.ProviderName, LocalDevelopmentSigningOptions.Def
 181        {
 1182            return ValueTask.FromResult(SignatureVerificationResult.Failed(
 1183                "localdev.signature.provider-not-trusted",
 1184                SignatureVerificationCategory.UntrustedSigningContext,
 1185                "The signing provider does not match the configured local-development provider."));
 186        }
 187
 188        try
 11189        {
 190            lock (rsaSync)
 191            {
 11192                ThrowIfDisposed();
 193
 11194                byte[] signature = Convert.FromBase64String(metadata.Signature!);
 10195                bool verified = rsa.VerifyData(request.SignatureInput.Span, signature, HashAlgorithmName.SHA256, RSASign
 196
 10197                return ValueTask.FromResult(verified
 10198                    ? SignatureVerificationResult.Verified()
 10199                    : SignatureVerificationResult.Failed(
 10200                        "localdev.signature.invalid",
 10201                        SignatureVerificationCategory.InvalidSignature,
 10202                        "The local-development signature did not verify."));
 203            }
 204        }
 1205        catch (FormatException)
 206        {
 1207            return ValueTask.FromResult(SignatureVerificationResult.Failed(
 1208                "localdev.signature.malformed",
 1209                SignatureVerificationCategory.InvalidSignature,
 1210                "The signature value is not valid Base64."));
 211        }
 0212        catch (Exception exception) when (exception is CryptographicException or ObjectDisposedException or InvalidOpera
 213        {
 0214            return ValueTask.FromResult(SignatureVerificationResult.Failed(
 0215                "localdev.verification.failed",
 0216                SignatureVerificationCategory.Failed,
 0217                exception.GetType().Name));
 218        }
 11219    }
 220
 221    /// <inheritdoc />
 222    public void Dispose()
 62223    {
 224        lock (rsaSync)
 225        {
 62226            if (disposed)
 227            {
 24228                return;
 229            }
 230
 38231            disposed = true;
 38232            rsa.Dispose();
 38233        }
 62234    }
 235
 236    /// <summary>
 237    /// Creates an RSA key of exactly the requested size.
 238    /// </summary>
 239    /// <remarks>
 240    /// The key size is supplied at creation through <see cref="RSA.Create(int)" /> rather than assigned to
 241    /// <see cref="AsymmetricAlgorithm.KeySize" /> afterwards, whose behavior varies across platform providers. A size t
 242    /// provider rejects is reported as <see cref="InvalidOperationException" /> alongside the other configuration failu
 243    /// and a key whose generated size differs from the request is refused rather than used under a different size.
 244    /// </remarks>
 245    /// <param name="requestedKeySizeBits">The configured RSA key size in bits.</param>
 246    /// <returns>An RSA instance whose key size equals <paramref name="requestedKeySizeBits" />.</returns>
 247    /// <exception cref="InvalidOperationException">Thrown when the platform RSA provider cannot generate the requested 
 248    private static RSA CreateRsa(int requestedKeySizeBits)
 249    {
 250        RSA created;
 251
 252        try
 253        {
 33254            created = RSA.Create(requestedKeySizeBits);
 31255        }
 2256        catch (CryptographicException exception)
 257        {
 2258            throw new InvalidOperationException(
 2259                $"Local-development RSA key size {requestedKeySizeBits} bits is not supported by the platform RSA provid
 2260                exception);
 261        }
 262
 31263        if (created.KeySize != requestedKeySizeBits)
 264        {
 0265            int generatedKeySizeBits = created.KeySize;
 0266            created.Dispose();
 267
 0268            throw new InvalidOperationException(
 0269                $"Local-development RSA key size {requestedKeySizeBits} bits is not supported by the platform RSA provid
 270        }
 271
 31272        return created;
 273    }
 274
 275    /// <summary>
 276    /// Imports the configured PEM-encoded RSA key.
 277    /// </summary>
 278    /// <remarks>
 279    /// Failure messages never include the key text, so a malformed key does not reach logs through the exception.
 280    /// </remarks>
 281    /// <param name="rsaKeyPem">The configured PEM-encoded RSA key.</param>
 282    /// <returns>An RSA instance holding the configured key.</returns>
 283    /// <exception cref="InvalidOperationException">
 284    /// Thrown when the key cannot be imported or is smaller than <see cref="LocalDevelopmentSigningOptions.MinimumKeySi
 285    /// </exception>
 286    private static RSA ImportRsa(string rsaKeyPem)
 287    {
 10288        var imported = RSA.Create();
 289
 290        try
 291        {
 10292            imported.ImportFromPem(rsaKeyPem);
 8293        }
 2294        catch (Exception exception) when (exception is ArgumentException or CryptographicException)
 295        {
 2296            imported.Dispose();
 297
 2298            throw new InvalidOperationException(
 2299                "The configured local-development RSA key could not be imported. Supply an unencrypted PEM-encoded RSA p
 2300                exception is CryptographicException ? exception : null);
 301        }
 302
 8303        if (imported.KeySize < LocalDevelopmentSigningOptions.MinimumKeySizeBits)
 304        {
 1305            int importedKeySizeBits = imported.KeySize;
 1306            imported.Dispose();
 307
 1308            throw new InvalidOperationException(
 1309                $"The configured local-development RSA key is {importedKeySizeBits} bits; at least {LocalDevelopmentSign
 310        }
 311
 7312        return imported;
 313    }
 314
 315    private static string NormalizeRequired(string? value, string fallback)
 316    {
 272317        return string.IsNullOrWhiteSpace(value)
 272318            ? fallback
 272319            : value.Trim();
 320    }
 321
 322    private static string NormalizeHashAlgorithm(string? hashAlgorithm)
 323    {
 93324        return string.IsNullOrWhiteSpace(hashAlgorithm)
 93325            ? SupportedHashAlgorithm
 93326            : hashAlgorithm.Trim().Equals("SHA256", StringComparison.OrdinalIgnoreCase)
 93327                ? SupportedHashAlgorithm
 93328                : hashAlgorithm.Trim();
 329    }
 330
 331    private static bool IsSupportedHashAlgorithm(string? hashAlgorithm)
 332    {
 47333        string normalized = NormalizeHashAlgorithm(hashAlgorithm);
 334
 47335        return normalized.Equals(SupportedHashAlgorithm, StringComparison.OrdinalIgnoreCase);
 336    }
 337
 338    private static bool FixedTimeHashEquals(string? expectedHash, string? actualHash)
 339    {
 18340        if (expectedHash is null || actualHash is null)
 341        {
 1342            return expectedHash is null && actualHash is null;
 343        }
 344
 17345        byte[] expectedBytes = SigningEncoding.GetBytes(expectedHash);
 17346        byte[] actualBytes = SigningEncoding.GetBytes(actualHash);
 347
 17348        return CryptographicOperations.FixedTimeEquals(expectedBytes, actualBytes);
 349    }
 350
 351    private string? ValidateSigningRequest(SigningRequest request)
 352    {
 47353        if (Volatile.Read(ref disposed))
 354        {
 16355            return "localdev.signing.disposed";
 356        }
 357
 31358        if (!IsSupportedHashAlgorithm(request.HashAlgorithm))
 359        {
 3360            return "localdev.signing.hash-algorithm-unsupported";
 361        }
 362
 28363        string configuredKeyId = NormalizeRequired(options.KeyId, LocalDevelopmentSigningOptions.DefaultKeyId);
 28364        if (request.KeyId is not null && !string.Equals(request.KeyId, configuredKeyId, StringComparison.Ordinal))
 365        {
 1366            return "localdev.signing.key-mismatch";
 367        }
 368
 27369        string configuredKeyVersion = NormalizeRequired(options.KeyVersion, LocalDevelopmentSigningOptions.DefaultKeyVer
 27370        return request.KeyVersion is not null && !string.Equals(request.KeyVersion, configuredKeyVersion, StringComparis
 27371            ? "localdev.signing.key-version-mismatch"
 27372            : null;
 373    }
 374
 375    private SigningResult CreateUnsignedFailureResult(SigningRequest request, string failureCode, string failureMessage)
 376    {
 21377        Dictionary<string, string> metadata = CreateBaseMetadata(request);
 21378        metadata["signing_status"] = "failed";
 21379        metadata["failure_code"] = failureCode;
 21380        metadata["failure_message"] = failureMessage;
 381
 21382        var signingMetadata = SigningMetadata.Create(
 21383            signingHash: request.SigningHash,
 21384            hashAlgorithm: NormalizeHashAlgorithm(request.HashAlgorithm),
 21385            keyId: NormalizeRequired(options.KeyId, LocalDevelopmentSigningOptions.DefaultKeyId),
 21386            keyVersion: NormalizeRequired(options.KeyVersion, LocalDevelopmentSigningOptions.DefaultKeyVersion),
 21387            provider: NormalizeRequired(options.ProviderName, LocalDevelopmentSigningOptions.DefaultProviderName),
 21388            metadata: metadata);
 389
 21390        return SigningResult.FromMetadata(signingMetadata);
 391    }
 392
 393    private Dictionary<string, string> CreateBaseMetadata(SigningRequest request)
 394    {
 46395        Dictionary<string, string> metadata = new(StringComparer.Ordinal)
 46396        {
 46397            ["provider_kind"] = "local-development",
 46398            ["provider_warning"] = "local-development-only",
 46399            ["key_algorithm"] = "RSA",
 46400            ["key_size_bits"] = keySizeBits.ToString(System.Globalization.CultureInfo.InvariantCulture)
 46401        };
 402
 46403        if (request.Purpose is not null)
 404        {
 13405            metadata["purpose"] = request.Purpose;
 406        }
 407
 170408        foreach (KeyValuePair<string, string> item in request.Metadata)
 409        {
 39410            if (string.IsNullOrWhiteSpace(item.Key))
 411            {
 412                continue;
 413            }
 414
 39415            metadata[item.Key.Trim()] = item.Value?.Trim() ?? string.Empty;
 416        }
 417
 46418        return metadata;
 419    }
 420
 421    private void ThrowIfDisposed()
 422    {
 37423        ObjectDisposedException.ThrowIf(disposed, this);
 37424    }
 425}