Skip to content

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

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

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

1 database task produced inconsistent slowdown signals across 1 measured environment.

0 IMPROVEMENTS 0 SLOWDOWNS 2/2 ENVIRONMENTS

1 INCONSISTENT SLOWDOWN

Signal fingerprint

Database task Unix / SQL Server 2022
10,000 output-converted rows / fetchmany(1000) 47.2% inconsistent

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

Measured timings
Environment Database task Before After Change
Unix / SQL Server 2022 10,000 output-converted rows / fetchmany(1000) 24.068 ms 35.417 ms +47.2%
Performance diagnostics

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

Unix / SQL Server 2022

10,000 output-converted rows / fetchmany(1000): ddbc::NativeCursor::fallback +11.341 ms; py::fetchmany::row_wrap +9.743 ms; py::fetchmany::cpp_call +1.312 ms.

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.563 ms 10.893 ms +1.3% no signal
SELECT queries 1.397 ms 1.306 ms -6.7% no signal
Row insertion 32.534 ms 32.305 ms -0.1% no signal
Executemany inserts 159.350 ms 163.776 ms +2.1% no signal
Fetch-all queries 120.741 ms 121.704 ms +0.7% no signal
Row-by-row fetching 6.042 ms 6.046 ms +0.9% no signal
Batched row fetching 119.923 ms 118.739 ms -1.7% no signal
Transaction commit and rollback 110.612 ms 110.451 ms +1.8% no signal
Arrow row fetching 94.272 ms 93.727 ms -1.5% no signal
100,000-row insertion 363.984 ms 362.713 ms +0.4% no signal
Row fetching in batches of 100 124.713 ms 126.252 ms +1.2% no signal
Row fetching in batches of 10,000 130.014 ms 143.084 ms +6.8% no signal
Repeated positional queries 34.167 ms 34.033 ms -0.2% no signal
Repeated named-parameter queries 34.273 ms 34.484 ms -1.1% no signal
Legacy 100,000-row insertion 286.466 ms 276.201 ms -3.6% no signal
Insertion with explicit input sizes 418.073 ms 423.858 ms +1.4% no signal
Joined aggregation queries 180.162 ms 179.710 ms +0.8% no signal
Large joined-result fetching 193.221 ms 192.384 ms +1.3% no signal
1.2-million-row fetching 3516.395 ms 3558.789 ms +1.4% no signal
Common table expression queries 5.605 ms 5.471 ms -2.5% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.376 ms 1.391 ms +2.2% no signal
10,000 scalar values / fetchval() (debug disabled) 19.530 ms 19.197 ms -1.7% no signal
10,000 output-converted rows / fetchall() 20.086 ms 19.417 ms +0.1% no signal
10,000 output-converted rows / fetchmany(1000) 24.068 ms 35.417 ms +47.2% inconsistent slowdown
10,000 INT/NVARCHAR rows / fetchmany(1) 27.874 ms 28.847 ms +3.6% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 43.518 ms 44.658 ms +3.6% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 57.130 ms 59.593 ms +6.4% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 102.699 ms 112.978 ms +10.1% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 90.413 ms 90.251 ms +0.1% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.253 ms 10.590 ms +3.5% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 43.719 ms 44.646 ms +1.1% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 12.563 ms 12.960 ms +3.1% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 43.657 ms 43.869 ms +1.3% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 16.201 ms 16.151 ms +0.5% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 46.644 ms 48.814 ms +6.3% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.186 ms 14.078 ms -2.4% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 60.454 ms 64.443 ms +6.6% no signal
200,000 x 8 VARCHAR(32) / fetchall control 542.390 ms 531.805 ms -1.2% no signal
200,000 x 8 INT / fetchall control 286.676 ms 284.842 ms -0.6% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 30.955 ms 30.934 ms -0.3% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 81.044 ms 81.754 ms +0.5% no signal
SELECT queries 1.301 ms 1.277 ms -5.4% no signal
Row insertion 31.625 ms 31.576 ms +0.7% no signal
Executemany inserts 152.853 ms 158.876 ms +2.1% no signal
Fetch-all queries 120.340 ms 120.516 ms +0.3% no signal
Row-by-row fetching 6.001 ms 6.035 ms +0.9% no signal
Batched row fetching 116.258 ms 118.698 ms +1.8% no signal
Transaction commit and rollback 108.977 ms 107.314 ms -1.3% no signal
Arrow row fetching 90.772 ms 91.480 ms +3.0% no signal
100,000-row insertion 358.551 ms 359.985 ms +0.4% no signal
Row fetching in batches of 100 127.185 ms 124.881 ms +0.2% no signal
Row fetching in batches of 10,000 127.087 ms 140.205 ms +11.7% no signal
Repeated positional queries 32.928 ms 32.945 ms -0.1% no signal
Repeated named-parameter queries 33.483 ms 33.433 ms +0.1% no signal
Legacy 100,000-row insertion 273.914 ms 273.767 ms -0.7% no signal
Insertion with explicit input sizes 419.648 ms 433.033 ms +2.8% no signal
Joined aggregation queries 167.508 ms 166.601 ms +2.2% no signal
Large joined-result fetching 183.920 ms 185.381 ms +0.3% no signal
1.2-million-row fetching 3511.306 ms 3479.922 ms -0.9% no signal
Common table expression queries 5.114 ms 5.216 ms +1.2% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.734 ms 1.688 ms -2.6% no signal
10,000 scalar values / fetchval() (debug disabled) 19.755 ms 19.071 ms -4.4% no signal
10,000 output-converted rows / fetchall() 19.946 ms 19.850 ms -0.2% no signal
10,000 output-converted rows / fetchmany(1000) 23.198 ms 23.318 ms +0.3% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 27.772 ms 27.453 ms -1.2% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 49.401 ms 49.940 ms -18.7% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 60.262 ms 61.140 ms +1.5% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 116.656 ms 118.332 ms +0.8% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 113.611 ms 115.174 ms +2.0% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.038 ms 10.047 ms +0.1% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 50.098 ms 50.107 ms +0.2% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 12.466 ms 12.679 ms +2.4% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 48.981 ms 49.178 ms +1.7% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 16.170 ms 15.957 ms -2.0% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 52.516 ms 52.187 ms -0.0% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.191 ms 14.046 ms -0.7% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 81.496 ms 76.669 ms -5.4% no signal
200,000 x 8 VARCHAR(32) / fetchall control 512.147 ms 499.818 ms -2.1% no signal
200,000 x 8 INT / fetchall control 270.626 ms 264.135 ms -2.9% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.181 ms 30.745 ms -1.4% no signal
Build and measurement details

