Skip to content

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 sets Approver = ApproverRegistry.Placeholder.Find("andrew"). Because HasPinnedApprover (lines 21–24) requires exact ordinal matches on Identity == Approver.EntityIdentity and Approver.FactorSids.Contains(FactorSid), any real enrolled Twilio Verify Identity/FactorSid fails 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 via FromConfiguration.
  • HasPinnedApprover only checks !string.IsNullOrWhiteSpace(ServiceSid) rather than verifying ServiceSid against a registry/executor pin (FLT-359 requires pinned service/entity/factor), and none of AccountSid, ApiKeySid, ServiceSid, or FactorSid validate 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 unrestricted AuthToken if ApiKeySid is configured with a missing ApiKeySecret while AuthToken is present, and FromConfiguration does not null-check read.
  • Fix: Pass the trusted ApproverRegistry (and pinned ServiceSid) into FromConfiguration(Func<string, string?> read, ApproverRegistry registry, ...) with ArgumentNullException.ThrowIfNull, resolve the approver by configured identity/approver ID instead of ApproverRegistry.Placeholder.Find("andrew"), pin ServiceSid, fail closed if partial API-key fields (ApiKeySid XOR ApiKeySecret) 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.Parse then parses via UTF-8, and JsonProperty.Name (line 29/34) and JsonElement.GetString() (line 51) replace invalid \uD800–\uDFFF surrogate escapes with U+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) throws FormatException (not JsonException) when a JSON number overflows IEEE-754 double (e.g., 1e400), bypassing JsonException error handling in callers before Number(double) runs.
  • Fix: Scan escaped string/property tokens via Utf8JsonReader (reader.ValueSpan when reader.ValueIsEscaped) and throw JsonException on any \uD800–\uDBFF not immediately followed by \uDC00–\uDFFF or any unpaired \uDC00–\uDFFF. On line 52, use if (!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), a null request, an invalid request.Action (ActionJson.Hash -> ActionJson.Validate throwing JsonException/ArgumentNullException), or a tampered CreatedUtc near DateTimeOffset.MinValue (AddMinutes(-2) throwing ArgumentOutOfRangeException) hits catch (Exception) and returns ApprovalDecision.ProviderUnavailable instead of ApprovalDecision.Invalid. In RequestAsync (lines 15–16, 23), ApprovalRequest.Create validation exceptions (ArgumentOutOfRangeException/JsonException) likewise return ProviderUnavailable after advancing clock.TryRecordAsync. Treating deterministic malformed/tampered inputs as transient upstream outages corrupts retry/backoff behavior and outage alerting.
  • Cancellation & unobserved task faults: RequestAsync, NotifyPersistedAsync, and Evaluate swallow OperationCanceledException when the caller's own cancellationToken is canceled. In NotifyPersistedAsync (line 32), if .WaitAsync(timeout.Token) times out at 10s and the abandoned notifier.NotifyAsync task faults later, its exception goes unobserved (TaskScheduler.UnobservedTaskException).
  • Clock TOCTOU race: Sampling var now = clock.UtcNow and then calling await clock.TryRecordAsync(now, ...) (ApprovalGate.cs:14-15, 67-68) races under concurrent RequestAsync/Evaluate calls: Thread B can sample T2 > T1 and record T2 before Thread A calls TryRecordAsync(T1), causing legitimate parallel calls to fail as ApprovalDecision.Invalid if IApprovalClock enforces non-decreasing timestamps.
  • Fix:
  • Add catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } before catch (Exception) in all three methods.
  • Validate request/action/lifetime and request.CreatedUtc >= DateTimeOffset.UnixEpoch before recording clock state, catching JsonException/ArgumentException to return ApprovalDecision.Invalid.
  • In NotifyPersistedAsync, capture the NotifyAsync task and observe late faults via ContinueWith(static t => _ = t.Exception, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously) before WaitAsync.
  • Replace split UtcNow + TryRecordAsync(now) on IApprovalClock with an atomic TryAdvanceUtcNowAsync(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) checks Uri.IsHexDigit, permitting uppercase/mixed-case hex, whereas digests elsewhere use lowercase hex; case differences produce divergent ActionHash values for the exact same command SHA-256.
  • ExactDecimalConverter (lines 131–139) accepts "-0" because C# decimal preserves its negative sign bit and (-0m).ToString("0.############################", InvariantCulture) formats as "-0" in modern .NET, producing distinct ActionHash digests for "0" vs "-0" despite -0m == 0m.
  • ActionJson.Validate (lines 110–115) checks string.IsNullOrWhiteSpace on top-level labels (line 104) but not on non-null Target strings (Repo, Host, Path, Currency, Destination) or Target.Recipients entries ("" and " " pass ValidateLabel), and does not require Target.Amount > 0 when Kind == ActionKind.Spend—allowing a Spend challenge to omit Amount/Currency completely or pass blank currency / non-positive amounts.
  • ActionTarget (lines 12–14) is a record containing IReadOnlyList<string>? Recipients, which uses reference equality and breaks value equality (== / Equals / GetHashCode) across ActionTarget, HardStopAction, and ApprovalRequest whenever Recipients is populated.
  • Fix: Restrict CommandSha256 to lowercase hex (0-9, a-f); reject negative zero (value == 0m && decimal.IsNegative(value)) in ExactDecimalConverter; require !string.IsNullOrWhiteSpace on all non-null Target strings and Recipients items (plus non-empty Recipients when provided) and require Target.Amount > 0 for ActionKind.Spend; implement sequence-based Equals/GetHashCode on ActionTarget.

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.

Jira FLT-359 · Vikunja · BOARD.md