< Summary

Information
Class: AsiBackbone.Core.Signing.CanonicalPayloadBuilder
Assembly: AsiBackbone.Core
File(s): /home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Core/Signing/CanonicalPayloadBuilder.cs
Line coverage
100%
Covered lines: 221
Uncovered lines: 0
Coverable lines: 221
Total lines: 378
Line coverage: 100%
Branch coverage
97%
Covered branches: 39
Total branches: 40
Branch coverage: 97.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

File(s)

/home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Core/Signing/CanonicalPayloadBuilder.cs

#LineLine coverage
 1using System.Globalization;
 2using AsiBackbone.Core.Audit;
 3using AsiBackbone.Core.CapabilityGrants;
 4using AsiBackbone.Core.Emissions;
 5using AsiBackbone.Core.Outbox;
 6using AsiBackbone.Core.Serialization;
 7
 8namespace AsiBackbone.Core.Signing;
 9
 10/// <summary>
 11/// Builds deterministic, provider-neutral signing payloads for AsiBackbone governance artifacts.
 12/// </summary>
 13public static class CanonicalPayloadBuilder
 14{
 15    /// <summary>
 16    /// Builds a canonical payload for decision receipt.
 17    /// </summary>
 18    public static CanonicalPayload ForDecisionReceipt(IDecisionReceipt receipt, CanonicalPayloadOptions? options = null)
 19    {
 5820        ArgumentNullException.ThrowIfNull(receipt);
 5821        CanonicalPayloadOptions effectiveOptions = options ?? CanonicalPayloadOptions.Default;
 5822        string decisionReceiptId = GetDecisionReceiptId(receipt);
 23
 5824        return CanonicalPayload.Create(
 5825            CanonicalArtifactTypes.DecisionReceipt,
 5826            decisionReceiptId,
 5827            receipt.SchemaVersion,
 5828            effectiveOptions.CanonicalizationVersion,
 5829            effectiveOptions.HashAlgorithm,
 5830            BuildDecisionReceiptContent(receipt, effectiveOptions, decisionReceiptId));
 31    }
 32
 33    /// <summary>
 34    /// Builds a canonical payload for a persistence-ready audit ledger record.
 35    /// </summary>
 36    public static CanonicalPayload ForAuditLedgerRecord(AuditLedgerRecord record, CanonicalPayloadOptions? options = nul
 37    {
 3238        ArgumentNullException.ThrowIfNull(record);
 3239        CanonicalPayloadOptions effectiveOptions = options ?? CanonicalPayloadOptions.Default;
 40
 3241        SortedDictionary<string, object?> content = BuildDecisionReceiptContent(record, effectiveOptions, record.Decisio
 3242        content["acknowledgmentId"] = record.AcknowledgmentId;
 3243        content["capabilityGrantId"] = record.CapabilityTokenId;
 3244        content["handshakeId"] = record.HandshakeId;
 3245        content["previousRecordHash"] = record.PreviousRecordHash;
 3246        content["recordedUtc"] = FormatUtc(record.RecordedUtc);
 3247        content["recordId"] = record.RecordId;
 48
 3249        return CanonicalPayload.Create(
 3250            CanonicalArtifactTypes.AuditLedgerRecord,
 3251            record.RecordId,
 3252            record.SchemaVersion,
 3253            effectiveOptions.CanonicalizationVersion,
 3254            effectiveOptions.HashAlgorithm,
 3255            content);
 56    }
 57
 58    /// <summary>
 59    /// Builds a canonical payload for an decision receipt lifecycle event.
 60    /// </summary>
 61    public static CanonicalPayload ForDecisionReceiptLifecycleEvent(DecisionReceiptLifecycleEvent lifecycleEvent, Canoni
 62    {
 2263        ArgumentNullException.ThrowIfNull(lifecycleEvent);
 2264        CanonicalPayloadOptions effectiveOptions = options ?? CanonicalPayloadOptions.Default;
 65
 2266        SortedDictionary<string, object?> content = new(StringComparer.Ordinal)
 2267        {
 2268            ["auditResidueId"] = lifecycleEvent.DecisionReceiptId,
 2269            ["correlationId"] = lifecycleEvent.CorrelationId,
 2270            ["eventId"] = lifecycleEvent.EventId,
 2271            ["metadata"] = FilterMetadata(lifecycleEvent.Metadata, effectiveOptions),
 2272            ["occurredUtc"] = FormatUtc(lifecycleEvent.OccurredUtc),
 2273            ["operationName"] = lifecycleEvent.OperationName,
 2274            ["outcome"] = lifecycleEvent.Outcome,
 2275            ["stage"] = CanonicalEnumWireNames.ForLifecycleStage(lifecycleEvent.Stage),
 2276            ["stageSequence"] = lifecycleEvent.StageSequence,
 2277            ["traceId"] = lifecycleEvent.TraceId
 2278        };
 79
 2280        return CanonicalPayload.Create(
 2281            CanonicalArtifactTypes.DecisionReceiptLifecycleEvent,
 2282            lifecycleEvent.EventId,
 2283            GovernanceSchemaVersions.StableArtifactsV1,
 2284            effectiveOptions.CanonicalizationVersion,
 2285            effectiveOptions.HashAlgorithm,
 2286            content);
 87    }
 88
 89    /// <summary>
 90    /// Builds a canonical payload for a governance emission envelope.
 91    /// </summary>
 92    public static CanonicalPayload ForGovernanceEmissionEnvelope(GovernanceEmissionEnvelope envelope, CanonicalPayloadOp
 93    {
 4494        ArgumentNullException.ThrowIfNull(envelope);
 4495        CanonicalPayloadOptions effectiveOptions = options ?? CanonicalPayloadOptions.Default;
 96
 4497        return CanonicalPayload.Create(
 4498            CanonicalArtifactTypes.GovernanceEmissionEnvelope,
 4499            envelope.EnvelopeId,
 44100            envelope.SchemaVersion,
 44101            effectiveOptions.CanonicalizationVersion,
 44102            effectiveOptions.HashAlgorithm,
 44103            BuildGovernanceEmissionEnvelopeContent(envelope, effectiveOptions));
 104    }
 105
 106    /// <summary>
 107    /// Builds a canonical payload for a durable outbox entry.
 108    /// </summary>
 109    public static CanonicalPayload ForGovernanceOutboxEntry(GovernanceOutboxEntry entry, CanonicalPayloadOptions? option
 110    {
 16111        ArgumentNullException.ThrowIfNull(entry);
 16112        CanonicalPayloadOptions effectiveOptions = options ?? CanonicalPayloadOptions.Default;
 113
 16114        SortedDictionary<string, object?> content = new(StringComparer.Ordinal)
 16115        {
 16116            ["createdUtc"] = FormatUtc(entry.CreatedUtc),
 16117            ["deadLetterReason"] = entry.DeadLetterReason,
 16118            ["envelope"] = BuildGovernanceEmissionEnvelopeContent(entry.Envelope, effectiveOptions),
 16119            ["lastError"] = BuildGovernanceEmissionErrorContent(entry.LastError),
 16120            ["maxRetryCount"] = entry.MaxRetryCount,
 16121            ["metadata"] = FilterMetadata(entry.Metadata, effectiveOptions),
 16122            ["nextRetryUtc"] = FormatUtc(entry.NextRetryUtc),
 16123            ["outboxEntryId"] = entry.OutboxEntryId,
 16124            ["providerName"] = entry.ProviderName,
 16125            ["providerRecordId"] = entry.ProviderRecordId,
 16126            ["retryCount"] = entry.RetryCount,
 16127            ["status"] = CanonicalEnumWireNames.ForEmissionStatus(entry.Status),
 16128            ["updatedUtc"] = FormatUtc(entry.UpdatedUtc)
 16129        };
 130
 16131        return CanonicalPayload.Create(
 16132            CanonicalArtifactTypes.GovernanceOutboxEntry,
 16133            entry.OutboxEntryId,
 16134            entry.Envelope.SchemaVersion,
 16135            effectiveOptions.CanonicalizationVersion,
 16136            effectiveOptions.HashAlgorithm,
 16137            content);
 138    }
 139
 140    /// <summary>
 141    /// Builds a canonical payload for a capability grant grant.
 142    /// </summary>
 143    /// <remarks>
 144    /// <para>
 145    /// Every field the grant carries is included, so the resulting hash binds the whole grant rather than a subset of
 146    /// it. A payload that omits a field leaves that field outside the proof while
 147    /// <see cref="CapabilityGrantValidator" /> still enforces it, which lets a modified value pass
 148    /// validation against a signature computed before the change. Scopes are normalized to a sorted, de-duplicated,
 149    /// ordinal set, so two grants that differ only in scope ordering produce the same hash.
 150    /// </para>
 151    /// <para>
 152    /// Metadata is the one exception, and deliberately so: it is filtered through
 153    /// <see cref="CanonicalPayloadOptions.AllowsMetadataKey" />, whose allow-list is empty by default. With default
 154    /// options no grant metadata reaches the proof at all, which keeps unbounded and potentially sensitive host data
 155    /// out of hashed payloads. A host that puts security-relevant data in grant metadata has no binding for it until
 156    /// that key is added to the allow-list.
 157    /// </para>
 158    /// </remarks>
 159    /// <param name="grant">The capability grant grant to canonicalize.</param>
 160    /// <param name="options">Canonicalization options, including the metadata allow-list.</param>
 161    /// <returns>A deterministic canonical payload for the grant.</returns>
 162    public static CanonicalPayload ForCapabilityGrant(CapabilityGrant grant, CanonicalPayloadOptions? options = null)
 163    {
 410164        ArgumentNullException.ThrowIfNull(grant);
 409165        CanonicalPayloadOptions effectiveOptions = options ?? CanonicalPayloadOptions.Default;
 166
 409167        SortedDictionary<string, object?> content = new(StringComparer.Ordinal)
 409168        {
 409169            ["acknowledgmentId"] = grant.AcknowledgmentId,
 409170            ["audience"] = grant.Audience,
 409171            ["expiresUtc"] = FormatUtc(grant.ExpiresUtc),
 409172            ["gatewayBinding"] = grant.GatewayBinding,
 409173            ["handshakeId"] = grant.HandshakeId,
 409174            ["issuedUtc"] = FormatUtc(grant.IssuedUtc),
 409175            ["issuer"] = grant.Issuer,
 409176            ["metadata"] = FilterMetadata(grant.Metadata, effectiveOptions),
 409177            ["notBeforeUtc"] = FormatUtc(grant.NotBeforeUtc),
 409178            ["operationName"] = grant.OperationName,
 409179            ["policyHash"] = grant.PolicyHash,
 409180            ["policyVersion"] = grant.PolicyVersion,
 409181            ["resourceBinding"] = grant.ResourceBinding,
 409182            ["scopes"] = NormalizeStringSet(grant.Scopes),
 409183            ["subjectId"] = grant.SubjectId,
 409184            ["tokenId"] = grant.TokenId
 409185        };
 186
 187        // A use limit supplied only at the validation call site is unsigned local policy that the issuer never
 188        // authorized. Binding it requires the grant to record the schema version that carries it, so grants signed unde
 189        // the earlier version continue to hash exactly as they did and keep verifying.
 409190        if (!string.Equals(grant.SchemaVersion, GovernanceSchemaVersions.StableArtifactsV1, StringComparison.Ordinal))
 191        {
 261192            content["maxUseCount"] = grant.MaxUseCount;
 193        }
 194
 409195        return CanonicalPayload.Create(
 409196            CanonicalArtifactTypes.CapabilityGrant,
 409197            grant.TokenId,
 409198            grant.SchemaVersion,
 409199            effectiveOptions.CanonicalizationVersion,
 409200            effectiveOptions.HashAlgorithm,
 409201            content);
 202    }
 203
 204    private static SortedDictionary<string, object?> BuildDecisionReceiptContent(
 205        IDecisionReceipt receipt,
 206        CanonicalPayloadOptions options,
 207        string decisionReceiptId)
 208    {
 90209        SortedDictionary<string, object?> content = new(StringComparer.Ordinal)
 90210        {
 90211            ["actorDisplayName"] = receipt.ActorDisplayName,
 90212            ["actorId"] = receipt.ActorId,
 90213            ["actorType"] = CanonicalEnumWireNames.ForActorType(receipt.ActorType),
 90214            ["auditResidueId"] = decisionReceiptId,
 90215            ["constraintCount"] = receipt.ConstraintCount,
 90216            ["constraintSetHash"] = receipt.ConstraintSetHash,
 90217            ["correlationId"] = receipt.CorrelationId,
 90218            ["decisionLatencyMs"] = receipt.DecisionLatencyMs,
 90219            ["decisionStage"] = receipt.DecisionStage,
 90220            ["emitterProvider"] = receipt.EmitterProvider,
 90221            ["emitterStatus"] = receipt.EmitterStatus,
 90222            ["eventId"] = receipt.EventId,
 90223            ["gatewayExecutionId"] = receipt.GatewayExecutionId,
 90224            ["metadata"] = FilterMetadata(receipt.Metadata, options),
 90225            ["occurredUtc"] = FormatUtc(receipt.OccurredUtc),
 90226            ["operationName"] = receipt.OperationName,
 90227            ["organizationHash"] = receipt.OrganizationHash,
 90228            ["outboxSequence"] = receipt.OutboxSequence,
 90229            ["outcome"] = receipt.Outcome,
 90230            ["parentSpanId"] = receipt.ParentSpanId,
 90231            ["policyHash"] = receipt.PolicyHash,
 90232            ["policyScope"] = receipt.PolicyScope,
 90233            ["policyVersion"] = receipt.PolicyVersion,
 90234            ["reasonCodes"] = NormalizeStringSet(receipt.ReasonCodes),
 90235            ["riskScore"] = receipt.RiskScore,
 90236            ["schemaVersion"] = receipt.SchemaVersion,
 90237            ["spanId"] = receipt.SpanId,
 90238            ["tenantHash"] = receipt.TenantHash,
 90239            ["traceId"] = receipt.TraceId
 90240        };
 241
 242        // The grant identifier is bound only when present, so receipts that carry none keep the exact payload, and hash
 243        // they had before the field existed. A receipt that names a grant cannot have that name removed or replaced
 244        // without changing its hash.
 89245        string? capabilityGrantId = receipt.CapabilityGrantId;
 89246        if (!string.IsNullOrWhiteSpace(capabilityGrantId))
 247        {
 19248            content["capabilityGrantId"] = capabilityGrantId.Trim();
 249        }
 250
 89251        return content;
 252    }
 253
 254    private static SortedDictionary<string, object?> BuildGovernanceEmissionEnvelopeContent(GovernanceEmissionEnvelope e
 255    {
 60256        return new SortedDictionary<string, object?>(StringComparer.Ordinal)
 60257        {
 60258            ["actorId"] = envelope.ActorId,
 60259            ["auditResidueId"] = envelope.DecisionReceiptId,
 60260            ["correlationId"] = envelope.CorrelationId,
 60261            ["createdUtc"] = FormatUtc(envelope.CreatedUtc),
 60262            ["decisionStage"] = envelope.DecisionStage,
 60263            ["emitterProvider"] = envelope.EmitterProvider,
 60264            ["emitterStatus"] = envelope.EmitterStatus,
 60265            ["envelopeId"] = envelope.EnvelopeId,
 60266            ["eventId"] = envelope.EventId,
 60267            ["eventType"] = CanonicalEnumWireNames.ForEmissionEventType(envelope.EventType),
 60268            ["gatewayExecutionId"] = envelope.GatewayExecutionId,
 60269            ["lifecycleStage"] = envelope.LifecycleStage.HasValue
 60270                ? CanonicalEnumWireNames.ForLifecycleStage(envelope.LifecycleStage.Value)
 60271                : null,
 60272            ["lifecycleStageSequence"] = envelope.LifecycleStageSequence,
 60273            ["metadata"] = FilterMetadata(envelope.Metadata, options),
 60274            ["occurredUtc"] = FormatUtc(envelope.OccurredUtc),
 60275            ["operationName"] = envelope.OperationName,
 60276            ["outboxSequence"] = envelope.OutboxSequence,
 60277            ["outcome"] = envelope.Outcome,
 60278            ["parentSpanId"] = envelope.ParentSpanId,
 60279            ["payload"] = BuildGovernanceEmissionPayloadContent(envelope.Payload, options),
 60280            ["policyHash"] = envelope.PolicyHash,
 60281            ["policyVersion"] = envelope.PolicyVersion,
 60282            ["schemaVersion"] = envelope.SchemaVersion,
 60283            ["spanId"] = envelope.SpanId,
 60284            ["traceId"] = envelope.TraceId
 60285        };
 286    }
 287
 288    private static SortedDictionary<string, object?>? BuildGovernanceEmissionPayloadContent(GovernanceEmissionPayload? p
 289    {
 60290        return payload is null
 60291            ? null
 60292            : new SortedDictionary<string, object?>(StringComparer.Ordinal)
 60293            {
 60294                ["contentHash"] = payload.ContentHash,
 60295                ["contentType"] = payload.ContentType,
 60296                ["metadata"] = FilterMetadata(payload.Metadata, options),
 60297                ["payloadType"] = payload.PayloadType,
 60298                ["schemaVersion"] = payload.SchemaVersion,
 60299                ["sizeBytes"] = payload.SizeBytes
 60300            };
 301    }
 302
 303    private static SortedDictionary<string, object?>? BuildGovernanceEmissionErrorContent(GovernanceEmissionError? error
 304    {
 16305        return error is null
 16306            ? null
 16307            : new SortedDictionary<string, object?>(StringComparer.Ordinal)
 16308            {
 16309                ["code"] = error.Code,
 16310                ["isRetryable"] = error.IsRetryable,
 16311                ["message"] = error.Message,
 16312                ["providerErrorCode"] = error.ProviderErrorCode,
 16313                ["providerName"] = error.ProviderName
 16314            };
 315    }
 316
 317    // Shared by every canonical payload builder in this assembly so all artifacts apply the metadata filtering and
 318    // normalization rules published for asibackbone.canonical-json.v1.
 319    internal static SortedDictionary<string, object?> FilterMetadata(IReadOnlyDictionary<string, string>? metadata, Cano
 320    {
 622321        SortedDictionary<string, object?> filteredMetadata = new(StringComparer.Ordinal);
 322
 622323        if (metadata is null || metadata.Count == 0)
 324        {
 553325            return filteredMetadata;
 326        }
 327
 389328        foreach (KeyValuePair<string, string> item in metadata)
 329        {
 126330            if (!options.AllowsMetadataKey(item.Key))
 331            {
 332                continue;
 333            }
 334
 58335            string normalizedKey = item.Key.Trim();
 336
 337            // Trimming keys before hashing makes "k" and " k" the same key. Overwriting silently made the hashed payloa
 338            // depend on enumeration order, so the same logical metadata could hash two ways and one key's value could
 339            // displace another's inside the signed payload.
 58340            if (filteredMetadata.ContainsKey(normalizedKey))
 341            {
 1342                throw new ArgumentException(
 1343                    $"Canonical payload metadata contains keys that collide after trimming: '{normalizedKey}'. Normalize
 1344                    nameof(metadata));
 345            }
 346
 57347            filteredMetadata[normalizedKey] = item.Value?.Trim() ?? string.Empty;
 348        }
 349
 68350        return filteredMetadata;
 351    }
 352
 353    private static string[] NormalizeStringSet(IEnumerable<string> values)
 354    {
 498355        return [.. values
 498356            .Where(value => !string.IsNullOrWhiteSpace(value))
 498357            .Select(value => value.Trim())
 498358            .Distinct(StringComparer.Ordinal)
 498359            .OrderBy(value => value, StringComparer.Ordinal)];
 360    }
 361
 362    private static string? FormatUtc(DateTimeOffset? timestamp)
 363    {
 425364        return timestamp.HasValue ? FormatUtc(timestamp.Value) : null;
 365    }
 366
 367    private static string FormatUtc(DateTimeOffset timestamp)
 368    {
 1381369        return timestamp.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'", CultureInfo.InvariantCulture);
 370    }
 371
 372    private static string GetDecisionReceiptId(IDecisionReceipt receipt)
 373    {
 58374        return string.IsNullOrWhiteSpace(receipt.DecisionReceiptId)
 58375            ? receipt.EventId
 58376            : receipt.DecisionReceiptId;
 377    }
 378}

Methods/Properties

ForDecisionReceipt(AsiBackbone.Core.Audit.IDecisionReceipt,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
ForAuditLedgerRecord(AsiBackbone.Core.Audit.AuditLedgerRecord,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
ForDecisionReceiptLifecycleEvent(AsiBackbone.Core.Audit.DecisionReceiptLifecycleEvent,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
ForGovernanceEmissionEnvelope(AsiBackbone.Core.Emissions.GovernanceEmissionEnvelope,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
ForGovernanceOutboxEntry(AsiBackbone.Core.Outbox.GovernanceOutboxEntry,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
ForCapabilityGrant(AsiBackbone.Core.CapabilityGrants.CapabilityGrant,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
BuildDecisionReceiptContent(AsiBackbone.Core.Audit.IDecisionReceipt,AsiBackbone.Core.Signing.CanonicalPayloadOptions,System.String)
BuildGovernanceEmissionEnvelopeContent(AsiBackbone.Core.Emissions.GovernanceEmissionEnvelope,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
BuildGovernanceEmissionPayloadContent(AsiBackbone.Core.Emissions.GovernanceEmissionPayload,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
BuildGovernanceEmissionErrorContent(AsiBackbone.Core.Emissions.GovernanceEmissionError)
FilterMetadata(System.Collections.Generic.IReadOnlyDictionary`2<System.String,System.String>,AsiBackbone.Core.Signing.CanonicalPayloadOptions)
NormalizeStringSet(System.Collections.Generic.IEnumerable`1<System.String>)
FormatUtc(System.Nullable`1<System.DateTimeOffset>)
FormatUtc(System.DateTimeOffset)
GetDecisionReceiptId(AsiBackbone.Core.Audit.IDecisionReceipt)