Jenny A1
Findings (FLT-359 — Chunk Review)¶
1. [HIGH] src/Forge.Approvals.Twilio/TwilioOptions.cs:18-38 — Hardcoded placeholder "andrew" approver, unpinned ServiceSid, and unvalidated Twilio SIDs¶
- Problem:
TwilioOptions.FromConfiguration(line 37) unconditionally setsApprover = ApproverRegistry.Placeholder.Find("andrew"). BecauseHasPinnedApprover(lines 21–24) requires exact ordinal matches onIdentity == Approver.EntityIdentityandApprover.FactorSids.Contains(FactorSid), any real enrolled Twilio VerifyIdentity/FactorSidfails against placeholder data (IsComplete == false), and no non-"andrew"approver can ever pass validation—breaking role policy and m-of-n distinct-person approvals whenever options are bound viaFromConfiguration.HasPinnedApproveronly checks!string.IsNullOrWhiteSpace(ServiceSid)rather than verifyingServiceSidagainst a registry/executor pin (FLT-359 requires pinned service/entity/factor), and none ofAccountSid,ApiKeySid,ServiceSid, orFactorSidvalidate Twilio SID format (AC/SK/VA/YF+ 32 hex chars), risking REST URL path injection if interpolated directly into Twilio Verify endpoints.HasCredentials(lines 18–20) allows silent fallback to an unrestrictedAuthTokenifApiKeySidis configured with a missingApiKeySecretwhileAuthTokenis present, andFromConfigurationdoes not null-checkread.- Fix: Pass the trusted
ApproverRegistry(and pinnedServiceSid) intoFromConfiguration(Func<string, string?> read, ApproverRegistry registry, ...)withArgumentNullException.ThrowIfNull, resolve the approver by configured identity/approver ID instead ofApproverRegistry.Placeholder.Find("andrew"), pinServiceSid, fail closed if partial API-key fields (ApiKeySidXORApiKeySecret) are set, and validate Twilio SID formats (^(AC|SK|VA|YF)[0-9a-fA-F]{32}$).
2. [HIGH] src/Forge.Approvals.Core/Jcs.cs:13-14, src/Forge.Approvals.Core/Jcs.cs:29-34, src/Forge.Approvals.Core/Jcs.cs:51-52, src/Forge.Approvals.Core/Jcs.cs:89 — Escaped lone UTF-16 surrogates bypass ValidateUnicode and silently mutate to U+FFFD (RFC 8785 violation)¶
- Problem:
ValidateUnicode(json)(line 13) checks raw JSON characters; an escaped lone surrogate such as"\"\\uDEAD\""or{"\uD800":1}is pure ASCII and passes.JsonDocument.Parsethen parses via UTF-8, andJsonProperty.Name(line 29/34) andJsonElement.GetString()(line 51) replace invalid\uD800–\uDFFFsurrogate escapes withU+FFFD(`) instead of throwing or preserving the lone surrogatechar. Consequently,ValidateUnicode(value)inQuote(line 89) seesU+FFFDand passes—violating RFC 8785 §3.2.2 (which requires error termination on lone surrogates) and silently mutating/colliding distinct malformed inputs prior toActionJson.Hash`.element.GetDouble()(line 52) throwsFormatException(notJsonException) when a JSON number overflows IEEE-754double(e.g.,1e400), bypassingJsonExceptionerror handling in callers beforeNumber(double)runs.- Fix: Scan escaped string/property tokens via
Utf8JsonReader(reader.ValueSpanwhenreader.ValueIsEscaped) and throwJsonExceptionon any\uD800–\uDBFFnot immediately followed by\uDC00–\uDFFFor any unpaired\uDC00–\uDFFF. On line 52, useif (!element.TryGetDouble(out var d)) throw new JsonException("Non-finite JSON number.");.
3. [MEDIUM] src/Forge.Approvals.Core/ApprovalGate.cs:14-23, src/Forge.Approvals.Core/ApprovalGate.cs:27-34, src/Forge.Approvals.Core/ApprovalGate.cs:42-69, src/Forge.Approvals.Core/Models.cs:52-56 — Validation errors misclassified as ProviderUnavailable, swallowed caller cancellation, unobserved timeout faults, and clock TOCTOU race¶
- Problem:
- Validation errors masked as provider outages: In
Evaluate(lines 42–46, 62, 68), anullrequest, an invalidrequest.Action(ActionJson.Hash->ActionJson.ValidatethrowingJsonException/ArgumentNullException), or a tamperedCreatedUtcnearDateTimeOffset.MinValue(AddMinutes(-2)throwingArgumentOutOfRangeException) hitscatch (Exception)and returnsApprovalDecision.ProviderUnavailableinstead ofApprovalDecision.Invalid. InRequestAsync(lines 15–16, 23),ApprovalRequest.Createvalidation exceptions (ArgumentOutOfRangeException/JsonException) likewise returnProviderUnavailableafter advancingclock.TryRecordAsync. Treating deterministic malformed/tampered inputs as transient upstream outages corrupts retry/backoff behavior and outage alerting. - Cancellation & unobserved task faults:
RequestAsync,NotifyPersistedAsync, andEvaluateswallowOperationCanceledExceptionwhen the caller's owncancellationTokenis canceled. InNotifyPersistedAsync(line 32), if.WaitAsync(timeout.Token)times out at 10s and the abandonednotifier.NotifyAsynctask faults later, its exception goes unobserved (TaskScheduler.UnobservedTaskException). - Clock TOCTOU race: Sampling
var now = clock.UtcNowand then callingawait clock.TryRecordAsync(now, ...)(ApprovalGate.cs:14-15, 67-68) races under concurrentRequestAsync/Evaluatecalls: Thread B can sampleT2 > T1and recordT2before Thread A callsTryRecordAsync(T1), causing legitimate parallel calls to fail asApprovalDecision.InvalidifIApprovalClockenforces non-decreasing timestamps. - Fix:
- Add
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }beforecatch (Exception)in all three methods. - Validate
request/action/lifetimeandrequest.CreatedUtc >= DateTimeOffset.UnixEpochbefore recording clock state, catchingJsonException/ArgumentExceptionto returnApprovalDecision.Invalid. - In
NotifyPersistedAsync, capture theNotifyAsynctask and observe late faults viaContinueWith(static t => _ = t.Exception, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously)beforeWaitAsync. - Replace split
UtcNow+TryRecordAsync(now)onIApprovalClockwith an atomicTryAdvanceUtcNowAsync(CancellationToken)that samples and records monotonic time inside one critical section/transaction.
4. [MEDIUM] src/Forge.Approvals.Core/Models.cs:12-14, src/Forge.Approvals.Core/Models.cs:107-115, src/Forge.Approvals.Core/Models.cs:131-139 — Non-canonical CommandSha256/Amount ("-0"), missing Spend/whitespace target validation, and broken record equality¶
- Problem:
CommandSha256(line 107) checksUri.IsHexDigit, permitting uppercase/mixed-case hex, whereas digests elsewhere use lowercase hex; case differences produce divergentActionHashvalues for the exact same command SHA-256.ExactDecimalConverter(lines 131–139) accepts"-0"because C#decimalpreserves its negative sign bit and(-0m).ToString("0.############################", InvariantCulture)formats as"-0"in modern .NET, producing distinctActionHashdigests for"0"vs"-0"despite-0m == 0m.ActionJson.Validate(lines 110–115) checksstring.IsNullOrWhiteSpaceon top-level labels (line 104) but not on non-nullTargetstrings (Repo,Host,Path,Currency,Destination) orTarget.Recipientsentries (""and" "passValidateLabel), and does not requireTarget.Amount > 0whenKind == ActionKind.Spend—allowing aSpendchallenge to omitAmount/Currencycompletely or pass blank currency / non-positive amounts.ActionTarget(lines 12–14) is arecordcontainingIReadOnlyList<string>? Recipients, which uses reference equality and breaks value equality (==/Equals/GetHashCode) acrossActionTarget,HardStopAction, andApprovalRequestwheneverRecipientsis populated.- Fix: Restrict
CommandSha256to lowercase hex (0-9,a-f); reject negative zero (value == 0m && decimal.IsNegative(value)) inExactDecimalConverter; require!string.IsNullOrWhiteSpaceon all non-nullTargetstrings andRecipientsitems (plus non-emptyRecipientswhen provided) and requireTarget.Amount > 0forActionKind.Spend; implement sequence-basedEquals/GetHashCodeonActionTarget.
Backend Concurrency & Cancellation Test Requirements (Missing in This Chunk)¶
Ensure the test suite for Forge.Approvals includes the following concurrency/resilience tests:
1. Evaluate_ParallelConsume_AllowsSingleWinner: Task.WhenAll over $N$ concurrent Evaluate(..., consume: true) calls for one approved Jti returns Approved for exactly one caller and Denied for $N - 1$.
2. ApprovalGate_ParallelRequestsAndEvaluations_NoMonotonicClockRace: Task.WhenAll over concurrent RequestAsync and Evaluate calls against the real IApprovalClock implementation never triggers false ApprovalDecision.Invalid rollback rejections.
3. Evaluate_RetryAfterProviderUnavailable_RemainsIdempotent: Transient ProviderUnavailable (or provider exception) does not consume Jti in IReplayStore, allowing subsequent retry within ExpiresUtc to return Approved once.
4. ApprovalGate_CallerCancellationAndHungNotifier_HandledCleanly: Canceled caller CancellationToken rethrows OperationCanceledException from RequestAsync, NotifyPersistedAsync, and Evaluate; a hung IApprovalNotifier that faults after the 10s deadline returns within ~10s and raises no TaskScheduler.UnobservedTaskException upon GC.