< Summary

Information
Class: AsiBackbone.Core.CapabilityGrants.CapabilityGrantToken
Assembly: AsiBackbone.Core
File(s): /home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Core/CapabilityGrants/CapabilityGrantToken.cs
Line coverage
97%
Covered lines: 273
Uncovered lines: 6
Coverable lines: 279
Total lines: 610
Line coverage: 97.8%
Branch coverage
81%
Covered branches: 91
Total branches: 112
Branch coverage: 81.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
Encode(...)83.33%121296.55%
Decode(...)87.5%161696.88%
DecodeDocument(...)75%121298.41%
WriteGrant(...)80%1010100%
WriteProof(...)83.33%66100%
WriteOptionalString(...)100%22100%
FilterGrantMetadata(...)100%44100%
FormatTimestamp(...)100%11100%
Malformed(...)100%11100%
RequireObject(...)100%22100%
RejectUnknownProperties(...)100%44100%
GetRequiredObject(...)75%44100%
GetRequiredString(...)100%22100%
GetOptionalString(...)83.33%66100%
GetRequiredStringArray(...)75%8887.5%
GetOptionalStringMap(...)80%111080%
GetOptionalInt32(...)62.5%88100%
GetRequiredTimestamp(...)50%22100%
GetOptionalTimestamp(...)75%44100%
.ctor(...)100%11100%

File(s)

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

