-
Notifications
You must be signed in to change notification settings - Fork 47
FIX: Strip stale auth fields from pycore_context after token acquisition in bulkcopy #488
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
bewithgaurav
merged 5 commits into
main
from
bewithgaurav/fix-bulkcopy-entra-auth-cleanup
Apr 3, 2026
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
2bbe919
Strip stale auth fields from pycore_context after token acquisition
bewithgaurav db746a8
Merge branch 'main' of https://github.com/microsoft/mssql-python into…
bewithgaurav f7e4628
linting fix
bewithgaurav 34524dc
Remove unused imports and unnecessary get_settings patching
bewithgaurav 971e2c9
Merge branch 'main' into bewithgaurav/fix-bulkcopy-entra-auth-cleanup
bewithgaurav File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
|
|
||
| """Tests for bulkcopy auth field cleanup in cursor.py. | ||
|
|
||
| When cursor.bulkcopy() acquires an Azure AD token, it must strip stale | ||
| authentication/user_name/password keys from the pycore_context dict before | ||
| passing it to mssql_py_core. The Rust validator rejects access_token | ||
| combined with those fields (ODBC parity). | ||
| """ | ||
|
|
||
| import pytest | ||
| import secrets | ||
| from unittest.mock import MagicMock, patch, PropertyMock | ||
|
|
||
| SAMPLE_TOKEN = secrets.token_hex(44) | ||
|
|
||
|
|
||
| def _make_cursor(connection_str, auth_type): | ||
| """Build a mock Cursor with just enough wiring for bulkcopy's auth path.""" | ||
| from mssql_python.cursor import Cursor | ||
|
|
||
| mock_conn = MagicMock() | ||
| mock_conn.connection_str = connection_str | ||
| mock_conn._auth_type = auth_type | ||
| mock_conn._is_connected = True | ||
|
|
||
| cursor = Cursor.__new__(Cursor) | ||
| cursor._connection = mock_conn | ||
| cursor.closed = False | ||
| cursor.hstmt = None | ||
| return cursor | ||
|
|
||
|
|
||
| class TestBulkcopyAuthCleanup: | ||
| """Verify cursor.bulkcopy strips stale auth fields after token acquisition.""" | ||
|
|
||
| @patch("mssql_python.cursor.get_settings") | ||
| @patch("mssql_python.cursor.logger") | ||
| def test_token_replaces_auth_fields(self, mock_logger, mock_settings): | ||
| """access_token present ⇒ authentication, user_name, password removed.""" | ||
| mock_settings.return_value = MagicMock(logging=False) | ||
| mock_logger.is_debug_enabled = False | ||
|
|
||
|
bewithgaurav marked this conversation as resolved.
Outdated
|
||
| cursor = _make_cursor( | ||
| "Server=tcp:test.database.windows.net;Database=testdb;" | ||
| "Authentication=ActiveDirectoryDefault;UID=user@test.com;PWD=secret", | ||
| "activedirectorydefault", | ||
| ) | ||
|
|
||
| captured_context = {} | ||
|
|
||
| mock_pycore_cursor = MagicMock() | ||
| mock_pycore_cursor.bulkcopy.return_value = { | ||
| "rows_copied": 1, | ||
| "batch_count": 1, | ||
| "elapsed_time": 0.1, | ||
| } | ||
| mock_pycore_conn = MagicMock() | ||
| mock_pycore_conn.cursor.return_value = mock_pycore_cursor | ||
|
|
||
| def capture_context(ctx, **kwargs): | ||
| captured_context.update(ctx) | ||
| return mock_pycore_conn | ||
|
|
||
| mock_pycore_module = MagicMock() | ||
| mock_pycore_module.PyCoreConnection = capture_context | ||
|
|
||
| with ( | ||
| patch.dict("sys.modules", {"mssql_py_core": mock_pycore_module}), | ||
| patch("mssql_python.auth.AADAuth.get_raw_token", return_value=SAMPLE_TOKEN), | ||
| ): | ||
| cursor.bulkcopy("dbo.test_table", [(1, "row")], timeout=10) | ||
|
|
||
| assert captured_context.get("access_token") == SAMPLE_TOKEN | ||
| assert "authentication" not in captured_context | ||
| assert "user_name" not in captured_context | ||
| assert "password" not in captured_context | ||
|
|
||
| @patch("mssql_python.cursor.get_settings") | ||
| @patch("mssql_python.cursor.logger") | ||
| def test_no_auth_type_leaves_fields_intact(self, mock_logger, mock_settings): | ||
| """No _auth_type ⇒ credentials pass through unchanged (SQL auth path).""" | ||
| mock_settings.return_value = MagicMock(logging=False) | ||
| mock_logger.is_debug_enabled = False | ||
|
|
||
| cursor = _make_cursor( | ||
| "Server=tcp:test.database.windows.net;Database=testdb;" "UID=sa;PWD=password123", | ||
| None, # no AD auth | ||
| ) | ||
|
|
||
| captured_context = {} | ||
|
|
||
| mock_pycore_cursor = MagicMock() | ||
| mock_pycore_cursor.bulkcopy.return_value = { | ||
| "rows_copied": 1, | ||
| "batch_count": 1, | ||
| "elapsed_time": 0.1, | ||
| } | ||
| mock_pycore_conn = MagicMock() | ||
| mock_pycore_conn.cursor.return_value = mock_pycore_cursor | ||
|
|
||
| def capture_context(ctx, **kwargs): | ||
| captured_context.update(ctx) | ||
| return mock_pycore_conn | ||
|
|
||
| mock_pycore_module = MagicMock() | ||
| mock_pycore_module.PyCoreConnection = capture_context | ||
|
|
||
| with patch.dict("sys.modules", {"mssql_py_core": mock_pycore_module}): | ||
| cursor.bulkcopy("dbo.test_table", [(1, "row")], timeout=10) | ||
|
|
||
| assert "access_token" not in captured_context | ||
| assert captured_context.get("user_name") == "sa" | ||
| assert captured_context.get("password") == "password123" | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.