Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FIX (databases): correctly detect read-only MariaDB/MySQL users with SHOW CREATE ROUTINE grant (#568)

Rostislav Dugine18f0be87619
diff --git a/backend/internal/features/databases/databases/mariadb/model.go b/backend/internal/features/databases/databases/mariadb/model.go
index ff6325b4..3fd3a3d2 100644
--- a/backend/internal/features/databases/databases/mariadb/model.go
+++ b/backend/internal/features/databases/databases/mariadb/model.go
@@ -321,12 +321,27 @@ func (m *MariadbDatabase) IsUserReadOnly(
}
defer func() { _ = rows.Close() }()
- writePrivileges := []string{
- "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER",
- "INDEX", "GRANT OPTION", "ALL PRIVILEGES", "SUPER",
- "EXECUTE", "FILE", "RELOAD", "SHUTDOWN", "CREATE ROUTINE",
- "ALTER ROUTINE", "CREATE USER",
- "CREATE TABLESPACE", "DELETE HISTORY", "REFERENCES",
+ writePrivileges := map[string]bool{
+ "INSERT": true,
+ "UPDATE": true,
+ "DELETE": true,
+ "CREATE": true,
+ "DROP": true,
+ "ALTER": true,
+ "INDEX": true,
+ "GRANT OPTION": true,
+ "ALL PRIVILEGES": true,
+ "SUPER": true,
+ "EXECUTE": true,
+ "FILE": true,
+ "RELOAD": true,
+ "SHUTDOWN": true,
+ "CREATE ROUTINE": true,
+ "ALTER ROUTINE": true,
+ "CREATE USER": true,
+ "CREATE TABLESPACE": true,
+ "DELETE HISTORY": true,
+ "REFERENCES": true,
}
detectedPrivileges := make(map[string]bool)
@@ -337,8 +352,8 @@ func (m *MariadbDatabase) IsUserReadOnly(
return false, nil, fmt.Errorf("failed to scan grant: %w", err)
}
- for _, priv := range writePrivileges {
- if regexp.MustCompile(`(?i)\b` + priv + `\b`).MatchString(grant) {
+ for _, priv := range parseGrantPrivileges(grant) {
+ if writePrivileges[priv] {
detectedPrivileges[priv] = true
}
}
@@ -563,6 +578,37 @@ func mapMariadb11xVersion(minor string) (tools.MariadbVersion, error) {
}
}
+// parseGrantPrivileges extracts comma-separated privilege names from a single
+// SHOW GRANTS line. Returns uppercased privilege tokens with column-level
+// qualifiers like "(col1, col2)" stripped. Returns nil for role grants and
+// other lines without an ON clause.
+//
+// Parsing the privilege list is necessary because a naive substring search
+// over the whole grant string falsely matches privilege keywords that appear
+// inside other privilege names — e.g. "SHOW CREATE ROUTINE" contains both
+// "CREATE" and "CREATE ROUTINE" as substrings.
+func parseGrantPrivileges(grant string) []string {
+ headRe := regexp.MustCompile(`(?is)^\s*GRANT\s+(.+?)\s+ON\s+`)
+ m := headRe.FindStringSubmatch(grant)
+ if m == nil {
+ return nil
+ }
+
+ colRe := regexp.MustCompile(`\s*\([^)]*\)`)
+ privsStr := colRe.ReplaceAllString(m[1], "")
+
+ parts := strings.Split(privsStr, ",")
+ privs := make([]string, 0, len(parts))
+ for _, p := range parts {
+ p = strings.TrimSpace(strings.ToUpper(p))
+ if p != "" {
+ privs = append(privs, p)
+ }
+ }
+
+ return privs
+}
+
// detectPrivileges detects backup-related privileges and returns them as comma-separated string
func detectPrivileges(ctx context.Context, db *sql.DB, database string) (string, error) {
rows, err := db.QueryContext(ctx, "SHOW GRANTS FOR CURRENT_USER()")
diff --git a/backend/internal/features/databases/databases/mariadb/model_test.go b/backend/internal/features/databases/databases/mariadb/model_test.go
index 53c19476..0d61f77c 100644
--- a/backend/internal/features/databases/databases/mariadb/model_test.go
+++ b/backend/internal/features/databases/databases/mariadb/model_test.go
@@ -846,6 +846,148 @@ func Test_GetRawDbSizeMb_Mariadb_ReturnsPositiveSize(t *testing.T) {
assert.Greater(t, sizeMB, 0.0, "raw db size should be > 0 after inserting data")
}
+// Regression test for issue #568: a user with only SELECT, SHOW VIEW, and
+// SHOW CREATE ROUTINE must be detected as read-only. Previously the
+// substring-regex check falsely matched "CREATE" and "CREATE ROUTINE" inside
+// "SHOW CREATE ROUTINE".
+//
+// SHOW CREATE ROUTINE was introduced as a distinct privilege in MariaDB
+// 11.3; the matrix below only covers versions that recognize the GRANT
+// statement.
+func Test_IsUserReadOnly_WithShowCreateRoutineGrant_ReturnsTrue(t *testing.T) {
+ env := config.GetEnv()
+ cases := []struct {
+ name string
+ version tools.MariadbVersion
+ port string
+ }{
+ {"MariaDB 11.4", tools.MariadbVersion114, env.TestMariadb114Port},
+ {"MariaDB 11.8", tools.MariadbVersion118, env.TestMariadb118Port},
+ {"MariaDB 12.0", tools.MariadbVersion120, env.TestMariadb120Port},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ container := connectToMariadbContainer(t, tc.port, tc.version)
+ defer container.DB.Close()
+
+ username := fmt.Sprintf("ro_%s", uuid.New().String()[:8])
+ password := "ropass123"
+
+ _, err := container.DB.Exec(fmt.Sprintf(
+ "CREATE USER '%s'@'%%' IDENTIFIED BY '%s'", username, password))
+ assert.NoError(t, err)
+ defer dropUserSafe(container.DB, username)
+
+ for _, stmt := range []string{
+ "GRANT SELECT ON *.* TO '%s'@'%%'",
+ "GRANT SHOW VIEW ON *.* TO '%s'@'%%'",
+ "GRANT SHOW CREATE ROUTINE ON *.* TO '%s'@'%%'",
+ } {
+ _, err = container.DB.Exec(fmt.Sprintf(stmt, username))
+ assert.NoError(t, err)
+ }
+
+ _, err = container.DB.Exec("FLUSH PRIVILEGES")
+ assert.NoError(t, err)
+
+ readOnlyModel := &MariadbDatabase{
+ Version: tc.version,
+ Host: container.Host,
+ Port: container.Port,
+ Username: username,
+ Password: password,
+ Database: &container.Database,
+ IsHttps: false,
+ }
+
+ logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
+
+ isReadOnly, privileges, err := readOnlyModel.IsUserReadOnly(
+ t.Context(),
+ logger,
+ nil,
+ )
+ assert.NoError(t, err)
+ assert.True(
+ t,
+ isReadOnly,
+ "SELECT + SHOW VIEW + SHOW CREATE ROUTINE must be read-only, got privileges=%v",
+ privileges,
+ )
+ assert.Empty(t, privileges)
+ })
+ }
+}
+
+func Test_ParseGrantPrivileges_ReturnsExpectedTokens(t *testing.T) {
+ cases := []struct {
+ name string
+ grant string
+ want []string
+ }{
+ {
+ "issue-568 SHOW CREATE ROUTINE not split into CREATE",
+ "GRANT SELECT, SHOW VIEW, SHOW CREATE ROUTINE ON *.* TO 'backup'@'%'",
+ []string{"SELECT", "SHOW VIEW", "SHOW CREATE ROUTINE"},
+ },
+ {
+ "standard write privs",
+ "GRANT SELECT, INSERT, UPDATE ON *.* TO 'x'@'%'",
+ []string{"SELECT", "INSERT", "UPDATE"},
+ },
+ {
+ "ALL PRIVILEGES",
+ "GRANT ALL PRIVILEGES ON db.* TO 'x'@'%'",
+ []string{"ALL PRIVILEGES"},
+ },
+ {
+ "USAGE-only line",
+ "GRANT USAGE ON *.* TO 'x'@'%'",
+ []string{"USAGE"},
+ },
+ {
+ "column-level qualifiers stripped",
+ "GRANT SELECT (col1, col2), UPDATE (col3) ON db.t TO 'x'@'%'",
+ []string{"SELECT", "UPDATE"},
+ },
+ {
+ "role grant (no ON clause) returns nil",
+ "GRANT my_role TO 'u'@'%'",
+ nil,
+ },
+ {
+ "PROXY grant",
+ "GRANT PROXY ON 'other'@'%' TO 'u'@'%'",
+ []string{"PROXY"},
+ },
+ {
+ "WITH GRANT OPTION trailer ignored",
+ "GRANT SELECT, INSERT ON *.* TO 'x'@'%' WITH GRANT OPTION",
+ []string{"SELECT", "INSERT"},
+ },
+ {
+ "mixed case GRANT/ON",
+ "grant Select, Update on *.* to 'x'@'%'",
+ []string{"SELECT", "UPDATE"},
+ },
+ {
+ "column literally named ON inside parens",
+ "GRANT SELECT (on) ON db.t TO 'x'@'%'",
+ []string{"SELECT"},
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := parseGrantPrivileges(tc.grant)
+ assert.Equal(t, tc.want, got)
+ })
+ }
+}
+
func connectToMariadbContainer(
t *testing.T,
port string,
diff --git a/backend/internal/features/databases/databases/mysql/model.go b/backend/internal/features/databases/databases/mysql/model.go
index f96e9ad5..438b09d8 100644
--- a/backend/internal/features/databases/databases/mysql/model.go
+++ b/backend/internal/features/databases/databases/mysql/model.go
@@ -324,12 +324,26 @@ func (m *MysqlDatabase) IsUserReadOnly(
}
defer func() { _ = rows.Close() }()
- writePrivileges := []string{
- "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER",
- "INDEX", "GRANT OPTION", "ALL PRIVILEGES", "SUPER",
- "EXECUTE", "FILE", "RELOAD", "SHUTDOWN", "CREATE ROUTINE",
- "ALTER ROUTINE", "CREATE USER",
- "CREATE TABLESPACE", "REFERENCES",
+ writePrivileges := map[string]bool{
+ "INSERT": true,
+ "UPDATE": true,
+ "DELETE": true,
+ "CREATE": true,
+ "DROP": true,
+ "ALTER": true,
+ "INDEX": true,
+ "GRANT OPTION": true,
+ "ALL PRIVILEGES": true,
+ "SUPER": true,
+ "EXECUTE": true,
+ "FILE": true,
+ "RELOAD": true,
+ "SHUTDOWN": true,
+ "CREATE ROUTINE": true,
+ "ALTER ROUTINE": true,
+ "CREATE USER": true,
+ "CREATE TABLESPACE": true,
+ "REFERENCES": true,
}
detectedPrivileges := make(map[string]bool)
@@ -340,8 +354,8 @@ func (m *MysqlDatabase) IsUserReadOnly(
return false, nil, fmt.Errorf("failed to scan grant: %w", err)
}
- for _, priv := range writePrivileges {
- if regexp.MustCompile(`(?i)\b` + priv + `\b`).MatchString(grant) {
+ for _, priv := range parseGrantPrivileges(grant) {
+ if writePrivileges[priv] {
detectedPrivileges[priv] = true
}
}
@@ -540,6 +554,37 @@ func mapMysql8xVersion(minor string) tools.MysqlVersion {
}
}
+// parseGrantPrivileges extracts comma-separated privilege names from a single
+// SHOW GRANTS line. Returns uppercased privilege tokens with column-level
+// qualifiers like "(col1, col2)" stripped. Returns nil for role grants and
+// other lines without an ON clause.
+//
+// Parsing the privilege list is necessary because a naive substring search
+// over the whole grant string falsely matches privilege keywords that appear
+// inside other privilege names — e.g. "CREATE VIEW" contains "CREATE" as a
+// substring.
+func parseGrantPrivileges(grant string) []string {
+ headRe := regexp.MustCompile(`(?is)^\s*GRANT\s+(.+?)\s+ON\s+`)
+ m := headRe.FindStringSubmatch(grant)
+ if m == nil {
+ return nil
+ }
+
+ colRe := regexp.MustCompile(`\s*\([^)]*\)`)
+ privsStr := colRe.ReplaceAllString(m[1], "")
+
+ parts := strings.Split(privsStr, ",")
+ privs := make([]string, 0, len(parts))
+ for _, p := range parts {
+ p = strings.TrimSpace(strings.ToUpper(p))
+ if p != "" {
+ privs = append(privs, p)
+ }
+ }
+
+ return privs
+}
+
// detectPrivileges detects backup-related privileges and returns them as comma-separated string
func detectPrivileges(ctx context.Context, db *sql.DB, database string) (string, error) {
rows, err := db.QueryContext(ctx, "SHOW GRANTS FOR CURRENT_USER()")
diff --git a/backend/internal/features/databases/databases/mysql/model_test.go b/backend/internal/features/databases/databases/mysql/model_test.go
index 8dc904cd..9f0e0c86 100644
--- a/backend/internal/features/databases/databases/mysql/model_test.go
+++ b/backend/internal/features/databases/databases/mysql/model_test.go
@@ -855,6 +855,72 @@ func Test_GetRawDbSizeMb_Mysql_ReturnsPositiveSize(t *testing.T) {
assert.Greater(t, sizeMB, 0.0, "raw db size should be > 0 after inserting data")
}
+func Test_ParseGrantPrivileges_ReturnsExpectedTokens(t *testing.T) {
+ cases := []struct {
+ name string
+ grant string
+ want []string
+ }{
+ {
+ "issue-568 SHOW CREATE ROUTINE not split into CREATE",
+ "GRANT SELECT, SHOW VIEW, SHOW CREATE ROUTINE ON *.* TO 'backup'@'%'",
+ []string{"SELECT", "SHOW VIEW", "SHOW CREATE ROUTINE"},
+ },
+ {
+ "standard write privs",
+ "GRANT SELECT, INSERT, UPDATE ON *.* TO 'x'@'%'",
+ []string{"SELECT", "INSERT", "UPDATE"},
+ },
+ {
+ "ALL PRIVILEGES",
+ "GRANT ALL PRIVILEGES ON db.* TO 'x'@'%'",
+ []string{"ALL PRIVILEGES"},
+ },
+ {
+ "USAGE-only line",
+ "GRANT USAGE ON *.* TO 'x'@'%'",
+ []string{"USAGE"},
+ },
+ {
+ "column-level qualifiers stripped",
+ "GRANT SELECT (col1, col2), UPDATE (col3) ON db.t TO 'x'@'%'",
+ []string{"SELECT", "UPDATE"},
+ },
+ {
+ "role grant (no ON clause) returns nil",
+ "GRANT my_role TO 'u'@'%'",
+ nil,
+ },
+ {
+ "PROXY grant",
+ "GRANT PROXY ON 'other'@'%' TO 'u'@'%'",
+ []string{"PROXY"},
+ },
+ {
+ "WITH GRANT OPTION trailer ignored",
+ "GRANT SELECT, INSERT ON *.* TO 'x'@'%' WITH GRANT OPTION",
+ []string{"SELECT", "INSERT"},
+ },
+ {
+ "mixed case GRANT/ON",
+ "grant Select, Update on *.* to 'x'@'%'",
+ []string{"SELECT", "UPDATE"},
+ },
+ {
+ "column literally named ON inside parens",
+ "GRANT SELECT (on) ON db.t TO 'x'@'%'",
+ []string{"SELECT"},
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := parseGrantPrivileges(tc.grant)
+ assert.Equal(t, tc.want, got)
+ })
+ }
+}
+
func connectToMysqlContainer(
t *testing.T,
port string,