| | | 1 | | using System.Buffers; |
| | | 2 | | using System.Buffers.Text; |
| | | 3 | | using System.Globalization; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | using AsiBackbone.Core.Signing; |
| | | 6 | | |
| | | 7 | | namespace 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> |
| | | 31 | | public 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. |
| | 2 | 84 | | private static readonly HashSet<string> DerivedSigningMetadataKeys = new(StringComparer.Ordinal) |
| | 2 | 85 | | { |
| | 2 | 86 | | "artifact_id", |
| | 2 | 87 | | "artifact_type", |
| | 2 | 88 | | "canonicalization_version", |
| | 2 | 89 | | "payload_schema_version" |
| | 2 | 90 | | }; |
| | | 91 | | |
| | 2 | 92 | | private static readonly HashSet<string> DocumentProperties = new(StringComparer.Ordinal) { "v", "grant", "proof" }; |
| | | 93 | | |
| | 2 | 94 | | private static readonly HashSet<string> GrantProperties = new(StringComparer.Ordinal) |
| | 2 | 95 | | { |
| | 2 | 96 | | "acknowledgmentId", |
| | 2 | 97 | | "audience", |
| | 2 | 98 | | "expiresUtc", |
| | 2 | 99 | | "gatewayBinding", |
| | 2 | 100 | | "handshakeId", |
| | 2 | 101 | | "issuedUtc", |
| | 2 | 102 | | "issuer", |
| | 2 | 103 | | "maxUseCount", |
| | 2 | 104 | | "metadata", |
| | 2 | 105 | | "notBeforeUtc", |
| | 2 | 106 | | "operationName", |
| | 2 | 107 | | "policyHash", |
| | 2 | 108 | | "policyVersion", |
| | 2 | 109 | | "resourceBinding", |
| | 2 | 110 | | "schemaVersion", |
| | 2 | 111 | | "scopes", |
| | 2 | 112 | | "subjectId", |
| | 2 | 113 | | "tokenId" |
| | 2 | 114 | | }; |
| | | 115 | | |
| | 2 | 116 | | private static readonly HashSet<string> ProofProperties = new(StringComparer.Ordinal) |
| | 2 | 117 | | { |
| | 2 | 118 | | "hashAlgorithm", |
| | 2 | 119 | | "keyId", |
| | 2 | 120 | | "keyVersion", |
| | 2 | 121 | | "metadata", |
| | 2 | 122 | | "provider", |
| | 2 | 123 | | "signature", |
| | 2 | 124 | | "signatureAlgorithm", |
| | 2 | 125 | | "signedUtc" |
| | 2 | 126 | | }; |
| | | 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 | | { |
| | 68 | 147 | | ArgumentNullException.ThrowIfNull(signedGrant); |
| | 68 | 148 | | ArgumentOutOfRangeException.ThrowIfLessThan(maxTokenLength, 1); |
| | | 149 | | |
| | 67 | 150 | | CapabilityGrant grant = signedGrant.Artifact; |
| | | 151 | | |
| | 67 | 152 | | if (!string.Equals(signedGrant.ArtifactType, CanonicalArtifactTypes.CapabilityGrant, StringComparison.Ordinal) |
| | 67 | 153 | | || !string.Equals(signedGrant.ArtifactId, grant.TokenId, StringComparison.Ordinal)) |
| | | 154 | | { |
| | 0 | 155 | | throw new ArgumentException("The signed artifact does not describe this capability grant.", nameof(signedGra |
| | | 156 | | } |
| | | 157 | | |
| | 67 | 158 | | if (!signedGrant.IsSigned) |
| | | 159 | | { |
| | 1 | 160 | | throw new InvalidOperationException("Only a signed capability grant can be encoded as a token."); |
| | | 161 | | } |
| | | 162 | | |
| | 66 | 163 | | CanonicalPayloadOptions effectiveOptions = options ?? CanonicalPayloadOptions.Default; |
| | 66 | 164 | | CanonicalPayloadHash rebuiltHash = CanonicalPayloadHasher.ComputeHash( |
| | 66 | 165 | | CanonicalPayloadBuilder.ForCapabilityGrant(grant, effectiveOptions), |
| | 66 | 166 | | signedGrant.HashAlgorithm); |
| | | 167 | | |
| | 66 | 168 | | if (!string.Equals(rebuiltHash.HashValue, signedGrant.CanonicalHash.HashValue, StringComparison.Ordinal)) |
| | | 169 | | { |
| | 1 | 170 | | throw new ArgumentException( |
| | 1 | 171 | | "The grant rebuilt with the supplied canonical payload options does not hash to the signed hash. Pass th |
| | 1 | 172 | | nameof(options)); |
| | | 173 | | } |
| | | 174 | | |
| | 65 | 175 | | ArrayBufferWriter<byte> buffer = new(); |
| | 65 | 176 | | using (Utf8JsonWriter writer = new(buffer)) |
| | | 177 | | { |
| | 65 | 178 | | writer.WriteStartObject(); |
| | 65 | 179 | | writer.WriteNumber("v", FormatVersion); |
| | 65 | 180 | | WriteGrant(writer, grant, effectiveOptions); |
| | 65 | 181 | | WriteProof(writer, signedGrant); |
| | 65 | 182 | | writer.WriteEndObject(); |
| | 65 | 183 | | } |
| | | 184 | | |
| | 65 | 185 | | string token = FormatPrefix + Base64Url.EncodeToString(buffer.WrittenSpan); |
| | | 186 | | |
| | 65 | 187 | | return token.Length > maxTokenLength |
| | 65 | 188 | | ? throw new InvalidOperationException( |
| | 65 | 189 | | $"The encoded capability grant token is {token.Length} characters, which exceeds the {maxTokenLength}-ch |
| | 65 | 190 | | : 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 | | { |
| | 88 | 211 | | ArgumentOutOfRangeException.ThrowIfLessThan(maxTokenLength, 1); |
| | | 212 | | |
| | 87 | 213 | | if (string.IsNullOrWhiteSpace(token)) |
| | | 214 | | { |
| | 2 | 215 | | return CapabilityGrantTokenDecodeResult.Failure(MissingFailureCode, "No capability grant token was supplied. |
| | | 216 | | } |
| | | 217 | | |
| | 85 | 218 | | string trimmed = token.Trim(); |
| | | 219 | | |
| | 85 | 220 | | if (trimmed.Length > maxTokenLength) |
| | | 221 | | { |
| | 1 | 222 | | return CapabilityGrantTokenDecodeResult.Failure( |
| | 1 | 223 | | TooLargeFailureCode, |
| | 1 | 224 | | $"The capability grant token exceeds the {maxTokenLength}-character limit."); |
| | | 225 | | } |
| | | 226 | | |
| | 84 | 227 | | if (!trimmed.StartsWith(FormatPrefix, StringComparison.Ordinal)) |
| | | 228 | | { |
| | 1 | 229 | | return CapabilityGrantTokenDecodeResult.Failure( |
| | 1 | 230 | | UnsupportedFormatFailureCode, |
| | 1 | 231 | | "The capability grant token does not use a supported format prefix."); |
| | | 232 | | } |
| | | 233 | | |
| | 83 | 234 | | ReadOnlySpan<char> encoded = trimmed.AsSpan(FormatPrefix.Length); |
| | | 235 | | |
| | 83 | 236 | | if (encoded.IsEmpty || !Base64Url.IsValid(encoded, out int decodedLength)) |
| | | 237 | | { |
| | 3 | 238 | | return Malformed("The capability grant token body is not valid base64url."); |
| | | 239 | | } |
| | | 240 | | |
| | 80 | 241 | | byte[] documentBytes = new byte[decodedLength]; |
| | | 242 | | |
| | 80 | 243 | | if (!Base64Url.TryDecodeFromChars(encoded, documentBytes, out int bytesWritten) || bytesWritten != decodedLength |
| | | 244 | | { |
| | 0 | 245 | | return Malformed("The capability grant token body is not valid base64url."); |
| | | 246 | | } |
| | | 247 | | |
| | | 248 | | try |
| | | 249 | | { |
| | 80 | 250 | | using var document = JsonDocument.Parse( |
| | 80 | 251 | | documentBytes, |
| | 80 | 252 | | new JsonDocumentOptions |
| | 80 | 253 | | { |
| | 80 | 254 | | MaxDepth = MaxDocumentDepth, |
| | 80 | 255 | | AllowTrailingCommas = false, |
| | 80 | 256 | | CommentHandling = JsonCommentHandling.Disallow, |
| | 80 | 257 | | AllowDuplicateProperties = false |
| | 80 | 258 | | }); |
| | | 259 | | |
| | 77 | 260 | | return DecodeDocument(document.RootElement, options ?? CanonicalPayloadOptions.Default); |
| | | 261 | | } |
| | 3 | 262 | | catch (JsonException) |
| | | 263 | | { |
| | 3 | 264 | | return Malformed("The capability grant token body is not a valid token document."); |
| | | 265 | | } |
| | | 266 | | catch (TokenStructureException exception) |
| | | 267 | | { |
| | 9 | 268 | | return Malformed(exception.Message); |
| | | 269 | | } |
| | 80 | 270 | | } |
| | | 271 | | |
| | | 272 | | private static CapabilityGrantTokenDecodeResult DecodeDocument(JsonElement root, CanonicalPayloadOptions options) |
| | | 273 | | { |
| | 77 | 274 | | RequireObject(root, "token document"); |
| | 76 | 275 | | RejectUnknownProperties(root, DocumentProperties, "token document"); |
| | | 276 | | |
| | 74 | 277 | | if (!root.TryGetProperty("v", out JsonElement versionElement) |
| | 74 | 278 | | || versionElement.ValueKind is not JsonValueKind.Number |
| | 74 | 279 | | || !versionElement.TryGetInt32(out int version)) |
| | | 280 | | { |
| | 0 | 281 | | throw new TokenStructureException("The capability grant token document has no format version."); |
| | | 282 | | } |
| | | 283 | | |
| | 74 | 284 | | if (version != FormatVersion) |
| | | 285 | | { |
| | 1 | 286 | | return CapabilityGrantTokenDecodeResult.Failure( |
| | 1 | 287 | | UnsupportedFormatFailureCode, |
| | 1 | 288 | | "The capability grant token format version is not supported."); |
| | | 289 | | } |
| | | 290 | | |
| | 73 | 291 | | JsonElement grantElement = GetRequiredObject(root, "grant", "token document"); |
| | 72 | 292 | | JsonElement proofElement = GetRequiredObject(root, "proof", "token document"); |
| | 72 | 293 | | RejectUnknownProperties(grantElement, GrantProperties, "grant"); |
| | 71 | 294 | | RejectUnknownProperties(proofElement, ProofProperties, "proof"); |
| | | 295 | | |
| | | 296 | | CapabilityGrant grant; |
| | | 297 | | |
| | | 298 | | try |
| | | 299 | | { |
| | 71 | 300 | | grant = CapabilityGrant.Create( |
| | 71 | 301 | | tokenId: GetRequiredString(grantElement, "tokenId"), |
| | 71 | 302 | | issuer: GetRequiredString(grantElement, "issuer"), |
| | 71 | 303 | | audience: GetRequiredString(grantElement, "audience"), |
| | 71 | 304 | | scopes: GetRequiredStringArray(grantElement, "scopes"), |
| | 71 | 305 | | issuedUtc: GetRequiredTimestamp(grantElement, "issuedUtc"), |
| | 71 | 306 | | expiresUtc: GetRequiredTimestamp(grantElement, "expiresUtc"), |
| | 71 | 307 | | notBeforeUtc: GetOptionalTimestamp(grantElement, "notBeforeUtc"), |
| | 71 | 308 | | subjectId: GetOptionalString(grantElement, "subjectId"), |
| | 71 | 309 | | operationName: GetOptionalString(grantElement, "operationName"), |
| | 71 | 310 | | policyVersion: GetOptionalString(grantElement, "policyVersion"), |
| | 71 | 311 | | policyHash: GetOptionalString(grantElement, "policyHash"), |
| | 71 | 312 | | acknowledgmentId: GetOptionalString(grantElement, "acknowledgmentId"), |
| | 71 | 313 | | handshakeId: GetOptionalString(grantElement, "handshakeId"), |
| | 71 | 314 | | gatewayBinding: GetOptionalString(grantElement, "gatewayBinding"), |
| | 71 | 315 | | resourceBinding: GetOptionalString(grantElement, "resourceBinding"), |
| | 71 | 316 | | metadata: FilterGrantMetadata(GetOptionalStringMap(grantElement, "metadata"), options), |
| | 71 | 317 | | maxUseCount: GetOptionalInt32(grantElement, "maxUseCount"), |
| | 71 | 318 | | schemaVersion: GetRequiredString(grantElement, "schemaVersion")); |
| | 65 | 319 | | } |
| | 2 | 320 | | catch (ArgumentException) |
| | | 321 | | { |
| | 2 | 322 | | return CapabilityGrantTokenDecodeResult.Failure( |
| | 2 | 323 | | InvalidGrantFailureCode, |
| | 2 | 324 | | "The capability grant token fields do not form a valid capability grant."); |
| | | 325 | | } |
| | | 326 | | |
| | 65 | 327 | | string hashAlgorithm = GetRequiredString(proofElement, "hashAlgorithm"); |
| | 65 | 328 | | CanonicalPayload payload = CanonicalPayloadBuilder.ForCapabilityGrant(grant, options); |
| | | 329 | | CanonicalPayloadHash hash; |
| | | 330 | | |
| | | 331 | | try |
| | | 332 | | { |
| | 65 | 333 | | hash = CanonicalPayloadHasher.ComputeHash(payload, hashAlgorithm); |
| | 64 | 334 | | } |
| | 1 | 335 | | catch (NotSupportedException) |
| | | 336 | | { |
| | 1 | 337 | | return CapabilityGrantTokenDecodeResult.Failure( |
| | 1 | 338 | | UnsupportedHashAlgorithmFailureCode, |
| | 1 | 339 | | "The capability grant token names a hash algorithm the built-in hasher does not support."); |
| | | 340 | | } |
| | | 341 | | |
| | 64 | 342 | | Dictionary<string, string> signingMetadata = new(StringComparer.Ordinal); |
| | | 343 | | |
| | 134 | 344 | | foreach (KeyValuePair<string, string> item in GetOptionalStringMap(proofElement, "metadata")) |
| | | 345 | | { |
| | 3 | 346 | | if (!DerivedSigningMetadataKeys.Contains(item.Key.Trim())) |
| | | 347 | | { |
| | 1 | 348 | | signingMetadata[item.Key] = item.Value; |
| | | 349 | | } |
| | | 350 | | } |
| | | 351 | | |
| | 64 | 352 | | var metadata = SigningMetadata.Create( |
| | 64 | 353 | | signingHash: hash.HashValue, |
| | 64 | 354 | | hashAlgorithm: hash.HashAlgorithm, |
| | 64 | 355 | | signature: GetOptionalString(proofElement, "signature"), |
| | 64 | 356 | | signatureAlgorithm: GetOptionalString(proofElement, "signatureAlgorithm"), |
| | 64 | 357 | | keyId: GetOptionalString(proofElement, "keyId"), |
| | 64 | 358 | | keyVersion: GetOptionalString(proofElement, "keyVersion"), |
| | 64 | 359 | | provider: GetOptionalString(proofElement, "provider"), |
| | 64 | 360 | | signedUtc: GetOptionalTimestamp(proofElement, "signedUtc"), |
| | 64 | 361 | | metadata: signingMetadata); |
| | | 362 | | |
| | 64 | 363 | | return CapabilityGrantTokenDecodeResult.Success( |
| | 64 | 364 | | SignedGovernanceArtifacts.FromSigningMetadata(grant, payload, hash, metadata)); |
| | 3 | 365 | | } |
| | | 366 | | |
| | | 367 | | private static void WriteGrant(Utf8JsonWriter writer, CapabilityGrant grant, CanonicalPayloadOptions options) |
| | | 368 | | { |
| | 65 | 369 | | writer.WriteStartObject("grant"); |
| | 65 | 370 | | WriteOptionalString(writer, "acknowledgmentId", grant.AcknowledgmentId); |
| | 65 | 371 | | writer.WriteString("audience", grant.Audience); |
| | 65 | 372 | | writer.WriteString("expiresUtc", FormatTimestamp(grant.ExpiresUtc)); |
| | 65 | 373 | | WriteOptionalString(writer, "gatewayBinding", grant.GatewayBinding); |
| | 65 | 374 | | WriteOptionalString(writer, "handshakeId", grant.HandshakeId); |
| | 65 | 375 | | writer.WriteString("issuedUtc", FormatTimestamp(grant.IssuedUtc)); |
| | 65 | 376 | | writer.WriteString("issuer", grant.Issuer); |
| | | 377 | | |
| | 65 | 378 | | if (grant.MaxUseCount.HasValue) |
| | | 379 | | { |
| | 65 | 380 | | writer.WriteNumber("maxUseCount", grant.MaxUseCount.Value); |
| | | 381 | | } |
| | | 382 | | |
| | 65 | 383 | | Dictionary<string, string> boundMetadata = FilterGrantMetadata(grant.Metadata, options); |
| | 65 | 384 | | if (boundMetadata.Count > 0) |
| | | 385 | | { |
| | 1 | 386 | | writer.WriteStartObject("metadata"); |
| | 4 | 387 | | foreach (KeyValuePair<string, string> item in boundMetadata.OrderBy(item => item.Key, StringComparer.Ordinal |
| | | 388 | | { |
| | 1 | 389 | | writer.WriteString(item.Key, item.Value); |
| | | 390 | | } |
| | | 391 | | |
| | 1 | 392 | | writer.WriteEndObject(); |
| | | 393 | | } |
| | | 394 | | |
| | 65 | 395 | | if (grant.NotBeforeUtc.HasValue) |
| | | 396 | | { |
| | 65 | 397 | | writer.WriteString("notBeforeUtc", FormatTimestamp(grant.NotBeforeUtc.Value)); |
| | | 398 | | } |
| | | 399 | | |
| | 65 | 400 | | WriteOptionalString(writer, "operationName", grant.OperationName); |
| | 65 | 401 | | WriteOptionalString(writer, "policyHash", grant.PolicyHash); |
| | 65 | 402 | | WriteOptionalString(writer, "policyVersion", grant.PolicyVersion); |
| | 65 | 403 | | WriteOptionalString(writer, "resourceBinding", grant.ResourceBinding); |
| | 65 | 404 | | writer.WriteString("schemaVersion", grant.SchemaVersion); |
| | 65 | 405 | | writer.WriteStartArray("scopes"); |
| | 260 | 406 | | foreach (string scope in grant.Scopes) |
| | | 407 | | { |
| | 65 | 408 | | writer.WriteStringValue(scope); |
| | | 409 | | } |
| | | 410 | | |
| | 65 | 411 | | writer.WriteEndArray(); |
| | 65 | 412 | | WriteOptionalString(writer, "subjectId", grant.SubjectId); |
| | 65 | 413 | | writer.WriteString("tokenId", grant.TokenId); |
| | 65 | 414 | | writer.WriteEndObject(); |
| | 65 | 415 | | } |
| | | 416 | | |
| | | 417 | | private static void WriteProof(Utf8JsonWriter writer, SignedGovernanceArtifact<CapabilityGrant> signedGrant) |
| | | 418 | | { |
| | 65 | 419 | | SigningMetadata signing = signedGrant.SigningMetadata; |
| | | 420 | | |
| | 65 | 421 | | writer.WriteStartObject("proof"); |
| | 65 | 422 | | writer.WriteString("hashAlgorithm", signedGrant.HashAlgorithm); |
| | 65 | 423 | | WriteOptionalString(writer, "keyId", signing.KeyId); |
| | 65 | 424 | | WriteOptionalString(writer, "keyVersion", signing.KeyVersion); |
| | | 425 | | |
| | 65 | 426 | | KeyValuePair<string, string>[] transportedMetadata = [.. signing.Metadata |
| | 65 | 427 | | .Where(item => !DerivedSigningMetadataKeys.Contains(item.Key)) |
| | 65 | 428 | | .OrderBy(item => item.Key, StringComparer.Ordinal)]; |
| | | 429 | | |
| | 65 | 430 | | if (transportedMetadata.Length > 0) |
| | | 431 | | { |
| | 1 | 432 | | writer.WriteStartObject("metadata"); |
| | 4 | 433 | | foreach (KeyValuePair<string, string> item in transportedMetadata) |
| | | 434 | | { |
| | 1 | 435 | | writer.WriteString(item.Key, item.Value); |
| | | 436 | | } |
| | | 437 | | |
| | 1 | 438 | | writer.WriteEndObject(); |
| | | 439 | | } |
| | | 440 | | |
| | 65 | 441 | | WriteOptionalString(writer, "provider", signing.Provider); |
| | 65 | 442 | | WriteOptionalString(writer, "signature", signing.Signature); |
| | 65 | 443 | | WriteOptionalString(writer, "signatureAlgorithm", signing.SignatureAlgorithm); |
| | | 444 | | |
| | 65 | 445 | | if (signing.SignedUtc.HasValue) |
| | | 446 | | { |
| | 65 | 447 | | writer.WriteString("signedUtc", FormatTimestamp(signing.SignedUtc.Value)); |
| | | 448 | | } |
| | | 449 | | |
| | 65 | 450 | | writer.WriteEndObject(); |
| | 65 | 451 | | } |
| | | 452 | | |
| | | 453 | | private static void WriteOptionalString(Utf8JsonWriter writer, string propertyName, string? value) |
| | | 454 | | { |
| | 845 | 455 | | if (value is not null) |
| | | 456 | | { |
| | 718 | 457 | | writer.WriteString(propertyName, value); |
| | | 458 | | } |
| | 845 | 459 | | } |
| | | 460 | | |
| | | 461 | | private static Dictionary<string, string> FilterGrantMetadata( |
| | | 462 | | IReadOnlyDictionary<string, string> metadata, |
| | | 463 | | CanonicalPayloadOptions options) |
| | | 464 | | { |
| | 133 | 465 | | Dictionary<string, string> filtered = new(StringComparer.Ordinal); |
| | | 466 | | |
| | 272 | 467 | | foreach (KeyValuePair<string, string> item in metadata) |
| | | 468 | | { |
| | 3 | 469 | | if (options.AllowsMetadataKey(item.Key)) |
| | | 470 | | { |
| | 2 | 471 | | filtered[item.Key] = item.Value; |
| | | 472 | | } |
| | | 473 | | } |
| | | 474 | | |
| | 133 | 475 | | return filtered; |
| | | 476 | | } |
| | | 477 | | |
| | | 478 | | private static string FormatTimestamp(DateTimeOffset value) |
| | | 479 | | { |
| | 260 | 480 | | return value.ToUniversalTime().ToString(TimestampFormat, CultureInfo.InvariantCulture); |
| | | 481 | | } |
| | | 482 | | |
| | | 483 | | private static CapabilityGrantTokenDecodeResult Malformed(string message) |
| | | 484 | | { |
| | 15 | 485 | | return CapabilityGrantTokenDecodeResult.Failure(MalformedFailureCode, message); |
| | | 486 | | } |
| | | 487 | | |
| | | 488 | | private static void RequireObject(JsonElement element, string description) |
| | | 489 | | { |
| | 77 | 490 | | if (element.ValueKind is not JsonValueKind.Object) |
| | | 491 | | { |
| | 1 | 492 | | throw new TokenStructureException($"The capability grant {description} must be a JSON object."); |
| | | 493 | | } |
| | 76 | 494 | | } |
| | | 495 | | |
| | | 496 | | private static void RejectUnknownProperties(JsonElement element, HashSet<string> knownProperties, string description |
| | | 497 | | { |
| | 4075 | 498 | | foreach (JsonProperty property in element.EnumerateObject()) |
| | | 499 | | { |
| | 1820 | 500 | | if (!knownProperties.Contains(property.Name)) |
| | | 501 | | { |
| | 3 | 502 | | throw new TokenStructureException($"The capability grant {description} contains an unsupported property. |
| | | 503 | | } |
| | | 504 | | } |
| | 216 | 505 | | } |
| | | 506 | | |
| | | 507 | | private static JsonElement GetRequiredObject(JsonElement element, string propertyName, string description) |
| | | 508 | | { |
| | 145 | 509 | | return element.TryGetProperty(propertyName, out JsonElement value) && value.ValueKind is JsonValueKind.Object |
| | 145 | 510 | | ? value |
| | 145 | 511 | | : throw new TokenStructureException($"The capability grant {description} requires a '{propertyName}' object. |
| | | 512 | | } |
| | | 513 | | |
| | | 514 | | private static string GetRequiredString(JsonElement element, string propertyName) |
| | | 515 | | { |
| | 344 | 516 | | return GetOptionalString(element, propertyName) |
| | 344 | 517 | | ?? throw new TokenStructureException($"The capability grant token requires a '{propertyName}' value."); |
| | | 518 | | } |
| | | 519 | | |
| | | 520 | | private static string? GetOptionalString(JsonElement element, string propertyName) |
| | | 521 | | { |
| | 1478 | 522 | | return !element.TryGetProperty(propertyName, out JsonElement value) || value.ValueKind is JsonValueKind.Null |
| | 1478 | 523 | | ? null |
| | 1478 | 524 | | : value.ValueKind is JsonValueKind.String |
| | 1478 | 525 | | ? value.GetString() |
| | 1478 | 526 | | : 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 | | { |
| | 70 | 531 | | if (!element.TryGetProperty(propertyName, out JsonElement value) || value.ValueKind is not JsonValueKind.Array) |
| | | 532 | | { |
| | 0 | 533 | | throw new TokenStructureException($"The capability grant token requires a '{propertyName}' array."); |
| | | 534 | | } |
| | | 535 | | |
| | 70 | 536 | | List<string> values = []; |
| | | 537 | | |
| | 281 | 538 | | foreach (JsonElement item in value.EnumerateArray()) |
| | | 539 | | { |
| | 71 | 540 | | if (item.ValueKind is not JsonValueKind.String) |
| | | 541 | | { |
| | 1 | 542 | | throw new TokenStructureException($"The capability grant token '{propertyName}' array must contain only |
| | | 543 | | } |
| | | 544 | | |
| | 70 | 545 | | values.Add(item.GetString()!); |
| | | 546 | | } |
| | | 547 | | |
| | 69 | 548 | | return [.. values]; |
| | | 549 | | } |
| | | 550 | | |
| | | 551 | | private static Dictionary<string, string> GetOptionalStringMap(JsonElement element, string propertyName) |
| | | 552 | | { |
| | 132 | 553 | | Dictionary<string, string> values = new(StringComparer.Ordinal); |
| | | 554 | | |
| | 132 | 555 | | if (!element.TryGetProperty(propertyName, out JsonElement value) || value.ValueKind is JsonValueKind.Null) |
| | | 556 | | { |
| | 129 | 557 | | return values; |
| | | 558 | | } |
| | | 559 | | |
| | 3 | 560 | | if (value.ValueKind is not JsonValueKind.Object) |
| | | 561 | | { |
| | 0 | 562 | | throw new TokenStructureException($"The capability grant token '{propertyName}' value must be an object."); |
| | | 563 | | } |
| | | 564 | | |
| | 14 | 565 | | foreach (JsonProperty property in value.EnumerateObject()) |
| | | 566 | | { |
| | 4 | 567 | | if (property.Value.ValueKind is not JsonValueKind.String) |
| | | 568 | | { |
| | 0 | 569 | | throw new TokenStructureException($"The capability grant token '{propertyName}' values must be strings." |
| | | 570 | | } |
| | | 571 | | |
| | 4 | 572 | | values[property.Name] = property.Value.GetString()!; |
| | | 573 | | } |
| | | 574 | | |
| | 3 | 575 | | return values; |
| | | 576 | | } |
| | | 577 | | |
| | | 578 | | private static int? GetOptionalInt32(JsonElement element, string propertyName) |
| | | 579 | | { |
| | 68 | 580 | | return !element.TryGetProperty(propertyName, out JsonElement value) || value.ValueKind is JsonValueKind.Null |
| | 68 | 581 | | ? null |
| | 68 | 582 | | : value.ValueKind is JsonValueKind.Number && value.TryGetInt32(out int result) |
| | 68 | 583 | | ? result |
| | 68 | 584 | | : 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 | | { |
| | 138 | 589 | | return GetOptionalTimestamp(element, propertyName) |
| | 138 | 590 | | ?? throw new TokenStructureException($"The capability grant token requires a '{propertyName}' timestamp."); |
| | | 591 | | } |
| | | 592 | | |
| | | 593 | | private static DateTimeOffset? GetOptionalTimestamp(JsonElement element, string propertyName) |
| | | 594 | | { |
| | 270 | 595 | | string? value = GetOptionalString(element, propertyName); |
| | | 596 | | |
| | 270 | 597 | | return value is null |
| | 270 | 598 | | ? null |
| | 270 | 599 | | : DateTimeOffset.TryParseExact( |
| | 270 | 600 | | value, |
| | 270 | 601 | | TimestampFormat, |
| | 270 | 602 | | CultureInfo.InvariantCulture, |
| | 270 | 603 | | DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, |
| | 270 | 604 | | out DateTimeOffset parsed) |
| | 270 | 605 | | ? parsed |
| | 270 | 606 | | : throw new TokenStructureException($"The capability grant token '{propertyName}' value must be a UTC timest |
| | | 607 | | } |
| | | 608 | | |
| | 9 | 609 | | private sealed class TokenStructureException(string message) : Exception(message); |
| | | 610 | | } |