ADO build 195424

PR head: 99e018194cd0f32408b2d0cd4339be830a0abd4a
Base: cfd8b9e69699e5e44d7c1d62115dd8b706ac7985
Measured merge: 1620ca3498d80ae04262607e4707bb53dcc40853

  • 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

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

93%


🎯 Overall Coverage

86%


📈 Total Lines Covered: 13590 out of 15747
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/pybind/connection/connection.cpp (93.9%): Missing lines 26-27

Summary

  • Total: 33 lines
  • Missing: 2 lines
  • Coverage: 93%

mssql_python/pybind/connection/connection.cpp

Lines 22-31

  22 
  23 static void validateAccessTokenStructure(const py::object& value) {
  24     const bool isBytes = py::isinstance<py::bytes>(value);
  25     if (!isBytes && !py::isinstance<py::bytearray>(value)) {
! 26         ThrowStdException("SQL_COPT_SS_ACCESS_TOKEN must be supplied as bytes or bytearray.");
! 27     }
  28     const Py_ssize_t bufferSize =
  29         isBytes ? PyBytes_GET_SIZE(value.ptr()) : PyByteArray_GET_SIZE(value.ptr());
  30     if (bufferSize < 4 || bufferSize > std::numeric_limits<SQLINTEGER>::max()) {
  31         ThrowStdException(


📋 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: 69.5%
mssql_python._native_fetch.py: 80.1%
mssql_python.pybind.ddbc_bindings.cpp: 80.5%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 83.1%
mssql_python.pybind.connection.connection.cpp: 84.7%
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
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants