< Summary

Information
Class: AsiBackbone.Core.CapabilityGrants.CapabilityGrant
Assembly: AsiBackbone.Core
File(s): /home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Core/CapabilityGrants/CapabilityGrant.cs
Line coverage
100%
Covered lines: 122
Uncovered lines: 0
Coverable lines: 122
Total lines: 318
Line coverage: 100%
Branch coverage
100%
Covered branches: 34
Total branches: 34
Branch coverage: 100%
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%1010100%
get_HasAcknowledgmentReference()100%11100%
get_HasHandshakeReference()100%11100%
get_HasMetadata()100%11100%
Create(...)100%44100%
WithSchemaVersion(...)100%22100%
NormalizeScopes(...)100%22100%
NormalizeMetadata(...)100%1414100%
NormalizeOptional(...)100%22100%

File(s)

/home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Core/CapabilityGrants/CapabilityGrant.cs

#LineLine coverage
 1using System.Collections.ObjectModel;
 2using AsiBackbone.Core.Serialization;
 3
 4namespace AsiBackbone.Core.CapabilityGrants;
 5
 6/// <summary>
 7/// Represents a provider-neutral, short-lived capability grant for follow-on governed execution.
 8/// </summary>
 9/// <remarks>
 10/// The grant is a metadata model, not a bearer-token format. Hosts decide how this grant is serialized,
 11/// transported, protected, and bound to their authentication and authorization systems. A signed grant can be carried
 12/// with <see cref="CapabilityGrantToken" />, which is one versioned transport form rather than a requirement.
 13/// </remarks>
 14public sealed class CapabilityGrant
 15{
 316    private static readonly ReadOnlyCollection<string> EmptyScopes =
 317        Array.AsReadOnly(Array.Empty<string>());
 18
 319    private static readonly IReadOnlyDictionary<string, string> EmptyMetadata =
 320        new ReadOnlyDictionary<string, string>(
 321            new Dictionary<string, string>(StringComparer.Ordinal));
 22
 47523    private CapabilityGrant(
 47524        string tokenId,
 47525        string issuer,
 47526        string audience,
 47527        IReadOnlyList<string> scopes,
 47528        DateTimeOffset issuedUtc,
 47529        DateTimeOffset? notBeforeUtc,
 47530        DateTimeOffset expiresUtc,
 47531        string? subjectId,
 47532        string? operationName,
 47533        string? policyVersion,
 47534        string? policyHash,
 47535        string? acknowledgmentId,
 47536        string? handshakeId,
 47537        string? gatewayBinding,
 47538        string? resourceBinding,
 47539        IReadOnlyDictionary<string, string> metadata,
 47540        int? maxUseCount,
 47541        string? schemaVersion)
 42    {
 47543        ArgumentException.ThrowIfNullOrWhiteSpace(tokenId);
 47544        ArgumentException.ThrowIfNullOrWhiteSpace(issuer);
 47545        ArgumentException.ThrowIfNullOrWhiteSpace(audience);
 47546        ArgumentNullException.ThrowIfNull(scopes);
 47
 47548        if (scopes.Count == 0)
 49        {
 150            throw new ArgumentException("At least one capability scope is required.", nameof(scopes));
 51        }
 52
 47453        DateTimeOffset normalizedIssuedUtc = issuedUtc.ToUniversalTime();
 47454        DateTimeOffset? normalizedNotBeforeUtc = notBeforeUtc?.ToUniversalTime();
 47455        DateTimeOffset normalizedExpiresUtc = expiresUtc.ToUniversalTime();
 56
 47457        if (normalizedNotBeforeUtc.HasValue && normalizedNotBeforeUtc.Value > normalizedExpiresUtc)
 58        {
 259            throw new ArgumentOutOfRangeException(nameof(notBeforeUtc), notBeforeUtc, "Not-before time must be earlier t
 60        }
 61
 47262        if (normalizedIssuedUtc > normalizedExpiresUtc)
 63        {
 164            throw new ArgumentOutOfRangeException(nameof(expiresUtc), expiresUtc, "Expiration time must be later than or
 65        }
 66
 47167        TokenId = tokenId.Trim();
 47168        Issuer = issuer.Trim();
 47169        Audience = audience.Trim();
 47170        Scopes = scopes;
 47171        IssuedUtc = normalizedIssuedUtc;
 47172        NotBeforeUtc = normalizedNotBeforeUtc;
 47173        ExpiresUtc = normalizedExpiresUtc;
 47174        SubjectId = NormalizeOptional(subjectId);
 47175        OperationName = NormalizeOptional(operationName);
 47176        PolicyVersion = NormalizeOptional(policyVersion);
 47177        PolicyHash = NormalizeOptional(policyHash);
 47178        AcknowledgmentId = NormalizeOptional(acknowledgmentId);
 47179        HandshakeId = NormalizeOptional(handshakeId);
 47180        GatewayBinding = NormalizeOptional(gatewayBinding);
 47181        ResourceBinding = NormalizeOptional(resourceBinding);
 47182        Metadata = metadata;
 47183        MaxUseCount = maxUseCount;
 47184        SchemaVersion = GovernanceSchemaVersions.Normalize(schemaVersion);
 47185    }
 86
 87    /// <summary>
 88    /// Gets the maximum number of times the issuer permits this grant to be used, when the issuer bound one.
 89    /// </summary>
 90    /// <remarks>
 91    /// A use limit supplied only at the validation call site is a local policy choice that the issuer never authorized 
 92    /// that nothing in the signature covers. When this value is present it is part of the signed payload, so a relying
 93    /// party cannot widen it. Validation uses the narrower of this value and any limit the caller supplies.
 94    /// </remarks>
 95    public int? MaxUseCount { get; }
 96
 97    /// <summary>
 98    /// Gets the stable grant identifier used for validation and replay checks.
 99    /// </summary>
 100    public string TokenId { get; }
 101
 102    /// <summary>
 103    /// Gets the issuer that created the grant.
 104    /// </summary>
 105    public string Issuer { get; }
 106
 107    /// <summary>
 108    /// Gets the intended audience for the grant.
 109    /// </summary>
 110    public string Audience { get; }
 111
 112    /// <summary>
 113    /// Gets the least-privilege scopes carried by the grant.
 114    /// </summary>
 115    public IReadOnlyList<string> Scopes { get; }
 116
 117    /// <summary>
 118    /// Gets the UTC timestamp when the grant was issued.
 119    /// </summary>
 120    public DateTimeOffset IssuedUtc { get; }
 121
 122    /// <summary>
 123    /// Gets the UTC timestamp before which the grant is not valid.
 124    /// </summary>
 125    public DateTimeOffset? NotBeforeUtc { get; }
 126
 127    /// <summary>
 128    /// Gets the UTC timestamp when the grant expires.
 129    /// </summary>
 130    public DateTimeOffset ExpiresUtc { get; }
 131
 132    /// <summary>
 133    /// Gets the host-defined subject identifier, when supplied.
 134    /// </summary>
 135    public string? SubjectId { get; }
 136
 137    /// <summary>
 138    /// Gets the operation name or action family the grant is intended to authorize.
 139    /// </summary>
 140    public string? OperationName { get; }
 141
 142    /// <summary>
 143    /// Gets the policy version bound to the grant, when supplied.
 144    /// </summary>
 145    public string? PolicyVersion { get; }
 146
 147    /// <summary>
 148    /// Gets the policy hash bound to the grant, when supplied.
 149    /// </summary>
 150    public string? PolicyHash { get; }
 151
 152    /// <summary>
 153    /// Gets the acknowledgment identifier bound to the grant, when supplied.
 154    /// </summary>
 155    public string? AcknowledgmentId { get; }
 156
 157    /// <summary>
 158    /// Gets the handshake identifier bound to the grant, when supplied.
 159    /// </summary>
 160    public string? HandshakeId { get; }
 161
 162    /// <summary>
 163    /// Gets the optional gateway binding used to limit execution context.
 164    /// </summary>
 165    public string? GatewayBinding { get; }
 166
 167    /// <summary>
 168    /// Gets the optional resource binding used to limit the target resource.
 169    /// </summary>
 170    public string? ResourceBinding { get; }
 171
 172    /// <summary>
 173    /// Gets the canonical schema version for this grant.
 174    /// </summary>
 175    public string SchemaVersion { get; }
 176
 177    /// <summary>
 178    /// Gets provider-neutral metadata carried with the grant.
 179    /// </summary>
 180    public IReadOnlyDictionary<string, string> Metadata { get; }
 181
 182    /// <summary>
 183    /// Gets a value indicating whether an acknowledgment reference is present.
 184    /// </summary>
 4185    public bool HasAcknowledgmentReference => AcknowledgmentId is not null;
 186
 187    /// <summary>
 188    /// Gets a value indicating whether a handshake reference is present.
 189    /// </summary>
 2190    public bool HasHandshakeReference => HandshakeId is not null;
 191
 192    /// <summary>
 193    /// Gets a value indicating whether additional metadata is present.
 194    /// </summary>
 2195    public bool HasMetadata => Metadata.Count > 0;
 196
 197    /// <summary>
 198    /// Creates a provider-neutral capability grant.
 199    /// </summary>
 200    public static CapabilityGrant Create(
 201        string tokenId,
 202        string issuer,
 203        string audience,
 204        IEnumerable<string> scopes,
 205        DateTimeOffset issuedUtc,
 206        DateTimeOffset expiresUtc,
 207        DateTimeOffset? notBeforeUtc = null,
 208        string? subjectId = null,
 209        string? operationName = null,
 210        string? policyVersion = null,
 211        string? policyHash = null,
 212        string? acknowledgmentId = null,
 213        string? handshakeId = null,
 214        string? gatewayBinding = null,
 215        string? resourceBinding = null,
 216        IReadOnlyDictionary<string, string>? metadata = null,
 217        int? maxUseCount = null,
 218        string? schemaVersion = null)
 219    {
 408220        return maxUseCount is < 1
 408221            ? throw new ArgumentOutOfRangeException(nameof(maxUseCount), maxUseCount, "A bound use limit must be greater
 408222            : new CapabilityGrant(
 408223            tokenId,
 408224            issuer,
 408225            audience,
 408226            NormalizeScopes(scopes),
 408227            issuedUtc,
 408228            notBeforeUtc,
 408229            expiresUtc,
 408230            subjectId,
 408231            operationName,
 408232            policyVersion,
 408233            policyHash,
 408234            acknowledgmentId,
 408235            handshakeId,
 408236            gatewayBinding,
 408237            resourceBinding,
 408238            NormalizeMetadata(metadata),
 408239            maxUseCount,
 408240            schemaVersion);
 241    }
 242
 243    /// <summary>
 244    /// Returns this grant when it already records <paramref name="schemaVersion" />, or an otherwise identical grant
 245    /// that records it.
 246    /// </summary>
 247    internal CapabilityGrant WithSchemaVersion(string schemaVersion)
 248    {
 71249        return string.Equals(SchemaVersion, GovernanceSchemaVersions.Normalize(schemaVersion), StringComparison.Ordinal)
 71250            ? this
 71251            : new CapabilityGrant(
 71252                TokenId,
 71253                Issuer,
 71254                Audience,
 71255                Scopes,
 71256                IssuedUtc,
 71257                NotBeforeUtc,
 71258                ExpiresUtc,
 71259                SubjectId,
 71260                OperationName,
 71261                PolicyVersion,
 71262                PolicyHash,
 71263                AcknowledgmentId,
 71264                HandshakeId,
 71265                GatewayBinding,
 71266                ResourceBinding,
 71267                Metadata,
 71268                MaxUseCount,
 71269                schemaVersion);
 270    }
 271
 272    private static ReadOnlyCollection<string> NormalizeScopes(IEnumerable<string> scopes)
 273    {
 406274        ArgumentNullException.ThrowIfNull(scopes);
 275
 405276        string[] normalizedScopes = [.. scopes
 405277            .Where(scope => !string.IsNullOrWhiteSpace(scope))
 405278            .Select(scope => scope.Trim())
 405279            .Distinct(StringComparer.Ordinal)
 405280            .OrderBy(scope => scope, StringComparer.Ordinal)];
 281
 405282        return normalizedScopes.Length == 0
 405283            ? EmptyScopes
 405284            : Array.AsReadOnly(normalizedScopes);
 285    }
 286
 287    private static IReadOnlyDictionary<string, string> NormalizeMetadata(
 288        IReadOnlyDictionary<string, string>? metadata)
 289    {
 405290        if (metadata is null || metadata.Count == 0)
 291        {
 397292            return EmptyMetadata;
 293        }
 294
 8295        Dictionary<string, string> normalizedMetadata = new(StringComparer.Ordinal);
 296
 38297        foreach (KeyValuePair<string, string> item in metadata)
 298        {
 11299            if (string.IsNullOrWhiteSpace(item.Key))
 300            {
 301                continue;
 302            }
 303
 9304            normalizedMetadata[item.Key.Trim()] = item.Value?.Trim() ?? string.Empty;
 305        }
 306
 8307        return normalizedMetadata.Count == 0
 8308            ? EmptyMetadata
 8309            : new ReadOnlyDictionary<string, string>(normalizedMetadata);
 310    }
 311
 312    private static string? NormalizeOptional(string? value)
 313    {
 3768314        return string.IsNullOrWhiteSpace(value)
 3768315            ? null
 3768316            : value.Trim();
 317    }
 318}