Skip to content

fix: hardening across webhooks, session, client, vault, passwordless - #253

Merged
gjtorikian merged 11 commits into
mainfrom
updates
May 11, 2026
Merged

gjtorikian merged 11 commits into
mainfrom
updates

Conversation

@gjtorikian

@gjtorikian gjtorikian commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Description

Summary

  • Webhooks: signature header now requires exactly two comma-separated parts before indexing, avoiding IndexOutOfRangeException on malformed input; malformed headers and timestamp parse errors surface as WorkOSWebhookException; timestamp tolerance check is symmetric (Math.Abs(...)) so far-future timestamps are rejected like too-old ones, matching ActionsService.VerifyHeader.
  • Session: ValidateJwt now enforces token lifetime and accepted signing algorithms, defaulting to RS256. Issuer and audience validation are available through additive optional ValidIssuer / ValidAudience properties, but remain opt-in until the canonical WorkOS claim values are confirmed.
  • Client: idempotency key is generated once in MakeRawAPIRequest before the retry loop instead of per-attempt in CreateHttpRequestMessage, so retried POSTs reuse the same key and server-side dedup actually works.
  • Vault: DecodeLeb128 is bounded to 4 continuation bytes and rejects truncated prefixes; DecryptAsync validates the decoded key length fits the remaining buffer before allocating, preventing ~4 GB allocations from pathological inputs.
  • Passwordless: sessionId is wrapped with Uri.EscapeDataString in SendSession, matching every other generated service path and blocking path traversal / URL injection.

Reviewer notes

  • JWT issuer/audience enforcement is intentionally not enabled by default in this revision because the exact WorkOS access-token issuer/audience behavior still needs confirmation, especially for custom auth domains.
  • This means the session change is an algorithm/lifetime hardening plus opt-in issuer/audience validation, not full default iss/aud enforcement.

Test plan

  • Webhooks: malformed signature header, non-numeric timestamp, and far-future timestamp all surface WorkOSWebhookException
  • Session: JWT with wrong algorithm is rejected; ValidIssuer / ValidAudience / ValidAlgorithms overrides work as expected
  • Client: retried POST under transient failure sends the same Idempotency-Key on every attempt
  • Vault: malformed LEB128 prefix and oversized key-length claims fail cleanly without large allocations
  • Passwordless: SendSession with a sessionId containing reserved URL chars hits the correctly-escaped path

Documentation

Does this require changes to the WorkOS Docs? E.g. the API Reference or code snippets need updates.

[ ] Yes

Link to Devin session: https://app.devin.ai/sessions/eb5c055e7c324404990419c4a8f6f26d
Requested by: @gjtorikian

gjtorikian and others added 6 commits May 7, 2026 14:34
Wrap sessionId with Uri.EscapeDataString in PasswordlessService.SendSession
to match every other generated service path interpolation. Prevents path
traversal / URL-injection via malformed session identifiers.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
DecodeLeb128 now caps at 4 continuation bytes and rejects truncated
prefixes. DecryptAsync validates that the decoded key length fits in
the remaining buffer before allocating, preventing pathological inputs
from triggering ~4 GB allocations.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Move auto-generation of the Idempotency-Key GUID out of
CreateHttpRequestMessage (which runs once per attempt) and into
MakeRawAPIRequest before the retry loop. All retries for a given
request now send the same key, so server-side dedup actually works
and a duplicate write cannot slip through on a retried POST.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ValidateJwt now sets ValidateIssuer, ValidateAudience, and ValidAlgorithms
on TokenValidationParameters. Defaults derive from the configured client
({ApiBaseURL}/user_management/{clientId} as the issuer; clientId as the
audience; RS256 as the only accepted algorithm). Each of these is
overridable via additive optional properties (ValidIssuer, ValidAudience,
ValidAlgorithms) on SessionService so existing callers keep working — no
required-parameter break.

