Skip to content

server: restore session on change user auth failure (release-7.5-20260724-v7.5.7) (#69692) | tidb-test=release-7.5.7 tikv=v7.5.7 pd=v7.5.7 tiflash=v7.5.7 - #70171

Merged
bb7133 merged 1 commit into
release-7.5-20260724-v7.5.7from
cp-69692-7.5-v7.5.7
Aug 10, 2026
Merged

server: restore session on change user auth failure (release-7.5-20260724-v7.5.7) (#69692) | tidb-test=release-7.5.7 tikv=v7.5.7 pd=v7.5.7 tiflash=v7.5.7#70171
bb7133 merged 1 commit into
release-7.5-20260724-v7.5.7from
cp-69692-7.5-v7.5.7

Conversation

@bb7133

@bb7133 bb7133 commented Jul 28, 2026

Copy link
Copy Markdown
Member

What problem does this PR solve?

Issue Number: close #69691

Problem Summary:
Cherry-pick #69692 (restore session on change user auth failure) to release-7.5-20260724-v7.5.7.

What changed and how does it work?

Cherry-pick of f1be26c. Conflict adaptations for 7.5:

  • Dropped the resource-group counter tracking lines (not present on this branch).
  • Kept 7.5's openSessionAndDoAuth(auth, authPlugin) signature (no ZstdLevel parameter on this branch).
    go vet ./pkg/server/ passes. See server: restore session on change user auth failure #69692 for the full description.

Check List

Tests

  • Unit test

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 handling when changing user credentials.
    • Preserved the existing authenticated session if the credential change fails.
    • Prevented failed authentication or invalid user changes from leaving the connection in a partially updated state.
    • Ensured the previous user, database, session context, and authentication settings remain available after an unsuccessful change.

@ti-chi-bot ti-chi-bot 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. labels Jul 28, 2026
@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Change-user session restoration

Layer / File(s) Summary
Snapshot and restore change-user state
pkg/server/conn.go
handleChangeUser preserves the existing session state, restores it when session opening or authentication fails, and closes the old context only after successful authentication.
Validate failed change-user restoration
pkg/server/conn_test.go
Tests verify that failed changes retain the original context, user, database, and session username.

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

Sequence Diagram(s)

sequenceDiagram
  participant clientConn
  participant handleChangeUser
  participant SessionAuth
  participant TiDBContext
  clientConn->>handleChangeUser: request user/database change
  handleChangeUser->>SessionAuth: open and authenticate replacement session
  SessionAuth-->>handleChangeUser: success or error
  handleChangeUser->>TiDBContext: restore previous context on error
  handleChangeUser-->>clientConn: return result
Loading

Possibly related PRs

Suggested reviewers: tiancaiamao, yangkeao

Poem

I’m a rabbit guarding the session door,
New credentials hop in, old ones stay ashore.
If auth goes thump and the new path fails,
I restore the context with sturdy rails.
Root remains root, the old state is bright—
Safe change-user through the night.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes match #69691 by making COM_CHANGE_USER restore the prior session or context on auth and plugin validation failure.
Out of Scope Changes check ✅ Passed The patch stays focused on the change-user session restore fix and its tests, with no clear unrelated additions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly identifies the main change: restoring the session after a COM_CHANGE_USER authentication failure, despite including release metadata.
Description check ✅ Passed The description includes the issue, problem, implementation details, tests, branch adaptations, and release note; omitted checklist sections are non-critical.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cp-69692-7.5-v7.5.7

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 1533-1566: Extend the handleChangeUser rollback test around
clientConn initialization and assertions to set a non-empty prior authPlugin
value before invoking cc.handleChangeUser. After the failed change-user attempt,
assert that cc.authPlugin retains the original value alongside the existing
user, database, and session checks.
🪄 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: 22a0c7de-c093-43d5-92bc-c60a957c3ae1

📥 Commits

Reviewing files that changed from the base of the PR and between 972e642 and 1ca5655.

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

Comment thread pkg/server/conn_test.go
Comment on lines +1533 to +1566
cc := &clientConn{
connectionID: 1,
alloc: arena.NewAllocator(1024),
chunkAlloc: chunk.NewAllocator(),
peerHost: "localhost",
collation: mysql.DefaultCollationID,
capability: mysql.ClientProtocol41,
pkt: internal.NewPacketIOForTest(bufio.NewWriter(bytes.NewBuffer(nil))),
server: srv,
user: "root",
dbname: "old_db",
}
se, err := session.CreateSession4Test(store)
require.NoError(t, err)
require.NoError(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil, nil))
tc := &TiDBContext{
Session: se,
stmts: make(map[int]*TiDBStatement),
}
cc.SetCtx(tc)

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

Assert authPlugin rollback too.

This test never sets or verifies a non-empty old plugin, so regression of cc.authPlugin = oldAuthPlugin would still pass.

Proposed test addition
 		server:       srv,
 		user:         "root",
 		dbname:       "old_db",
+		authPlugin:   mysql.AuthNativePassword,
 	}
 ...
 	require.Equal(t, "old_db", cc.dbname)
+	require.Equal(t, mysql.AuthNativePassword, cc.authPlugin)
 	require.Equal(t, "root", cc.ctx.GetSessionVars().User.Username)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cc := &clientConn{
connectionID: 1,
alloc: arena.NewAllocator(1024),
chunkAlloc: chunk.NewAllocator(),
peerHost: "localhost",
collation: mysql.DefaultCollationID,
capability: mysql.ClientProtocol41,
pkt: internal.NewPacketIOForTest(bufio.NewWriter(bytes.NewBuffer(nil))),
server: srv,
user: "root",
dbname: "old_db",
}
se, err := session.CreateSession4Test(store)
require.NoError(t, err)
require.NoError(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil, nil))
tc := &TiDBContext{
Session: se,
stmts: make(map[int]*TiDBStatement),
}
cc.SetCtx(tc)
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)
cc := &clientConn{
connectionID: 1,
alloc: arena.NewAllocator(1024),
chunkAlloc: chunk.NewAllocator(),
peerHost: "localhost",
collation: mysql.DefaultCollationID,
capability: mysql.ClientProtocol41,
pkt: internal.NewPacketIOForTest(bufio.NewWriter(bytes.NewBuffer(nil))),
server: srv,
user: "root",
dbname: "old_db",
authPlugin: mysql.AuthNativePassword,
}
se, err := session.CreateSession4Test(store)
require.NoError(t, err)
require.NoError(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil, nil))
tc := &TiDBContext{
Session: se,
stmts: make(map[int]*TiDBStatement),
}
cc.SetCtx(tc)
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, mysql.AuthNativePassword, cc.authPlugin)
require.Equal(t, "root", cc.ctx.GetSessionVars().User.Username)
🤖 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 1533 - 1566, Extend the
handleChangeUser rollback test around clientConn initialization and assertions
to set a non-empty prior authPlugin value before invoking cc.handleChangeUser.
After the failed change-user attempt, assert that cc.authPlugin retains the
original value alongside the existing user, database, and session checks.

@codecov

codecov Bot commented Jul 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 65.21739% with 8 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (release-7.5-20260724-v7.5.7@972e642). Learn more about missing BASE report.

Additional details and impacted files
@@                       Coverage Diff                        @@
##             release-7.5-20260724-v7.5.7     #70171   +/-   ##
================================================================
  Coverage                               ?   73.0238%           
================================================================
  Files                                  ?       1445           
  Lines                                  ?     421806           
  Branches                               ?          0           
================================================================
  Hits                                   ?     308019           
  Misses                                 ?      94509           
  Partials                               ?      19278           
Flag Coverage Δ
integration 41.1352% <0.0000%> (?)
unit 72.2072% <65.2173%> (?)

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

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