#LineLine coverage
 1using System.Buffers;
 2using System.Buffers.Text;
 3using System.Globalization;
 4using System.Text.Json;
 5using AsiBackbone.Core.Signing;
 6
 7namespace AsiBackbone.Core.CapabilityGrants;
 8
 9/// <summary>
 10/// Encodes and decodes the versioned, size-limited transport form of a signed capability grant.
 11/// </summary>
 12/// <remarks>
 13/// <para>
 14/// A token is the prefix <see cref="FormatPrefix" /> followed by the unpadded base64url encoding of a UTF-8 JSON
 15/// document. The document carries format version <see cref="FormatVersion" />, every grant field, and the signing
 16/// metadata a verifier needs. It does not carry the canonical payload or its hash: <see cref="Decode" /> rebuilds both 
 17/// the decoded grant fields, so editing any field after signing, including the resource binding, yields a hash the
 18/// signature does not cover.
 19/// </para>
 20/// <para>
 21/// The token is not encrypted. Every field is readable by anyone who holds it, so a grant must not carry secrets.
 22/// Decoding is strict: unknown properties, duplicate properties, an unsupported format version, or a token longer
 23/// than the configured limit fail rather than being ignored. A successful decode is not verification; validate the
 24/// result with <see cref="CapabilityGrantValidator.ValidateAsync" /> before trusting it.
 25/// </para>
 26/// <para>
 27/// Grant metadata is transported only for keys that the canonical payload options allow, because only those keys are
 28/// covered by the signature. The issuer and the relying party must use the same <see cref="CanonicalPayloadOptions" />.
 29/// </para>
 30/// </remarks>
 31public static class CapabilityGrantToken
 32{
 33    /// <summary>
 34    /// Gets the prefix that identifies a version 1 capability grant token.
 35    /// </summary>
 36    public const string FormatPrefix = "asibcg1.";
 37
 38    /// <summary>
 39    /// Gets the token format version written into, and required in, the token document.
 40    /// </summary>
 41    public const int FormatVersion = 1;
 42
 43    /// <summary>
 44    /// Gets the default maximum token length, in characters, accepted by <see cref="Decode" /> and produced by
 45    /// <see cref="Encode" />.
 46    /// </summary>
 47    public const int DefaultMaxTokenLength = 8 * 1024;
 48
 49    /// <summary>
 50    /// The failure code returned when no token was supplied.
 51    /// </summary>
 52    public const string MissingFailureCode = "capability.token-missing";
 53
 54    /// <summary>
 55    /// The failure code returned when the token exceeds the configured maximum length.
 56    /// </summary>
 57    public const string TooLargeFailureCode = "capability.token-too-large";
 58
 59    /// <summary>
 60    /// The failure code returned when the token prefix or format version is not supported.
 61    /// </summary>
 62    public const string UnsupportedFormatFailureCode = "capability.token-format-unsupported";
 63
 64    /// <summary>
 65    /// The failure code returned when the token is not valid base64url, JSON, or token structure.
 66    /// </summary>
 67    public const string MalformedFailureCode = "capability.token-malformed";
 68
 69    /// <summary>
 70    /// The failure code returned when the token fields do not form a valid capability grant.
 71    /// </summary>
 72    public const string InvalidGrantFailureCode = "capability.token-grant-invalid";
 73
 74    /// <summary>
 75    /// The failure code returned when the token names a hash algorithm the built-in hasher cannot rebuild.
 76    /// </summary>
 77    public const string UnsupportedHashAlgorithmFailureCode = "capability.token-hash-algorithm-unsupported";
 78
 79    private const int MaxDocumentDepth = 4;
 80    private const string TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'";
 81
 82    // These descriptors are derived from the rebuilt canonical hash. Reading them from the token would let a token
 83    // describe an artifact other than the one rebuilt from its fields.
 284    private static readonly HashSet<string> DerivedSigningMetadataKeys = new(StringComparer.Ordinal)
 285    {
 286        "artifact_id",
 287        "artifact_type",
 288        "canonicalization_version",
 289        "payload_schema_version"
 290    };
 91
 292    private static readonly HashSet<string> DocumentProperties = new(StringComparer.Ordinal) { "v", "grant", "proof" };
 93
 294    private static readonly HashSet<string> GrantProperties = new(StringComparer.Ordinal)
 295    {
 296        "acknowledgmentId",
 297        "audience",
 298        "expiresUtc",
 299        "gatewayBinding",
 2100        "handshakeId",
 2101        "issuedUtc",
 2102        "issuer",
 2103        "maxUseCount",
 2104        "metadata",
 2105        "notBeforeUtc",
 2106        "operationName",
 2107        "policyHash",
 2108        "policyVersion",
 2109        "resourceBinding",
 2110        "schemaVersion",
 2111        "scopes",
 2112        "subjectId",
 2113        "tokenId"
 2114    };
 115
 2116    private static readonly HashSet<string> ProofProperties = new(StringComparer.Ordinal)
 2117    {
 2118        "hashAlgorithm",
 2119        "keyId",
 2120        "keyVersion",
 2121        "metadata",
 2122        "provider",
 2123        "signature",
 2124        "signatureAlgorithm",
 2125        "signedUtc"
 2126    };
 127
 128    /// <summary>
 129    /// Encodes a signed capability grant as a version 1 token.
 130    /// </summary>
 131    /// <param name="signedGrant">The signed grant, typically from <see cref="GovernanceArtifactSigner.SignCapabilityGra
 132    /// <param name="options">The canonical payload options the grant was signed with; defaults apply when <see langword
 133    /// <param name="maxTokenLength">The maximum token length in characters.</param>
 134    /// <returns>The encoded token.</returns>
 135    /// <exception cref="ArgumentNullException"><paramref name="signedGrant" /> is <see langword="null" />.</exception>
 136    /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxTokenLength" /> is less than one.</exception>
 137    /// <exception cref="ArgumentException">
 138    /// The artifact is not a capability grant, or its canonical hash does not match the grant rebuilt with
 139    /// <paramref name="options" />, so the token could never verify.
 140    /// </exception>
 141    /// <exception cref="InvalidOperationException">The grant is not signed, or the token would exceed <paramref name="m
 142    public static string Encode(
 143        SignedGovernanceArtifact<CapabilityGrant> signedGrant,
 144        CanonicalPayloadOptions? options = null,
 145        int maxTokenLength = DefaultMaxTokenLength)
 146    {
 68147        ArgumentNullException.ThrowIfNull(signedGrant);
 68148        ArgumentOutOfRangeException.ThrowIfLessThan(maxTokenLength, 1);
 149
 67150        CapabilityGrant grant = signedGrant.Artifact;
 151
 67152        if (!string.Equals(signedGrant.ArtifactType, CanonicalArtifactTypes.CapabilityGrant, StringComparison.Ordinal)
 67153            || !string.Equals(signedGrant.ArtifactId, grant.TokenId, StringComparison.Ordinal))
 154        {
 0155            throw new ArgumentException("The signed artifact does not describe this capability grant.", nameof(signedGra
 156        }
 157
 67158        if (!signedGrant.IsSigned)
 159        {
 1160            throw new InvalidOperationException("Only a signed capability grant can be encoded as a token.");
 161        }
 162
 66163        CanonicalPayloadOptions effectiveOptions = options ?? CanonicalPayloadOptions.Default;
 66164        CanonicalPayloadHash rebuiltHash = CanonicalPayloadHasher.ComputeHash(
 66165            CanonicalPayloadBuilder.ForCapabilityGrant(grant, effectiveOptions),
 66166            signedGrant.HashAlgorithm);
 167
 66168        if (!string.Equals(rebuiltHash.HashValue, signedGrant.CanonicalHash.HashValue, StringComparison.Ordinal))
 169        {
 1170            throw new ArgumentException(
 1171                "The grant rebuilt with the supplied canonical payload options does not hash to the signed hash. Pass th
 1172                nameof(options));
 173        }
 174
 65175        ArrayBufferWriter<byte> buffer = new();
 65176        using (Utf8JsonWriter writer = new(buffer))
 177        {
 65178            writer.WriteStartObject();
 65179            writer.WriteNumber("v", FormatVersion);
 65180            WriteGrant(writer, grant, effectiveOptions);
 65181            WriteProof(writer, signedGrant);
 65182            writer.WriteEndObject();
 65183        }
 184
 65185        string token = FormatPrefix + Base64Url.EncodeToString(buffer.WrittenSpan);
 186
 65187        return token.Length > maxTokenLength
 65188            ? throw new InvalidOperationException(
 65189                $"The encoded capability grant token is {token.Length} characters, which exceeds the {maxTokenLength}-ch
 65190            : token;
 191    }
 192
 193    /// <summary>
 194    /// Decodes a version 1 token into a signed capability grant whose canonical payload and hash are rebuilt from the
 195    /// decoded fields.
 196    /// </summary>
 197    /// <remarks>
 198    /// Decoding never throws for token content. Every malformed, oversized, or unsupported token produces a failed
 199    /// result with a stable failure code.
 200    /// </remarks>
 201    /// <param name="token">The token to decode.</param>
 202    /// <param name="options">The canonical payload options the issuer signed with; defaults apply when <see langword="n
 203    /// <param name="maxTokenLength">The maximum accepted token length in characters.</param>
 204    /// <returns>The decode result.</returns>
 205    /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxTokenLength" /> is less than one.</exception>
 206    public static CapabilityGrantTokenDecodeResult Decode(
 207        string? token,
 208        CanonicalPayloadOptions? options = null,
 209        int maxTokenLength = DefaultMaxTokenLength)
 210    {
 88211        ArgumentOutOfRangeException.ThrowIfLessThan(maxTokenLength, 1);
 212
 87213        if (string.IsNullOrWhiteSpace(token))
 214        {
 2215            return CapabilityGrantTokenDecodeResult.Failure(MissingFailureCode, "No capability grant token was supplied.
 216        }
 217
 85218        string trimmed = token.Trim();
 219
 85220        if (trimmed.Length > maxTokenLength)
 221        {
 1222            return CapabilityGrantTokenDecodeResult.Failure(
 1223                TooLargeFailureCode,
 1224                $"The capability grant token exceeds the {maxTokenLength}-character limit.");
 225        }
 226
 84227        if (!trimmed.StartsWith(FormatPrefix, StringComparison.Ordinal))
 228        {
 1229            return CapabilityGrantTokenDecodeResult.Failure(
 1230                UnsupportedFormatFailureCode,
 1231                "The capability grant token does not use a supported format prefix.");
 232        }
 233
 83234        ReadOnlySpan<char> encoded = trimmed.AsSpan(FormatPrefix.Length);
 235
 83236        if (encoded.IsEmpty || !Base64Url.IsValid(encoded, out int decodedLength))
 237        {
 3238            return Malformed("The capability grant token body is not valid base64url.");
 239        }
 240
 80241        byte[] documentBytes = new byte[decodedLength];
 242
 80243        if (!Base64Url.TryDecodeFromChars(encoded, documentBytes, out int bytesWritten) || bytesWritten != decodedLength
 244        {
 0245            return Malformed("The capability grant token body is not valid base64url.");
 246        }
 247
 248        try
 249        {
 80250            using var document = JsonDocument.Parse(
 80251                documentBytes,
 80252                new JsonDocumentOptions
 80253                {
 80254                    MaxDepth = MaxDocumentDepth,
 80255                    AllowTrailingCommas = false,
 80256                    CommentHandling = JsonCommentHandling.Disallow,
 80257                    AllowDuplicateProperties = false
 80258                });
 259
 77260            return DecodeDocument(document.RootElement, options ?? CanonicalPayloadOptions.Default);
 261        }
 3262        catch (JsonException)
 263        {
 3264            return Malformed("The capability grant token body is not a valid token document.");
 265        }
 266        catch (TokenStructureException exception)
 267        {
 9268            return Malformed(exception.Message);
 269        }
 80270    }
 271
 272    private static CapabilityGrantTokenDecodeResult DecodeDocument(JsonElement root, CanonicalPayloadOptions options)
 273    {
 77274        RequireObject(root, "token document");
 76275        RejectUnknownProperties(root, DocumentProperties, "token document");
 276
 74277        if (!root.TryGetProperty("v", out JsonElement versionElement)
 74278            || versionElement.ValueKind is not JsonValueKind.Number
 74279            || !versionElement.TryGetInt32(out int version))
 280        {
 0281            throw new TokenStructureException("The capability grant token document has no format version.");
 282        }
 283
 74284        if (version != FormatVersion)
 285        {
 1286            return CapabilityGrantTokenDecodeResult.Failure(
 1287                UnsupportedFormatFailureCode,
 1288                "The capability grant token format version is not supported.");
 289        }
 290
 73291        JsonElement grantElement = GetRequiredObject(root, "grant", "token document");
 72292        JsonElement proofElement = GetRequiredObject(root, "proof", "token document");
 72293        RejectUnknownProperties(grantElement, GrantProperties, "grant");
 71294        RejectUnknownProperties(proofElement, ProofProperties, "proof");
 295
 296        CapabilityGrant grant;
 297
 298        try
 299        {
 71300            grant = CapabilityGrant.Create(
 71301                tokenId: GetRequiredString(grantElement, "tokenId"),
 71302                issuer: GetRequiredString(grantElement, "issuer"),
 71303                audience: GetRequiredString(grantElement, "audience"),
 71304                scopes: GetRequiredStringArray(grantElement, "scopes"),
 71305                issuedUtc: GetRequiredTimestamp(grantElement, "issuedUtc"),
 71306                expiresUtc: GetRequiredTimestamp(grantElement, "expiresUtc"),
 71307                notBeforeUtc: GetOptionalTimestamp(grantElement, "notBeforeUtc"),
 71308                subjectId: GetOptionalString(grantElement, "subjectId"),
 71309                operationName: GetOptionalString(grantElement, "operationName"),
 71310                policyVersion: GetOptionalString(grantElement, "policyVersion"),
 71311                policyHash: GetOptionalString(grantElement, "policyHash"),
 71312                acknowledgmentId: GetOptionalString(grantElement, "acknowledgmentId"),
 71313                handshakeId: GetOptionalString(grantElement, "handshakeId"),
 71314                gatewayBinding: GetOptionalString(grantElement, "gatewayBinding"),
 71315                resourceBinding: GetOptionalString(grantElement, "resourceBinding"),
 71316                metadata: FilterGrantMetadata(GetOptionalStringMap(grantElement, "metadata"), options),
 71317                maxUseCount: GetOptionalInt32(grantElement, "maxUseCount"),
 71318                schemaVersion: GetRequiredString(grantElement, "schemaVersion"));
 65319        }
 2320        catch (ArgumentException)
 321        {
 2322            return CapabilityGrantTokenDecodeResult.Failure(
 2323                InvalidGrantFailureCode,
 2324                "The capability grant token fields do not form a valid capability grant.");
 325        }
 326
 65327        string hashAlgorithm = GetRequiredString(proofElement, "hashAlgorithm");
 65328        CanonicalPayload payload = CanonicalPayloadBuilder.ForCapabilityGrant(grant, options);
 329        CanonicalPayloadHash hash;
 330
 331        try
 332        {
 65333            hash = CanonicalPayloadHasher.ComputeHash(payload, hashAlgorithm);
 64334        }
 1335        catch (NotSupportedException)
 336        {
 1337            return CapabilityGrantTokenDecodeResult.Failure(
 1338                UnsupportedHashAlgorithmFailureCode,
 1339                "The capability grant token names a hash algorithm the built-in hasher does not support.");
 340        }
 341
 64342        Dictionary<string, string> signingMetadata = new(StringComparer.Ordinal);
 343
 134344        foreach (KeyValuePair<string, string> item in GetOptionalStringMap(proofElement, "metadata"))
 345        {
 3346            if (!DerivedSigningMetadataKeys.Contains(item.Key.Trim()))
 347            {
 1348                signingMetadata[item.Key] = item.Value;
 349            }
 350        }
 351
 64352        var metadata = SigningMetadata.Create(
 64353            signingHash: hash.HashValue,
 64354            hashAlgorithm: hash.HashAlgorithm,
 64355            signature: GetOptionalString(proofElement, "signature"),
 64356            signatureAlgorithm: GetOptionalString(proofElement, "signatureAlgorithm"),
 64357            keyId: GetOptionalString(proofElement, "keyId"),
 64358            keyVersion: GetOptionalString(proofElement, "keyVersion"),
 64359            provider: GetOptionalString(proofElement, "provider"),
 64360            signedUtc: GetOptionalTimestamp(proofElement, "signedUtc"),
 64361            metadata: signingMetadata);
 362
 64363        return CapabilityGrantTokenDecodeResult.Success(
 64364            SignedGovernanceArtifacts.FromSigningMetadata(grant, payload, hash, metadata));
 3365    }
 366
 367    private static void WriteGrant(Utf8JsonWriter writer, CapabilityGrant grant, CanonicalPayloadOptions options)
 368    {
 65369        writer.WriteStartObject("grant");
 65370        WriteOptionalString(writer, "acknowledgmentId", grant.AcknowledgmentId);
 65371        writer.WriteString("audience", grant.Audience);
 65372        writer.WriteString("expiresUtc", FormatTimestamp(grant.ExpiresUtc));
 65373        WriteOptionalString(writer, "gatewayBinding", grant.GatewayBinding);
 65374        WriteOptionalString(writer, "handshakeId", grant.HandshakeId);
 65375        writer.WriteString("issuedUtc", FormatTimestamp(grant.IssuedUtc));
 65376        writer.WriteString("issuer", grant.Issuer);
 377
 65378        if (grant.MaxUseCount.HasValue)
 379        {
 65380            writer.WriteNumber("maxUseCount", grant.MaxUseCount.Value);
 381        }
 382
 65383        Dictionary<string, string> boundMetadata = FilterGrantMetadata(grant.Metadata, options);
 65384        if (boundMetadata.Count > 0)
 385        {
 1386            writer.WriteStartObject("metadata");
 4387            foreach (KeyValuePair<string, string> item in boundMetadata.OrderBy(item => item.Key, StringComparer.Ordinal
 388            {
 1389                writer.WriteString(item.Key, item.Value);
 390            }
 391
 1392            writer.WriteEndObject();
 393        }
 394
 65395        if (grant.NotBeforeUtc.HasValue)
 396        {
 65397            writer.WriteString("notBeforeUtc", FormatTimestamp(grant.NotBeforeUtc.Value));
 398        }
 399
 65400        WriteOptionalString(writer, "operationName", grant.OperationName);
 65401        WriteOptionalString(writer, "policyHash", grant.PolicyHash);
 65402        WriteOptionalString(writer, "policyVersion", grant.PolicyVersion);
 65403        WriteOptionalString(writer, "resourceBinding", grant.ResourceBinding);
 65404        writer.WriteString("schemaVersion", grant.SchemaVersion);
 65405        writer.WriteStartArray("scopes");
 260406        foreach (string scope in grant.Scopes)
 407        {
 65408            writer.WriteStringValue(scope);
 409        }
 410
 65411        writer.WriteEndArray();
 65412        WriteOptionalString(writer, "subjectId", grant.SubjectId);
 65413        writer.WriteString("tokenId", grant.TokenId);
 65414        writer.WriteEndObject();
 65415    }
 416
 417    private static void WriteProof(Utf8JsonWriter writer, SignedGovernanceArtifact<CapabilityGrant> signedGrant)
 418    {
 65419        SigningMetadata signing = signedGrant.SigningMetadata;
 420
 65421        writer.WriteStartObject("proof");
 65422        writer.WriteString("hashAlgorithm", signedGrant.HashAlgorithm);
 65423        WriteOptionalString(writer, "keyId", signing.KeyId);
 65424        WriteOptionalString(writer, "keyVersion", signing.KeyVersion);
 425
 65426        KeyValuePair<string, string>[] transportedMetadata = [.. signing.Metadata
 65427            .Where(item => !DerivedSigningMetadataKeys.Contains(item.Key))
 65428            .OrderBy(item => item.Key, StringComparer.Ordinal)];
 429
 65430        if (transportedMetadata.Length > 0)
 431        {
 1432            writer.WriteStartObject("metadata");
 4433            foreach (KeyValuePair<string, string> item in transportedMetadata)
 434            {
 1435                writer.WriteString(item.Key, item.Value);
 436            }
 437
 1438            writer.WriteEndObject();
 439        }
 440
 65441        WriteOptionalString(writer, "provider", signing.Provider);
 65442        WriteOptionalString(writer, "signature", signing.Signature);
 65443        WriteOptionalString(writer, "signatureAlgorithm", signing.SignatureAlgorithm);
 444
 65445        if (signing.SignedUtc.HasValue)
 446        {
 65447            writer.WriteString("signedUtc", FormatTimestamp(signing.SignedUtc.Value));
 448        }
 449
 65450        writer.WriteEndObject();
 65451    }
 452
 453    private static void WriteOptionalString(Utf8JsonWriter writer, string propertyName, string? value)
 454    {
 845455        if (value is not null)
 456        {
 718457            writer.WriteString(propertyName, value);
 458        }
 845459    }
 460
 461    private static Dictionary<string, string> FilterGrantMetadata(
 462        IReadOnlyDictionary<string, string> metadata,
 463        CanonicalPayloadOptions options)
 464    {
 133465        Dictionary<string, string> filtered = new(StringComparer.Ordinal);
 466
 272467        foreach (KeyValuePair<string, string> item in metadata)
 468        {
 3469            if (options.AllowsMetadataKey(item.Key))
 470            {
 2471                filtered[item.Key] = item.Value;
 472            }
 473        }
 474
 133475        return filtered;
 476    }
 477
 478    private static string FormatTimestamp(DateTimeOffset value)
 479    {
 260480        return value.ToUniversalTime().ToString(TimestampFormat, CultureInfo.InvariantCulture);
 481    }
 482
 483    private static CapabilityGrantTokenDecodeResult Malformed(string message)
 484    {
 15485        return CapabilityGrantTokenDecodeResult.Failure(MalformedFailureCode, message);
 486    }
 487
 488    private static void RequireObject(JsonElement element, string description)
 489    {
 77490        if (element.ValueKind is not JsonValueKind.Object)
 491        {
 1492            throw new TokenStructureException($"The capability grant {description} must be a JSON object.");
 493        }
 76494    }
 495
 496    private static void RejectUnknownProperties(JsonElement element, HashSet<string> knownProperties, string description
 497    {
 4075498        foreach (JsonProperty property in element.EnumerateObject())
 499        {
 1820500            if (!knownProperties.Contains(property.Name))
 501            {
 3502                throw new TokenStructureException($"The capability grant {description} contains an unsupported property.
 503            }
 504        }
 216505    }
 506
 507    private static JsonElement GetRequiredObject(JsonElement element, string propertyName, string description)
 508    {
 145509        return element.TryGetProperty(propertyName, out JsonElement value) && value.ValueKind is JsonValueKind.Object
 145510            ? value
 145511            : throw new TokenStructureException($"The capability grant {description} requires a '{propertyName}' object.
 512    }
 513
 514    private static string GetRequiredString(JsonElement element, string propertyName)
 515    {
 344516        return GetOptionalString(element, propertyName)
 344517            ?? throw new TokenStructureException($"The capability grant token requires a '{propertyName}' value.");
 518    }
 519
 520    private static string? GetOptionalString(JsonElement element, string propertyName)
 521    {
 1478522        return !element.TryGetProperty(propertyName, out JsonElement value) || value.ValueKind is JsonValueKind.Null
 1478523            ? null
 1478524            : value.ValueKind is JsonValueKind.String
 1478525            ? value.GetString()
 1478526            : throw new TokenStructureException($"The capability grant token '{propertyName}' value must be a string.");
 527    }
 528
 529    private static string[] GetRequiredStringArray(JsonElement element, string propertyName)
 530    {
 70531        if (!element.TryGetProperty(propertyName, out JsonElement value) || value.ValueKind is not JsonValueKind.Array)
 532        {
 0533            throw new TokenStructureException($"The capability grant token requires a '{propertyName}' array.");
 534        }
 535
 70536        List<string> values = [];
 537
 281538        foreach (JsonElement item in value.EnumerateArray())
 539        {
 71540            if (item.ValueKind is not JsonValueKind.String)
 541            {
 1542                throw new TokenStructureException($"The capability grant token '{propertyName}' array must contain only 
 543            }
 544
 70545            values.Add(item.GetString()!);
 546        }
 547
 69548        return [.. values];
 549    }
 550
 551    private static Dictionary<string, string> GetOptionalStringMap(JsonElement element, string propertyName)
 552    {
 132553        Dictionary<string, string> values = new(StringComparer.Ordinal);
 554
 132555        if (!element.TryGetProperty(propertyName, out JsonElement value) || value.ValueKind is JsonValueKind.Null)
 556        {
 129557            return values;
 558        }
 559
 3560        if (value.ValueKind is not JsonValueKind.Object)
 561        {
 0562            throw new TokenStructureException($"The capability grant token '{propertyName}' value must be an object.");
 563        }
 564
 14565        foreach (JsonProperty property in value.EnumerateObject())
 566        {
 4567            if (property.Value.ValueKind is not JsonValueKind.String)
 568            {
 0569                throw new TokenStructureException($"The capability grant token '{propertyName}' values must be strings."
 570            }
 571
 4572            values[property.Name] = property.Value.GetString()!;
 573        }
 574
 3575        return values;
 576    }
 577
 578    private static int? GetOptionalInt32(JsonElement element, string propertyName)
 579    {
 68580        return !element.TryGetProperty(propertyName, out JsonElement value) || value.ValueKind is JsonValueKind.Null
 68581            ? null
 68582            : value.ValueKind is JsonValueKind.Number && value.TryGetInt32(out int result)
 68583            ? result
 68584            : throw new TokenStructureException($"The capability grant token '{propertyName}' value must be a 32-bit int
 585    }
 586
 587    private static DateTimeOffset GetRequiredTimestamp(JsonElement element, string propertyName)
 588    {
 138589        return GetOptionalTimestamp(element, propertyName)
 138590            ?? throw new TokenStructureException($"The capability grant token requires a '{propertyName}' timestamp.");
 591    }
 592
 593    private static DateTimeOffset? GetOptionalTimestamp(JsonElement element, string propertyName)
 594    {
 270595        string? value = GetOptionalString(element, propertyName);
 596
 270597        return value is null
 270598            ? null
 270599            : DateTimeOffset.TryParseExact(
 270600            value,
 270601            TimestampFormat,
 270602            CultureInfo.InvariantCulture,
 270603            DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
 270604            out DateTimeOffset parsed)
 270605            ? parsed
 270606            : throw new TokenStructureException($"The capability grant token '{propertyName}' value must be a UTC timest
 607    }
 608
 9609    private sealed class TokenStructureException(string message) : Exception(message);
 610}

Methods/Properties

.cctor()
Encode(AsiBackbone.Core.Signing.SignedGovernanceArtifact`1<AsiBackbone.Core.CapabilityGrants.CapabilityGrant>,AsiBackbone.Core.Signing.CanonicalPayloadOptions,System.Int32)
Decode(System.String,AsiBackbone.Core.Signing.CanonicalPayloadOptions,System.Int32)
DecodeDocument(System.Text.Json.JsonElement,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
WriteGrant(System.Text.Json.Utf8JsonWriter,AsiBackbone.Core.CapabilityGrants.CapabilityGrant,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
WriteProof(System.Text.Json.Utf8JsonWriter,AsiBackbone.Core.Signing.SignedGovernanceArtifact`1<AsiBackbone.Core.CapabilityGrants.CapabilityGrant>)
WriteOptionalString(System.Text.Json.Utf8JsonWriter,System.String,System.String)
FilterGrantMetadata(System.Collections.Generic.IReadOnlyDictionary`2<System.String,System.String>,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
FormatTimestamp(System.DateTimeOffset)
Malformed(System.String)
RequireObject(System.Text.Json.JsonElement,System.String)
RejectUnknownProperties(System.Text.Json.JsonElement,System.Collections.Generic.HashSet`1<System.String>,System.String)
GetRequiredObject(System.Text.Json.JsonElement,System.String,System.String)
GetRequiredString(System.Text.Json.JsonElement,System.String)
GetOptionalString(System.Text.Json.JsonElement,System.String)
GetRequiredStringArray(System.Text.Json.JsonElement,System.String)
GetOptionalStringMap(System.Text.Json.JsonElement,System.String)
GetOptionalInt32(System.Text.Json.JsonElement,System.String)
GetRequiredTimestamp(System.Text.Json.JsonElement,System.String)
GetOptionalTimestamp(System.Text.Json.JsonElement,System.String)
.ctor(System.String)