Leaves a TODO comment on the literal documented WorkOS issuer/audience
strings.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
GetTimestampAndSignature now validates that the signature header splits
into exactly two comma-separated parts before indexing, preventing an
IndexOutOfRangeException on malformed input. VerifyTimeTolerance wraps
long.Parse and the UnixTimeToDateTime / AddMilliseconds path in
try/catch and re-raises as WorkOSWebhookException so callers see a
single, expected exception type for malformed timestamps.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Replace the one-sided "now - timestamp > tolerance" comparison with
Math.Abs(nowMs - timestampMs) > tolerance * 1000L so a far-future
timestamp is rejected the same way a too-old one is. Matches the
ActionsService.VerifyHeader pattern. The unused UnixTimeToDateTime
helper is removed in the same change.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@gjtorikian
gjtorikian requested review from a team as code owners May 8, 2026 17:02
@gjtorikian
gjtorikian requested a review from mthadley May 8, 2026 17:02
@greptile-apps

greptile-apps Bot commented May 8, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR applies targeted security hardening across six components — webhooks, session JWT validation, HTTP client retries, vault decryption, and passwordless URL construction — all of which had exploitable edge cases. The algorithm / lifetime hardening in SessionService and the DecodeLeb128 bounds checks in VaultService are the highest-value changes.

  • Webhooks: GetTimestampAndSignature now uses a uniform WorkOSWebhookException and rejects headers that don't split into exactly two comma-separated parts; VerifyTimeTolerance is symmetric and wraps parse errors.
  • Session: ValidateLifetime = true and ValidAlgorithms (defaulting to RS256) are now enforced unconditionally; iss/aud enforcement is intentionally opt-in pending confirmation of WorkOS canonical claim values.
  • Vault / Client / Passwordless: DecodeLeb128 is bounded to 4 continuation bytes and validates the decoded key length against the remaining buffer; idempotency key is generated once before the retry loop; sessionId is URL-encoded in the passwordless path.

Confidence Score: 4/5

Safe to merge for the vault, client, passwordless, and webhook hardening; the session service ships with issuer and audience validation deliberately disabled by default, an open item acknowledged in the PR description that existing review threads have flagged.

The vault, webhook, idempotency, and URL-encoding changes are straightforward and correct. The session service intentionally leaves iss/aud enforcement opt-in pending confirmation of WorkOS canonical claim values — a deliberate deferral that existing review threads already track. Until that gap is closed, the JWT validation is incomplete relative to the team's stated rule that both claims must always be validated.

src/WorkOS.net/Services/Session/SessionService.cs — the opt-in issuer/audience validation leaves a security gap that should be resolved before treating the session hardening as complete.

Important Files Changed

Filename Overview
src/WorkOS.net/Services/Session/SessionService.cs Adds ValidAlgorithms (defaulting to RS256) and ValidateLifetime = true; makes iss/aud validation opt-in — a deliberate but open deferral acknowledged in the PR description and flagged in existing review threads.
src/WorkOS.net/Services/Webhooks/WebhookService.cs Exception type is now consistent (WorkOSWebhookException throughout); symmetric tolerance check replaces one-sided comparison; malformed headers are rejected before array indexing.
src/WorkOS.net/Services/Vault/VaultService.cs LEB128 decoder now caps at 4 continuation bytes and checks for truncated input; keyLen is validated against remaining buffer length before allocation, preventing multi-GB heap allocations from malicious payloads.
src/WorkOS.net/Client/WorkOSClient.cs Idempotency key is now generated once before the retry loop so all retry attempts carry the same key, making server-side deduplication effective.
src/WorkOS.net/Services/Passwordless/PasswordlessService.cs Wraps sessionId with Uri.EscapeDataString in the request path, blocking path traversal / URL injection; consistent with every other service path in the SDK.
test/WorkOSTests/Services/Webhooks/ConstructEventTest.cs Malformed-header assertion updated from ArgumentException to WorkOSWebhookException to match the new consistent exception contract; all test timestamps use milliseconds, consistent with the refactored VerifyTimeTolerance.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Incoming Webhook] --> B{signatureHeader not null?}
    B -- No --> E1[WorkOSWebhookException]
    B -- Yes --> C{Split on comma = exactly 2 parts?}
    C -- No --> E1
    C -- Yes --> D{Contains t= AND v1=?}
    D -- No --> E1
    D -- Yes --> F[Extract timestamp and hash]
    F --> G{Parse timestamp as long}
    G -- FormatException/Overflow --> E1
    G -- OK --> H{abs delta within tolerance x 1000 ms?}
    H -- No --> E2[WorkOSWebhookException: Timestamp outside tolerance]
    H -- Yes --> I{HMAC-SHA256 match constant-time?}
    I -- No --> E3[WorkOSWebhookException: Signature mismatch]
    I -- Yes --> J[Webhook verified]

    K[Session JWT] --> L[Fetch JWKS config]
    L --> M[JwtSecurityTokenHandler ValidateToken]
    M --> N{Algorithm in ValidAlgorithms default RS256?}
    N -- No --> F2[SecurityTokenException]
    N -- Yes --> O{Lifetime valid nbf / exp?}
    O -- No --> F2
    O -- Yes --> P{ValidIssuer set?}
    P -- Yes --> Q{iss matches?}
    Q -- No --> F2
    Q -- Yes --> R{ValidAudience set?}
    P -- No --> R
    R -- Yes --> S{aud matches?}
    S -- No --> F2
    S -- Yes --> T[JWT valid]
    R -- No --> T

    U[Vault DecryptAsync] --> V[DecodeLeb128 max 4 bytes]
    V --> W{keyLen within remaining buffer?}
    W -- No --> F3[InvalidOperationException]
    W -- Yes --> X[Allocate and copy key bytes]
    X --> Y[AES-GCM Decrypt]
Loading

Reviews (6): Last reviewed commit: "fix(session): treat empty ValidAlgorithm..." | Re-trigger Greptile

gjtorikian and others added 4 commits May 8, 2026 12:23
…eader

GetTimestampAndSignature now raises WorkOSWebhookException for null,
wrong-arity, and missing-prefix headers instead of ArgumentException.
This keeps the verification path exception contract consistent with
VerifyTimeTolerance, so callers catching WorkOSWebhookException on
VerifyHeader cover every malformed-input case.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Issuer validation is now opt-in via SessionService.ValidIssuer rather
than defaulting to the unverified {ApiBaseURL}/user_management/{clientId}
string. Shipping that derived issuer turned ValidateIssuer = true on by
default against a value that has not been confirmed against real WorkOS
access tokens, which would have rejected every legitimate token after
upgrade. Until the literal issuer string is verified, callers who want
issuer enforcement set it explicitly.

Audience validation no longer silently disables when ClientId is empty:
if neither ValidAudience nor ClientId is set, ValidateJwt now throws
InvalidOperationException instead of skipping the check.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Aligns the malformed-header assertion with the exception type now
raised by GetTimestampAndSignature.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Defaulting ValidAudience to ClientId would reject every legitimate
token on upgrade if WorkOS access tokens carry a different `aud`
(e.g. a resource-server URL rather than the client identifier). The
workos-php investigation under workos/workos-php#386 confirmed that
the canonical WorkOS `iss` / `aud` values are not documented across
SDKs — workos-node validates only signature + algorithm + expiry,
and Ruby/Python skip `aud` entirely.

Audience now mirrors issuer: validated only when ValidAudience is
explicitly configured. Signature, algorithm, and lifetime remain
enforced unconditionally. Once the canonical claim values are
confirmed, defaults can be reintroduced safely.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
An empty IList<string> bypassed the ?? null-coalescing fallback,
leaving the JWT handler with an empty algorithm list — which some
Microsoft.IdentityModel.Tokens runtimes interpret as "accept any
algorithm" rather than rejecting. Default to RS256 when the list
is null OR empty.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@gjtorikian
gjtorikian merged commit 6e4570c into main May 11, 2026
7 checks passed
@gjtorikian
gjtorikian deleted the updates branch May 11, 2026 16:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant