You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(auth): decode az and gh CLI credentials as UTF-8 in caller thread - #5500
Both CLI-backed authentication providers in specify_cli.authentication — AzureDevOpsAuth._acquire_via_az_cli() (src/specify_cli/authentication/azure_devops.py) and GitHubAuth._acquire_via_gh_cli() (src/specify_cli/authentication/github.py) — ran subprocess.run(..., capture_output=True, text=True) without an explicit encoding, decoding UTF-8 az and gh output with the host locale encoding (cp1252 by default on Windows) on background subprocess._readerthread threads:
AzureDevOpsAuth (auth: "azure-cli"): When az account get-access-token --output json returned valid UTF-8 JSON containing bytes undefined in cp1252 (such as 0x90 in CJK subscription names or 0x9D in right double quotation marks), or malformed bytes containing 0x81..0x9D, subprocess._readerthread failed with UnicodeDecodeError and left result.stdout as None. _json.loads(result.stdout) then raised an unhandled TypeError: the JSON object must be str, bytes or bytearray, not NoneType, crashing resolve_token(), build_request(), and open_url() instead of returning the token or degrading to None (fix(auth): Azure DevOps az-CLI token returns None on undecodable output instead of crashing #3527). Invalid UTF-8 bytes defined in cp1252 (such as 0xFF) decoded as U+00FF and returned a corrupted non-ASCII token instead of None.
GitHubAuth (auth: "github-cli"): When gh auth token emitted invalid UTF-8 bytes or non-ASCII UTF-8 bytes undefined in cp1252, subprocess._readerthread left result.stdout as None, causing result.stdout.strip() to raise an unhandled AttributeError: 'NoneType' object has no attribute 'strip' past GitHubCliAuthError sanitization and per-host failure caching (feat(auth): support GitHub CLI credentials #4960), while invalid UTF-8 high bytes such as 0xFF decoded under cp1252 and misclassified decode failures as malformed token.
Non-zero exits with UTF-8 stderr:capture_output=True, text=True decoded unread stderr on a reader thread as well, raising unhandled background-thread UnicodeDecodeError on Windows (and masking returncode != 0gh auth login guidance under cp1252 on POSIX).
This PR removes text=True from both subprocess.run() calls and decodes result.stdout as UTF-8 in the caller thread (mirroring GitHubStep._run() in #5477 and mcp_server/executor.py).
Testing
Set up this checkout's .venv and editable install using the local development guide. Run commands from the checkout root.
Tested locally with .venv/bin/specify --help (Windows PowerShell: .\.venv\Scripts\specify.exe --help)
Ran relevant existing tests with .venv/bin/python -m pytest tests -q (Windows PowerShell: .\.venv\Scripts\python.exe -m pytest tests -q); use affected test paths for focused checks and LC_ALL=en_US.UTF-8 on macOS
Tested with a sample project (if applicable)
Added TestCliCredentialSubprocessEncoding (8 real-subprocess test cases across 6 test methods) in tests/specify_cli/authentication/test_authentication.py under cp1252 default text encoding with threading.excepthook monitoring:
test_azure_cli_real_subprocess_decodes_utf8_json_under_cp1252: verifies AzureDevOpsAuth resolves accessToken when az emits raw UTF-8 JSON containing CJK text and curly quotes (0x90, 0x9D). Fails on main (TypeError) and passes with this fix.
test_azure_cli_real_subprocess_invalid_utf8_returns_none (cp1252-undefined-byte, invalid-utf8-json-string): verifies malformed non-UTF-8 az stdout (0x81 0xFF and {"accessToken": "secret\xff"}) returns None cleanly with no reader-thread exception. Both fail on main (TypeError and corrupted 'secret\xff') and pass with this fix.
test_build_request_falls_through_when_azure_cli_returns_invalid_utf8: verifies http.build_request() falls through from a failing azure-cli entry to a subsequent bearer entry when az emits invalid UTF-8. Fails on main (TypeError) and passes with this fix.
test_github_cli_real_subprocess_invalid_utf8_caches_sanitized_failure (cp1252-undefined-byte, latin-high-byte): verifies malformed non-UTF-8 gh stdout raises cached sanitized GitHubCliAuthError (could not provide a token) without leaking CLI output. Both fail on main (AttributeError and misclassified malformed token) and pass with this fix.
test_github_cli_real_subprocess_utf8_non_ascii_token_raises_malformed_token: verifies UTF-8 non-ASCII gh stdout containing U+201D (0x9D) raises cached sanitized GitHubCliAuthError (malformed token) without leaking CLI output. Fails on main (AttributeError) and passes with this fix.
test_cli_providers_nonzero_exit_with_utf8_stderr_do_not_fail_decoding: verifies non-zero gh and az exits with UTF-8 stderr (0x90, 0x9D) emit zero unhandled reader-thread exceptions and preserve gh auth login --hostname github.com guidance. Fails on main (UnicodeDecodeError in _readerthread) and passes with this fix.
Suite runs:
tests/specify_cli/authentication: 506 passed, 1 skipped (406 passed, 1 skipped in test_authentication.py, 100 passed in test_github_http.py).
uvx ruff@0.15.0 check src tests, .github/scripts/check_extension_version_bump.py origin/main HEAD, .github/scripts/check_file_helper_migration.py --base origin/main --head HEAD, and git diff origin/main...HEAD --check: all clean.
AI Disclosure
I did not use AI assistance for this contribution
I did use AI assistance (fill in the disclosure below)
AI disclosure: OpenCode with Gemini 4 Carbon (max reasoning effort, autonomous agent mode), acting on behalf of @adityajai119, found and reproduced the bug, wrote the fix and regression tests, ran all checks above, and drafted this PR description. The commit carries an Assisted-by: OpenCode (model: Gemini 4 Carbon, autonomous) trailer.
AzureDevOpsAuth._acquire_via_az_cli() and GitHubAuth._acquire_via_gh_cli()
invoked subprocess.run(..., capture_output=True, text=True) without an
explicit encoding, decoding CLI stdout and stderr with the host locale
encoding inside background reader threads on Windows. When az or gh output
contained UTF-8 bytes undefined in cp1252 (such as 0x81, 0x90, or 0x9D),
subprocess._readerthread failed with UnicodeDecodeError and left
result.stdout as None, raising an unhandled TypeError from json.loads(None)
in AzureDevOpsAuth and an unhandled AttributeError from result.stdout.strip()
in GitHubAuth, while invalid UTF-8 high bytes such as 0xFF decoded as U+00FF
under cp1252 instead of failing UTF-8 decoding.
Capture raw subprocess bytes without reader-thread text decoding and decode
stdout as UTF-8 in the caller thread so valid UTF-8 az JSON resolves tokens
across all locales, invalid UTF-8 az output returns None and preserves
fallback, invalid or non-ASCII gh output raises cached sanitized
GitHubCliAuthError, and non-zero exits with UTF-8 stderr produce no
reader-thread decode errors.
Fixesgithub#5499
Assisted-by: OpenCode (model: Gemini 4 Carbon, autonomous)
Fixes #5499 by decoding Azure and GitHub CLI credentials as UTF-8 in the caller thread, avoiding locale-dependent crashes while preserving authentication fallback and sanitized errors.
Changes:
Capture raw subprocess bytes from az and gh, then decode stdout explicitly.
Add real-subprocess regression cases for UTF-8 output, malformed bytes, authentication fallback, and non-zero exits.
AI-generated review for the requester by GitHub Copilot (model: unknown; autonomous; code/test inspection and a focused shim check). Project tests were not run during this review.
Add a real-subprocess byte-output success test for GitHubAuth.resolve_token() resolving a whitespace- and CRLF-padded UTF-8 token twice to verify UTF-8 decoding, trimming, and single-invocation caching. Also include surrounding token whitespace and CRLF in the real-subprocess AzureDevOpsAuth UTF-8 JSON test.
Assisted-by: OpenCode (model: Gemini 4 Carbon, autonomous)
Added TestCliCredentialSubprocessEncoding.test_github_cli_real_subprocess_decodes_trims_and_caches_token_bytes in tests/specify_cli/authentication/test_authentication.py, running a real Python subprocess that writes b" gho_test_token_123 \r\n", resolving GitHubAuth().resolve_token(_github_cli_entry()) twice, asserting both return "gho_test_token_123", the subprocess executes once, and no reader-thread decode errors occur.
Updated TestCliCredentialSubprocessEncoding.test_azure_cli_real_subprocess_decodes_utf8_json_under_cp1252 to include surrounding token whitespace and trailing \r\n on the UTF-8 JSON byte payload so trimming is also exercised on real Azure CLI byte output.
Verification on 05a7cdd (Windows / Python 3.14.7):
AI disclosure: posted on behalf of @adityajai119 by OpenCode (model: Gemini 4 Carbon, autonomous mode); extent: test update, local verification runs, commit/push, and posting this reply.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
An active shim-isolation issue in the authentication test duplicates the script path and increments the GitHub counter during the Azure call, even though current assertions pass.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Restore the GitHub shim before installing the Azure shim
The second shim installation captures the first wrapper because both providers share the global subprocess module. This duplicates the script path and increments the GitHub shim’s counter during the Azure call, although the current assertions still pass. Optional: scope the GitHub setup with monkeypatch.context() so it is restored before installing the Azure shim.
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
triage-must-haveVerdict: high-value, important work for Spec Kit — do first
3 participants
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.
You can’t perform that action at this time.
✕
Wait! Don't Go Yet 🚀
Get our FREE eBook "10 Programming Tips That Changed Everything" when you subscribe!
Description
Fixes #5499.
Both CLI-backed authentication providers in
specify_cli.authentication—AzureDevOpsAuth._acquire_via_az_cli()(src/specify_cli/authentication/azure_devops.py) andGitHubAuth._acquire_via_gh_cli()(src/specify_cli/authentication/github.py) — ransubprocess.run(..., capture_output=True, text=True)without an explicitencoding, decoding UTF-8azandghoutput with the host locale encoding (cp1252by default on Windows) on backgroundsubprocess._readerthreadthreads:AzureDevOpsAuth(auth: "azure-cli"): Whenaz account get-access-token --output jsonreturned valid UTF-8 JSON containing bytes undefined incp1252(such as0x90in CJK subscription names or0x9Din right double quotation marks), or malformed bytes containing0x81..0x9D,subprocess._readerthreadfailed withUnicodeDecodeErrorand leftresult.stdoutasNone._json.loads(result.stdout)then raised an unhandledTypeError: the JSON object must be str, bytes or bytearray, not NoneType, crashingresolve_token(),build_request(), andopen_url()instead of returning the token or degrading toNone(fix(auth): Azure DevOps az-CLI token returns None on undecodable output instead of crashing #3527). Invalid UTF-8 bytes defined incp1252(such as0xFF) decoded asU+00FFand returned a corrupted non-ASCII token instead ofNone.GitHubAuth(auth: "github-cli"): Whengh auth tokenemitted invalid UTF-8 bytes or non-ASCII UTF-8 bytes undefined incp1252,subprocess._readerthreadleftresult.stdoutasNone, causingresult.stdout.strip()to raise an unhandledAttributeError: 'NoneType' object has no attribute 'strip'pastGitHubCliAuthErrorsanitization and per-host failure caching (feat(auth): support GitHub CLI credentials #4960), while invalid UTF-8 high bytes such as0xFFdecoded undercp1252and misclassified decode failures asmalformed token.stderr:capture_output=True, text=Truedecoded unreadstderron a reader thread as well, raising unhandled background-threadUnicodeDecodeErroron Windows (and maskingreturncode != 0gh auth loginguidance undercp1252on POSIX).This PR removes
text=Truefrom bothsubprocess.run()calls and decodesresult.stdoutas UTF-8 in the caller thread (mirroringGitHubStep._run()in #5477 andmcp_server/executor.py).Testing
Set up this checkout's
.venvand editable install using the local development guide. Run commands from the checkout root..venv/bin/specify --help(Windows PowerShell:.\.venv\Scripts\specify.exe --help).venv/bin/python -m pytest tests -q(Windows PowerShell:.\.venv\Scripts\python.exe -m pytest tests -q); use affected test paths for focused checks andLC_ALL=en_US.UTF-8on macOSAdded
TestCliCredentialSubprocessEncoding(8 real-subprocess test cases across 6 test methods) intests/specify_cli/authentication/test_authentication.pyundercp1252default text encoding withthreading.excepthookmonitoring:test_azure_cli_real_subprocess_decodes_utf8_json_under_cp1252: verifiesAzureDevOpsAuthresolvesaccessTokenwhenazemits raw UTF-8 JSON containing CJK text and curly quotes (0x90,0x9D). Fails onmain(TypeError) and passes with this fix.test_azure_cli_real_subprocess_invalid_utf8_returns_none(cp1252-undefined-byte,invalid-utf8-json-string): verifies malformed non-UTF-8azstdout (0x81 0xFFand{"accessToken": "secret\xff"}) returnsNonecleanly with no reader-thread exception. Both fail onmain(TypeErrorand corrupted'secret\xff') and pass with this fix.test_build_request_falls_through_when_azure_cli_returns_invalid_utf8: verifieshttp.build_request()falls through from a failingazure-clientry to a subsequentbearerentry whenazemits invalid UTF-8. Fails onmain(TypeError) and passes with this fix.test_github_cli_real_subprocess_invalid_utf8_caches_sanitized_failure(cp1252-undefined-byte,latin-high-byte): verifies malformed non-UTF-8ghstdout raises cached sanitizedGitHubCliAuthError(could not provide a token) without leaking CLI output. Both fail onmain(AttributeErrorand misclassifiedmalformed token) and pass with this fix.test_github_cli_real_subprocess_utf8_non_ascii_token_raises_malformed_token: verifies UTF-8 non-ASCIIghstdout containingU+201D(0x9D) raises cached sanitizedGitHubCliAuthError(malformed token) without leaking CLI output. Fails onmain(AttributeError) and passes with this fix.test_cli_providers_nonzero_exit_with_utf8_stderr_do_not_fail_decoding: verifies non-zeroghandazexits with UTF-8stderr(0x90,0x9D) emit zero unhandled reader-thread exceptions and preservegh auth login --hostname github.comguidance. Fails onmain(UnicodeDecodeErrorin_readerthread) and passes with this fix.Suite runs:
tests/specify_cli/authentication:506 passed, 1 skipped(406 passed, 1 skippedintest_authentication.py,100 passedintest_github_http.py).2562 passed, 38 skipped, 0 failed.uvx ruff@0.15.0 check src tests,.github/scripts/check_extension_version_bump.py origin/main HEAD,.github/scripts/check_file_helper_migration.py --base origin/main --head HEAD, andgit diff origin/main...HEAD --check: all clean.AI Disclosure
AI disclosure: OpenCode with Gemini 4 Carbon (max reasoning effort, autonomous agent mode), acting on behalf of @adityajai119, found and reproduced the bug, wrote the fix and regression tests, ran all checks above, and drafted this PR description. The commit carries an
Assisted-by: OpenCode (model: Gemini 4 Carbon, autonomous)trailer.