@bb7133

bb7133 commented Aug 3, 2026

Copy link
Copy Markdown
Member Author

/retest

1 similar comment
@jebter

jebter commented Aug 3, 2026

Copy link
Copy Markdown

/retest

@ti-chi-bot ti-chi-bot Bot added needs-1-more-lgtm Indicates a PR needs 1 more LGTM. approved labels Aug 3, 2026
@ti-chi-bot ti-chi-bot Bot added the lgtm label Aug 3, 2026
@ti-chi-bot

ti-chi-bot Bot commented Aug 3, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: wjhuang2016, YangKeao

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

The pull request process is described here

Details Needs approval from an approver in each of these files:
  • OWNERS [YangKeao,wjhuang2016]

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

@ti-chi-bot ti-chi-bot Bot removed the needs-1-more-lgtm Indicates a PR needs 1 more LGTM. label Aug 3, 2026
@ti-chi-bot

ti-chi-bot Bot commented Aug 3, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-08-03 13:52:41.095952459 +0000 UTC m=+2449747.132047515: ☑️ agreed by YangKeao.
  • 2026-08-03 14:03:30.091205109 +0000 UTC m=+2450396.127300175: ☑️ agreed by wjhuang2016.

@jebter

jebter commented Aug 6, 2026

Copy link
Copy Markdown

/retest

2 similar comments
@jebter

jebter commented Aug 6, 2026

Copy link
Copy Markdown

/retest

@jebter

jebter commented Aug 6, 2026

Copy link
Copy Markdown

/retest

@jebter jebter changed the title server: restore session on change user auth failure (release-7.5-20260724-v7.5.7) (#69692) server: restore session on change user auth failure (release-7.5-20260724-v7.5.7) (#69692) | tidb-test=release-7.5.7 tikv=v7.5.7 pd=v7.5.7 tiflash=v7.5.7 Aug 6, 2026
@wuhuizuo

wuhuizuo commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

/retest

@wuhuizuo

wuhuizuo commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

/test check-dev2

1 similar comment
@jebter

jebter commented Aug 7, 2026

Copy link
Copy Markdown

/test check-dev2

@ti-chi-bot

ti-chi-bot Bot commented Aug 7, 2026

Copy link
Copy Markdown

@jebter: The specified target(s) for /test were not found.
The following commands are available to trigger required jobs:

/test build
/test check-dev
/test check-dev2
/test mysql-test
/test unit-test

The following commands are available to trigger optional jobs:

/test pull-br-integration-test
/test pull-common-test
/test pull-e2e-test
/test pull-integration-binlog-test
/test pull-integration-common-test
/test pull-integration-copr-test
/test pull-integration-ddl-test
/test pull-integration-jdbc-test
/test pull-integration-mysql-test
/test pull-integration-nodejs-test
/test pull-integration-python-orm-test
/test pull-integration-tidb-tools-test
/test pull-mysql-client-test
/test pull-sqllogic-test
/test pull-tiflash-test

Use /test all to run the following jobs that were automatically triggered:

pingcap/tidb/release-7.5/ghpr_build
pingcap/tidb/release-7.5/ghpr_check
pingcap/tidb/release-7.5/ghpr_check2
pingcap/tidb/release-7.5/ghpr_mysql_test
pingcap/tidb/release-7.5/ghpr_unit_test
Details

In response to this:

/test check-dev2

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.

@jebter

jebter commented Aug 7, 2026

Copy link
Copy Markdown

/retest

@bb7133

bb7133 commented Aug 10, 2026

Copy link
Copy Markdown
Member Author

/retest

@bb7133
bb7133 merged commit 9bd76e1 into release-7.5-20260724-v7.5.7 Aug 10, 2026
15 of 19 checks passed
@bb7133
bb7133 deleted the cp-69692-7.5-v7.5.7 branch August 10, 2026 08:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants