Skip to content

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

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

Jahnvi Thakkar (jahnvi480) wants to merge 7 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

✅ No regression detected

No consistent slowdowns detected across all 2 environments.

0 IMPROVEMENTS 0 SLOWDOWNS 2/2 ENVIRONMENTS

Coverage: 2 of 2 environments completed. Advisory result; does not block merging.

Performance diagnostics

Phase times are inclusive diagnostics and must not be added together. They identify where measured time changed, not why it changed.

No affected phases or call-count changes were recorded.

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 11.667 ms 10.855 ms -9.0% no signal
SELECT queries 1.435 ms 1.651 ms +11.3% no signal
Row insertion 32.226 ms 33.255 ms +2.0% no signal
Executemany inserts 164.271 ms 171.107 ms +2.9% no signal
Fetch-all queries 126.861 ms 128.586 ms +2.9% no signal
Row-by-row fetching 6.181 ms 6.146 ms -0.3% no signal
Batched row fetching 122.422 ms 125.468 ms +2.1% no signal
Transaction commit and rollback 109.057 ms 109.875 ms +1.2% no signal
Arrow row fetching 102.993 ms 105.645 ms +2.1% no signal
100,000-row insertion 402.372 ms 418.593 ms +0.3% no signal
Row fetching in batches of 100 129.603 ms 129.153 ms +2.5% no signal
Row fetching in batches of 10,000 138.671 ms 138.351 ms -2.4% no signal
Repeated positional queries 34.142 ms 34.075 ms -0.4% no signal
Repeated named-parameter queries 34.822 ms 34.481 ms -1.0% no signal
Legacy 100,000-row insertion 314.480 ms 310.160 ms -2.2% no signal
Insertion with explicit input sizes 582.153 ms 608.948 ms +5.6% no signal
Joined aggregation queries 185.790 ms 182.724 ms -1.6% no signal
Large joined-result fetching 214.870 ms 216.579 ms -0.5% no signal
1.2-million-row fetching 3669.795 ms 3649.210 ms -0.6% no signal
Common table expression queries 5.829 ms 5.902 ms +1.2% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.356 ms 1.343 ms -3.8% no signal
10,000 scalar values / fetchval() (debug disabled) 20.086 ms 20.203 ms -0.0% no signal
10,000 output-converted rows / fetchall() 20.267 ms 20.411 ms +0.7% no signal
10,000 output-converted rows / fetchmany(1000) 26.562 ms 25.590 ms -3.8% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 28.898 ms 28.772 ms -0.5% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 47.096 ms 45.995 ms -2.3% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 60.434 ms 60.520 ms +0.6% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 111.953 ms 111.045 ms -5.3% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 91.597 ms 91.788 ms -3.2% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.932 ms 10.950 ms +1.1% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 45.320 ms 46.302 ms +1.0% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 13.285 ms 13.366 ms -1.3% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 43.941 ms 49.234 ms +11.7% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 16.426 ms 16.856 ms +2.6% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 49.605 ms 49.621 ms +4.1% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.651 ms 15.050 ms +1.3% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 63.710 ms 60.267 ms -1.3% no signal
200,000 x 8 VARCHAR(32) / fetchall control 552.489 ms 565.057 ms +3.6% no signal
200,000 x 8 INT / fetchall control 309.365 ms 309.171 ms +2.8% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 32.688 ms 32.916 ms +1.1% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 81.847 ms 82.388 ms +0.7% no signal
SELECT queries 1.474 ms 1.461 ms +13.3% no signal
Row insertion 33.936 ms 33.583 ms +3.1% no signal
Executemany inserts 155.072 ms 156.800 ms +0.1% no signal
Fetch-all queries 123.965 ms 126.491 ms +1.9% no signal
Row-by-row fetching 6.178 ms 6.375 ms +3.2% no signal
Batched row fetching 122.202 ms 121.853 ms -0.0% no signal
Transaction commit and rollback 114.464 ms 111.848 ms +1.0% no signal
Arrow row fetching 100.732 ms 102.702 ms +0.9% no signal
100,000-row insertion 385.882 ms 385.117 ms +0.1% no signal
Row fetching in batches of 100 129.028 ms 128.431 ms -0.6% no signal
Row fetching in batches of 10,000 131.551 ms 133.537 ms -0.1% no signal
Repeated positional queries 34.298 ms 34.357 ms -1.8% no signal
Repeated named-parameter queries 34.990 ms 34.428 ms -3.5% no signal
Legacy 100,000-row insertion 299.224 ms 282.041 ms -2.3% no signal
Insertion with explicit input sizes 568.405 ms 550.338 ms -1.3% no signal
Joined aggregation queries 166.458 ms 167.640 ms +0.8% no signal
Large joined-result fetching 210.336 ms 198.420 ms -2.1% no signal
1.2-million-row fetching 3558.731 ms 3604.516 ms +0.7% no signal
Common table expression queries 5.285 ms 5.291 ms +0.1% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.629 ms 1.660 ms +1.9% no signal
10,000 scalar values / fetchval() (debug disabled) 20.174 ms 20.264 ms +0.4% no signal
10,000 output-converted rows / fetchall() 19.873 ms 20.074 ms +0.6% no signal
10,000 output-converted rows / fetchmany(1000) 24.982 ms 25.302 ms -0.2% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 28.577 ms 28.982 ms +0.1% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 52.202 ms 50.704 ms -10.1% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 63.036 ms 62.232 ms +1.5% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 112.408 ms 114.457 ms +1.9% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 126.446 ms 126.564 ms -3.4% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.604 ms 10.871 ms +3.6% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 50.907 ms 52.517 ms +10.4% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 12.898 ms 13.148 ms +3.0% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 50.239 ms 51.187 ms +2.0% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 16.700 ms 16.348 ms -1.2% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 54.206 ms 53.807 ms +0.0% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.631 ms 14.647 ms +0.3% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 75.194 ms 75.214 ms +1.2% no signal
200,000 x 8 VARCHAR(32) / fetchall control 522.495 ms 525.277 ms +0.5% no signal
200,000 x 8 INT / fetchall control 282.452 ms 279.786 ms -3.2% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.696 ms 31.562 ms -0.4% no signal
Build and measurement details

ADO build 196099

PR head: 2cbbe0ea66bce874a7906b088c65cbfcfe19b76d
Base: df875895484e9219753bb5bdce9f62cfb462692b
Measured merge: 80315ad34dc3130061ed8cda7227dd2904bdf034

  • Unix / SQL Server 2022: Python 3.12.3, x86_64, SQL 16.0.4325.4; 5 paired comparisons and 1 warmup.
  • Unix / SQL Server 2025: Python 3.12.3, x86_64, SQL 17.0.5065.9; 5 paired comparisons and 1 warmup.

A consistent change requires more than 20% median paired movement, at least 1 ms between the median runtimes, and at least 80% of pairs exceeding the relative threshold in the same direction. A slowdown without enough pair agreement is reported as inconsistent.

The displayed change is the median of paired before-and-after ratios. It is not recalculated from the two displayed median runtimes.

Both revisions use profiling-enabled builds on the same agent and database, with alternating order and discarded warmups. Results are diagnostic and do not represent production-wheel latency.

Raw samples and logs are attached to the ADO run as profiler-* artifacts.

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

96%


🎯 Overall Coverage

87%


📈 Total Lines Covered: 15159 out of 17383
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/pybind/connection/connection.cpp (96.6%): Missing lines 62-63

Summary

  • Total: 58 lines
  • Missing: 2 lines
  • Coverage: 96%

mssql_python/pybind/connection/connection.cpp

Lines 58-67

  58             key = py::cast<int>(item.first);
  59         } catch (const py::cast_error&) {
  60             continue;
  61         } catch (const py::error_already_set&) {
! 62             continue;
! 63         }
  64         if (key == SQL_COPT_SS_ACCESS_TOKEN) {
  65             validateAccessTokenStructure(py::reinterpret_borrow<py::object>(item.second));
  66         }
  67     }


📋 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: 82.5%
mssql_python.pybind.ddbc_bindings.cpp: 83.9%
mssql_python.pybind.connection.connection.cpp: 84.9%
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

Comment thread tests/test_039_rs_runtime_pipelines.py Resolved
Update the profiler pipeline contract for the intentional 120-minute macOS budget so the shared test no longer fails on every platform.

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

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 new test runs with any installed genhtml, including incompatible LCOV 2.4, causing failures outside the dedicated coverage job that pins version 2.6.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

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