Skip to content

FIX: Validate access-token buffers before ODBC calls - #923

Open
Jahnvi Thakkar (jahnvi480) wants to merge 6 commits into
mainfrom
jahnvi/validate-access-token-crashes
Open

Jahnvi Thakkar (jahnvi480) wants to merge 6 commits into
mainfrom
jahnvi/validate-access-token-crashes

Conversation

@jahnvi480

@jahnvi480 Jahnvi Thakkar (jahnvi480) commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

N/A

GitHub Issue: #278


Summary

Prevent malformed access-token buffers from crashing the ODBC driver or bypassing validation on pooled connections, using shared native validation before pool acquisition and ODBC attribute setting.

  • Validate the four-byte little-endian length header, exact non-empty/even payload length, and ODBC signed size limit before forwarding the token.
  • Validate explicitly supplied tokens before acquiring a pooled connection, so empty bytes or bytearrays cannot reuse a token-free connection without validation.
  • Preserve connection-owned token buffers and accept correctly packed opaque tokens without JWT parsing. Deferred token factories remain lazy and their results are validated when invoked.
  • Add bounded subprocess regressions for public connections, direct native calls, deferred token factories, and warmed token-free pools; document the raw-token contract.

Validation

  • Windows x64 native Release rebuild using CMake/Ninja: passed.
  • Microsoft provider: .venv\Scripts\python.exe -m pytest tests\test_008_auth.py -q -p no:cacheprovider — 249 passed.
  • Rust provider: .venv\Scripts\python.exe -m pytest tests\test_008_auth.py -k 'access_token_structure_in_subprocess or empty_access_token_rejected_before_pool_checkout or TestRawAccessTokenPoolKey' -q -p no:cacheprovider — 52 passed.
  • Warmed-pool regression: all four empty-bytes/empty-bytearray public/native combinations reproduced the bypass before this update; all now reject cleanly on both providers and verify a subsequent healthy checkout. Empty buffers are also covered in the non-pooled matrix.
  • Initial-fix 24-case isolated matrix per provider: all nine former Microsoft crashes prevented; 16 malformed buffers cleanly rejected per provider; no crashes or timeouts.
  • .venv\Scripts\python.exe -m pre_commit run black-check --all-files --hook-stage pre-push — passed.

Limitations: Validation used Windows x64, Python 3.13, and SQL Server 2019 LocalDB. Actual Entra credential rejection, other platforms/architectures, and the full repository suite were not verified. This change validates buffer structure, not credential validity.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 05:35
@github-actions github-actions Bot added the pr-size: medium Moderate update size label Nov 27, 2026
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

PR Performance Report

Performance assessment pending.

Waiting for the matching performance run for head f720a6534e369ac6bfc7f06dfcc26f063a695203.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Explicitly supplied empty tokens can bypass validation and reuse a healthy token-free pooled connection instead of raising OperationalError.

1 open issue
What changed in this PR

Adds defensive access-token buffer validation at the shared C++ attribute boundary to address the ODBC crashes reported in #278, without parsing JWTs or checking credential validity.

Changes:

  • Checks the length header, payload size and alignment, and ODBC’s signed size limit.
  • Adds bounded subprocess regressions for public connections, native connections, and deferred token factories.
  • Documents the raw-token format and validation behavior.

Reported runtime validation covers Windows x64, Python 3.13, and SQL Server 2019 LocalDB; other platforms remain unverified.

File Description
tests/​test_008_auth.py Adds isolated malformed and correctly packed token probes.
README.md Documents the raw-token structure and validation limits.
mssql_python/​pybind/​connection/​connection.cpp Validates token buffers before forwarding the attribute to ODBC.

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 05:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Token validation can be bypassed during pooled connection reuse through same-token refreshes or nonstandard attribute keys, allowing inputs rejected on pool misses to succeed.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Validate token type on near-expiry pool reuse

mssql_python/​pybind/​connection/​connection.cpp:500

Near-expiry pool reuse bypasses this validator if a factory returns a str whose UTF-8 bytes match the stored token (connection_pool.cpp:163–169). The connection can then be reused with refreshed expiry even though the same factory output is rejected on a pool miss. Validate token attributes in both return paths of invokeTokenFactory() and add a regression for same-token refresh.

Medium severity Use attribute-key conversion when validating pool hits

mssql_python/​pybind/​connection/​connection.cpp:958

The pre-checkout lookup does not recognize every key that applyAttrsBefore() treats as attribute 1256: that method converts each key with py::cast<int> (lines 651–669), whereas this lookup uses dictionary equality. For example, an int subclass with value 1256 that compares unequal to plain integers can carry an empty token without triggering this check. A warmed pool then returns a token-free connection, although a pool miss rejects the same attributes. Iterate and convert keys using the same rules as applyAttrsBefore() before validating, so accepted attribute keys cannot bypass validation on pool hits.

1 resolved since last review

Review effort: Balanced

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

100%


🎯 Overall Coverage

87%


📈 Total Lines Covered: 15149 out of 17365
📁 Project: mssql-python


Diff Coverage

Diff: main...HEAD, staged and unstaged changes

  • mssql_python/pybind/connection/connection.cpp (100%)

Summary

  • Total: 33 lines
  • Missing: 0 lines
  • Coverage: 100%

📋 Files Needing Attention

📉 Files with overall lowest coverage (click to expand)
mssql_python.pybind.performance_counter.hpp: 0.7%
mssql_python.pybind.logger_bridge.cpp: 57.9%
mssql_python.pybind.vector_support.hpp: 59.5%
mssql_python.pybind.ddbc_bindings.h: 75.4%
mssql_python._native_fetch.py: 80.1%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 83.7%
mssql_python.pybind.ddbc_bindings.cpp: 83.9%
mssql_python.pybind.connection.connection.cpp: 85.1%
mssql_python.logging.py: 86.8%

🔗 Quick Links

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

@jahnvi480
Jahnvi Thakkar (jahnvi480) marked this pull request as ready for review November 27, 2026 07:58
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 09:26

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The pooled-refresh path can accept a factory’s string token without validating the required bytes/bytearray type, leaving a validation bypass that needs a fix and regression coverage.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Validate deferred factory tokens on pooled reuse

mssql_python/​pybind/​connection/​connection.cpp:500

Deferred factory tokens are not validated on the near-expiry, same-token pool reuse path (connection_pool.cpp:164–169). A factory can return a Python str whose UTF-8 bytes match the stored token and a future expiry; the pool accepts it without calling setAttribute, bypassing the new bytes/bytearray requirement. Validate token attributes inside invokeTokenFactory before returning either supported result form, and add a pooled-refresh regression for this non-binary result.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 28, 2026 11:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Expiry-aware pool reuse can bypass validation and accept a non-binary factory token, requiring validation inside invokeTokenFactory and a near-expiry pooled regression test.

1 open issue

Review effort: Balanced

Validate both token factory return formats before comparison, normalize native attribute-key validation, and name the token header size. Add isolated refresh and key-conversion regressions with valid binary controls.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 30, 2026 08:58

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Native crash-prevention changes require maintainer-confirmed runtime validation on macOS and Linux, as reported runs cover only Windows x64 and this review cannot run native probes.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Install checksum-pinned LCOV 2.6 to fix Python function-record HTML rendering, cover hit and unhit functions, and allow the full macOS suite to finish.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 03:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new regression test is not version-gated, so ordinary full-suite runs with Bash and LCOV 2.4 fail even though only the dedicated coverage job installs the fixed renderer.

1 open issue

Review effort: Balanced

)
@pytest.mark.parametrize("hits", [0, 1])
def test_unified_coverage_html_handles_function_without_line_record(tmp_path, hits):
"""Python LCOV can locate a function on a line without a DA record."""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-size: medium Moderate update size

3 participants