Skip to content

server: restore session on change user auth failure (#69692) - #70229

Open
ti-chi-bot wants to merge 1 commit into
pingcap:release-8.5from
ti-chi-bot:cherry-pick-69692-to-release-8.5
Open

server: restore session on change user auth failure (#69692)#70229
ti-chi-bot wants to merge 1 commit into
pingcap:release-8.5from
ti-chi-bot:cherry-pick-69692-to-release-8.5

Conversation

@ti-chi-bot

@ti-chi-bot ti-chi-bot commented Jul 30, 2026

Copy link
Copy Markdown
Member

This is an automated cherry-pick of #69692

What problem does this PR solve?

Issue Number: close #69691

Problem Summary:

COM_CHANGE_USER replaces the connection user/database and opens a new session before the new identity has fully passed authentication. If auth-plugin validation or authentication fails, the function returns the error while the new session can remain attached to the connection, leaving the connection in an inconsistent state.

What changed and how does it work?

This PR makes the change-user session switch failure-safe:

  • snapshot the previous user, database, auth plugin, and TiDB context before opening the new session;
  • restore the previous authenticated session and close the temporary new session if opening/authenticating the new identity fails;
  • close the old context and move the resource-group connection counter only after the new identity has authenticated successfully.

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test
    • I checked and no code files have been changed.

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

Fix a bug that `COM_CHANGE_USER` authentication failure might leave the connection in an inconsistent session state.

Summary by CodeRabbit

  • Bug Fixes

    • Improved connection switching so failed user or database changes preserve the existing session.
    • Ensured authentication failures no longer leave connections in a partially updated state.
    • Preserved session context and credentials after both successful and unsuccessful changes.
  • Tests

    • Added coverage verifying session restoration after failed credential changes.
    • Confirmed successful changes retain the expected session context and authenticated user.

Signed-off-by: bb7133 <bb7133@gmail.com>
@ti-chi-bot ti-chi-bot added release-note Denotes a PR that will be considered when it comes time to generate release notes. size/M Denotes a PR that changes 30-99 lines, ignoring generated files. type/cherry-pick-for-release-8.5 This PR is cherry-picked to release-8.5 from a source PR. labels Jul 30, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 30, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign winoros for approval. For more information see the Code Review Process.
Please ensure that each of them provides their approval before proceeding.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

handleChangeUser now snapshots the existing connection state, restores it when authentication or session setup fails, and closes the previous context after success. Tests verify context, user, database, and session-variable preservation.

Changes

Atomic change-user authentication

Layer / File(s) Summary
Session snapshot and rollback
pkg/server/conn.go
handleChangeUser stages the new identity, restores the prior session and connection fields on failures, and closes the old context after successful authentication.
Session restoration tests
pkg/server/conn_test.go
Tests verify context and user preservation after success, and context, user, database, and session-variable restoration after failure.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: tiancaiamao, yangkeao

Poem

I’m a bunny guarding the session door,
Old context stays when auth fails once more.
New credentials hop, then safely retreat,
Roots and databases remain neat.
thump thump—rollback makes the flow complete!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main fix: restoring session state on change-user auth failure.
Description check ✅ Passed The description matches the template with issue number, problem summary, changes, tests, and release note.
Linked Issues check ✅ Passed The code and tests address #69691 by restoring the prior session on auth/plugin validation failure.
Out of Scope Changes check ✅ Passed The changes stay within the bug fix and its tests; no unrelated scope is introduced.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

Error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions
The command is terminated due to an error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/server/conn_test.go`:
- Around line 1754-1766: The existing handleChangeUser test only covers an
unknown user and does not exercise rollback after authentication failure. Update
the test around cc.handleChangeUser to create or use a valid password-protected
user, provide an invalid authentication response, and then assert the existing
old-session invariants for tc, cc.user, cc.dbname, and session username.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9d5cdd89-1f6c-490d-94cf-d74dfdc0b574

📥 Commits

Reviewing files that changed from the base of the PR and between 0d2e635 and de15638.

📒 Files selected for processing (2)
  • pkg/server/conn.go
  • pkg/server/conn_test.go

Comment thread pkg/server/conn_test.go
Comment on lines +1754 to +1766
data := []byte{}
data = append(data, "missing_user"...)
data = append(data, 0)
data = append(data, 0)
data = append(data, "new_db"...)
data = append(data, 0)
data = append(data, 0, 0)
err = cc.handleChangeUser(context.Background(), data)
require.Error(t, err)
require.Same(t, tc, cc.getCtx())
require.Equal(t, "root", cc.user)
require.Equal(t, "old_db", cc.dbname)
require.Equal(t, "root", cc.ctx.GetSessionVars().User.Username)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Cover rollback after credential authentication fails.

missing_user fails in checkAuthPlugin before openSessionAndDoAuth, leaving the rollback at pkg/server/conn.go Line 2659 untested. Add a valid password-protected user and an invalid auth response, then assert the same old-session invariants.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/server/conn_test.go` around lines 1754 - 1766, The existing
handleChangeUser test only covers an unknown user and does not exercise rollback
after authentication failure. Update the test around cc.handleChangeUser to
create or use a valid password-protected user, provide an invalid authentication
response, and then assert the existing old-session invariants for tc, cc.user,
cc.dbname, and session username.

@codecov

codecov Bot commented Jul 30, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 66.66667% with 8 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (release-8.5@0d2e635). Learn more about missing BASE report.

Additional details and impacted files
@@               Coverage Diff                @@
##             release-8.5     #70229   +/-   ##
================================================
  Coverage               ?   53.6091%           
================================================
  Files                  ?       1848           
  Lines                  ?     666302           
  Branches               ?          0           
================================================
  Hits                   ?     357199           
  Misses                 ?     283583           
  Partials               ?      25520           
Flag Coverage Δ
integration 35.4846% <0.0000%> (?)
unit 65.1916% <66.6666%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
dumpling 55.3108% <0.0000%> (?)
parser ∅ <0.0000%> (?)
br 40.3469% <0.0000%> (?)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ti-chi-bot

ti-chi-bot Bot commented Jul 30, 2026

Copy link
Copy Markdown

@ti-chi-bot: The following test failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
idc-jenkins-ci-tidb/check_dev_2 de15638 link true /test check-dev2

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

@ti-chi-bot ti-chi-bot Bot added cherry-pick-approved Cherry pick PR approved by release team. and removed do-not-merge/cherry-pick-not-approved labels Jul 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cherry-pick-approved Cherry pick PR approved by release team. release-note Denotes a PR that will be considered when it comes time to generate release notes. size/M Denotes a PR that changes 30-99 lines, ignoring generated files. type/cherry-pick-for-release-8.5 This PR is cherry-picked to release-8.5 from a source PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants