Skip to content

Fix panic in JSONB decoder on invalid version byte#4158

Open
jrey8343 wants to merge 2 commits intolaunchbadge:mainfrom
jrey8343:fix-jsonb-panic
Open

Fix panic in JSONB decoder on invalid version byte#4158
jrey8343 wants to merge 2 commits intolaunchbadge:mainfrom
jrey8343:fix-jsonb-panic

Conversation

@jrey8343
Copy link

@jrey8343 jrey8343 commented Feb 8, 2026

Fixes #4157

Summary

Replaces assert_eq! with proper error handling in the JSONB decoder to prevent panics on untrusted database input.

Changes

  • File: sqlx-postgres/src/types/json.rs
  • Change: Replace assertion with conditional check + error return
  • Lines changed: 8 insertions, 5 deletions

Why This Fix Is Needed

The Decode trait contract requires implementations to return Result<T, Error>, but the current code uses assert_eq! which panics on invalid input. This violates the trait contract and prevents applications from handling errors gracefully.

Before

assert_eq!(
    buf[0], 1,
    "unsupported JSONB format version {}; please open an issue",
    buf[0]
);

After

// Check JSONB version byte - PostgreSQL currently only supports version 1
if buf[0] != 1 {
    return Err(format!(
        "unsupported JSONB format version {} (expected 1)",
        buf[0]
    )
    .into());
}

Testing

  • ✅ Compiles successfully (cargo check -p sqlx-postgres)
  • ✅ Maintains identical behavior for valid input (version byte = 1)
  • ✅ Returns proper error for invalid input instead of panicking
  • ✅ Discovered and validated through fuzzing

Impact

This fix prevents denial-of-service scenarios where malformed JSONB data could crash applications. It allows applications to handle database errors gracefully through the standard Result error handling pattern.

Replace assert_eq! with proper error handling to prevent panic on
untrusted database input. The Decode trait contract requires returning
Result<T, Error>, but the assertion would cause a panic instead.

This issue was discovered through fuzzing and can be triggered by:
- Malformed JSONB data in the database
- Database corruption
- Future PostgreSQL versions with different JSONB formats

The fix replaces the assertion with a conditional check that returns
an appropriate error, maintaining the Decode trait contract and
allowing applications to handle the error gracefully.

Signed-off-by: Jared Reyes <jaredreyespt@gmail.com>
Signed-off-by: Jared Reyes <jaredreyespt@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Panic in JSONB decoder on invalid version byte

1 participant