Conversation
|
[FORMAT CHECKER NOTIFICATION] Notice: To remove the 📖 For more info, you can check the "Contribute Code" section in the development guide. |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
Summary of ChangesHello @joechenrh, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a robust mechanism for converting MariaDB DDLs to be compatible with TiDB. By integrating a dedicated conversion library and applying its rules across the data migration pipeline, it significantly reduces manual intervention and potential errors when migrating schemas from MariaDB to TiDB. The changes include new configuration parameters for fine-grained control over the conversion process and ensure that schema checks, data loading, and DDL replication all benefit from this compatibility layer. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request integrates a MariaDB to TiDB SQL conversion library into DM, affecting the checker, loader, and syncer components, and extends configuration for this new feature. Critical security vulnerabilities and data corruption risks have been identified in the pre-parse rules, specifically a SQL injection vulnerability in the CREATE OR REPLACE rewriting logic and potential data corruption from context-unaware regex replacements. Additionally, there are critical issues in handling multi-statement transformations, where both the checker and syncer might incorrectly process only the first statement, leading to incorrect behavior or data inconsistency. A minor issue also exists in the checker's transformation logic. It is strongly recommended to move all transformations to the AST level or use a context-aware lexer for pre-parsing to address these critical concerns.
| func rewriteCreateOrReplace(sql string) string { | ||
| sql = createOrReplaceIndexRegex.ReplaceAllString(sql, "DROP INDEX IF EXISTS $1 ON $2; CREATE INDEX $1 ON $2") | ||
| sql = createOrReplaceTableRegex.ReplaceAllString(sql, "DROP TABLE IF EXISTS $1; CREATE TABLE $1") | ||
| sql = createOrReplaceSequenceRegex.ReplaceAllString(sql, "DROP SEQUENCE IF EXISTS $1; CREATE SEQUENCE $1") | ||
| return sql | ||
| } |
There was a problem hiding this comment.
The rewriteCreateOrReplace function is vulnerable to SQL Injection. It uses regular expressions to rewrite CREATE OR REPLACE statements into DROP ...; CREATE ... statements. The regexes used to capture identifiers (table names, index names, sequence names) are too broad ([^\s(]+ and [^\s]+) and do not account for semicolons or other SQL-terminating characters.
An attacker with the ability to create tables, indexes, or sequences on the upstream MariaDB can craft an identifier containing a semicolon followed by malicious SQL commands. When DM transforms this SQL for the downstream TiDB, the injected commands will be executed as separate statements.
Example exploit:
Upstream: CREATE OR REPLACE TABLE users; DROP TABLE orders; -- (id INT)
Transformed: DROP TABLE IF EXISTS users; DROP TABLE orders; --; CREATE TABLE users; DROP TABLE orders; -- (id INT)
Impact: Critical. An attacker can execute arbitrary SQL commands on the downstream database.
Remediation: Avoid using regular expressions for SQL rewriting. Use a proper SQL parser to identify the components of the statement and then reconstruct the desired SQL. If regexes must be used, ensure they explicitly exclude SQL delimiters like semicolons.
| stmts, err := parserpkg.Parse(qec.p, parseSQL, "", "") | ||
| if err != nil { | ||
| // log error rather than fatal, so other defer can be executed | ||
| qec.tctx.L().Error("parse ddl", zap.String("event", "query"), zap.Stringer("query event context", qec)) | ||
| return nil, terror.ErrSyncerParseDDL.Delegate(err, qec.originSQL) | ||
| if parseSQL != qec.originSQL { | ||
| qec.tctx.L().Error("parse ddl after mariadb2tidb transform", | ||
| zap.String("event", "query"), | ||
| zap.String("origin_sql", qec.originSQL), | ||
| zap.String("ddl_sql", parseSQL), | ||
| zap.Error(err)) | ||
| } else { | ||
| qec.tctx.L().Error("parse ddl", zap.String("event", "query"), zap.Stringer("query event context", qec)) | ||
| } | ||
| return nil, terror.ErrSyncerParseDDL.Delegate(err, parseSQL) | ||
| } |
There was a problem hiding this comment.
The function parseOneStmt uses parserpkg.Parse which can return multiple statements, but it only returns the first statement (stmts[0]). This is incorrect when the MariaDB to TiDB transformation produces multiple statements (e.g., CREATE OR REPLACE becomes DROP and CREATE). The subsequent statements are lost, which will break the replication logic. The caller HandleQueryEvent should be updated to iterate over all statements returned from parsing and process them individually.
| func stripSystemVersioning(sql string) string { | ||
| sql = withSystemVersioningRegex.ReplaceAllString(sql, " ") | ||
| sql = withoutSystemVersioningRegex.ReplaceAllString(sql, " ") | ||
| sql = periodSystemTimeRegex.ReplaceAllString(sql, " ") | ||
| sql = rowStartRegex.ReplaceAllString(sql, " ") | ||
| sql = rowEndRegex.ReplaceAllString(sql, " ") | ||
| sql = alterSystemVersioningRegex.ReplaceAllString(sql, " ") | ||
| return sql |
There was a problem hiding this comment.
Several pre-parse rules (e.g., SystemVersioningRule, ColumnAttributesRule, SequenceTypeRule, VersionMacrosRule) use global regular expression replacement on the raw SQL string without considering the context. These regexes do not distinguish between SQL keywords and string literals or comments.
If a string literal in an INSERT or UPDATE statement contains text that matches one of these regexes (e.g., "WITH SYSTEM VERSIONING"), it will be incorrectly replaced or stripped, leading to data corruption in the downstream database.
Impact: High. Data corruption in the downstream database.
Remediation: Pre-parse rules should be aware of SQL syntax and only apply replacements to keywords and identifiers, avoiding string literals and comments. Move these transformations to the AST level where possible.
| sql = encryptedRegex.ReplaceAllString(sql, " ") | ||
|
|
||
| // Apply charset and collation transformations if configured | ||
| sql = l.applyCharsetMappings(sql) | ||
|
|
||
| // Replace standalone UUID data types with char(36) but keep functions and identifiers | ||
| matches := uuidRegex.FindAllStringIndex(sql, -1) | ||
| if matches == nil { | ||
| return sql | ||
| } | ||
|
|
||
| var result strings.Builder | ||
| last := 0 | ||
| for _, m := range matches { | ||
| start, end := m[0], m[1] | ||
| result.WriteString(sql[last:start]) | ||
|
|
||
| // Find preceding non-space/non-backtick character | ||
| j := start - 1 | ||
| for j >= 0 && (isSpace(sql[j]) || sql[j] == '`') { | ||
| j-- | ||
| } | ||
|
|
||
| // Find following non-space/non-backtick character | ||
| i := end | ||
| for i < len(sql) && (isSpace(sql[i]) || sql[i] == '`') { | ||
| i++ | ||
| } | ||
|
|
||
| // Extract preceding word for context checks | ||
| wordEnd := j | ||
| for wordEnd >= 0 && (isAlphaNum(sql[wordEnd]) || sql[wordEnd] == '_') { | ||
| wordEnd-- | ||
| } | ||
| precedingWord := strings.ToLower(sql[wordEnd+1 : j+1]) | ||
|
|
||
| switch { | ||
| case i < len(sql) && sql[i] == '(': | ||
| // uuid used as function - leave unchanged | ||
| result.WriteString(sql[start:end]) | ||
| case i < len(sql) && sql[i] == '`': | ||
| // uuid inside backticks - identifier | ||
| result.WriteString(sql[start:end]) | ||
| case precedingWord == "key" || precedingWord == "unique" || precedingWord == "primary" || precedingWord == "constraint" || precedingWord == "index": | ||
| // index or constraint name - leave unchanged | ||
| result.WriteString(sql[start:end]) | ||
| case j >= 0 && (isAlphaNum(sql[j]) || sql[j] == '_'): | ||
| // uuid used as a data type - replace | ||
| result.WriteString("char(36)") | ||
| default: | ||
| // uuid as column name or other - leave unchanged | ||
| result.WriteString(sql[start:end]) | ||
| } | ||
|
|
||
| last = end | ||
| } | ||
|
|
||
| result.WriteString(sql[last:]) | ||
|
|
||
| processed := result.String() | ||
|
|
||
| // Rename unique key named "uuid" to "uuid_key" | ||
| processed = uuidKeyRegex.ReplaceAllString(processed, "UNIQUE KEY uuid_key") |
There was a problem hiding this comment.
The preprocessSQL function applies global regex replacements for encryption options and UUID keys without context awareness. This can lead to data corruption if string literals in DML statements contain text that matches these patterns.
Impact: High. Data corruption in the downstream database.
Remediation: Ensure regex replacements are context-aware or performed on tokens/AST.
| return ret, nil | ||
| } | ||
|
|
||
| upstreamStmt, err := getCreateTableStmt(w.upstreamParser, createSQL) |
There was a problem hiding this comment.
getCreateTableStmt uses parser.ParseOneStmt, which cannot handle multi-statement SQL. The maybeTransformCreateTable function can return multiple SQL statements (e.g., for CREATE OR REPLACE TABLE). This will cause getCreateTableStmt to fail, leading to an incorrect check result. You should modify the logic to handle multiple statements, for example by using parser.Parse and then finding the *ast.CreateTableStmt from the returned statements. This issue also exists in dm/pkg/checker/table_structure.go.
| if strings.TrimSpace(transformed) == "" { | ||
| return statement, nil | ||
| } |
There was a problem hiding this comment.
If the SQL transformation results in an empty string (e.g., the statement is completely removed), this function currently returns the original, untransformed statement. This is incorrect as it leads to processing a statement that should have been removed. The function should return an empty string in this case, and the caller should handle it appropriately (e.g., by skipping the check for this table).
| if strings.TrimSpace(transformed) == "" { | |
| return statement, nil | |
| } | |
| if strings.TrimSpace(transformed) == "" { | |
| return "", nil | |
| } |
|
/test ? |
|
@wuhuizuo: The following commands are available to trigger required jobs: Use DetailsIn response to this:
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. |
|
/test wip-pull-build |
|
/test wip-pull-check |
|
/test wip-pull-unit-test-cdc |
|
/test wip-pull-unit-test-dm |
|
/test wip-pull-unit-test-engine |
|
@joechenrh: The following tests failed, say
Full PR test history. Your PR dashboard. DetailsInstructions 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. |
What problem does this PR solve?
Issue Number: close #xxx
What is changed and how it works?
Check List
Tests
Questions
Will it cause performance regression or break compatibility?
Do you need to update user documentation, design documentation or monitoring documentation?
Release note