From eedaa781e4776827ecc44e3d32367aee6b6ad8da Mon Sep 17 00:00:00 2001 From: Nick Tobey Date: Wed, 23 Apr 2025 12:37:13 -0700 Subject: [PATCH] Remove the system procedure for `dolt admin createchunk commit`, make it work entirely at the filesystem level. This guarantees that an unauthenticated SQL user can't use the procedure to edit branches (whereas anyone with CLI access is assumed to already have filesystem (and thus admin) access anyway.) --- .../admin/createchunk/createcommit.go | 94 +++++++++--- .../admin/dolt_admin_createchunk_commit.go | 138 ------------------ .../doltcore/sqle/dprocedures/init.go | 4 - integration-tests/bats/createchunk.bats | 60 +------- 4 files changed, 76 insertions(+), 220 deletions(-) delete mode 100644 go/libraries/doltcore/sqle/dprocedures/admin/dolt_admin_createchunk_commit.go diff --git a/go/cmd/dolt/commands/admin/createchunk/createcommit.go b/go/cmd/dolt/commands/admin/createchunk/createcommit.go index 8f53da5d5c..de4bce36e5 100644 --- a/go/cmd/dolt/commands/admin/createchunk/createcommit.go +++ b/go/cmd/dolt/commands/admin/createchunk/createcommit.go @@ -17,15 +17,16 @@ package createchunk import ( "bytes" "context" - - "github.com/dolthub/go-mysql-server/sql" - "github.com/gocraft/dbr/v2" - "github.com/gocraft/dbr/v2/dialect" + "errors" "github.com/dolthub/dolt/go/cmd/dolt/cli" "github.com/dolthub/dolt/go/cmd/dolt/errhand" + "github.com/dolthub/dolt/go/libraries/doltcore/doltdb" "github.com/dolthub/dolt/go/libraries/doltcore/env" + "github.com/dolthub/dolt/go/libraries/doltcore/ref" "github.com/dolthub/dolt/go/libraries/utils/argparser" + "github.com/dolthub/dolt/go/store/datas" + "github.com/dolthub/dolt/go/store/hash" ) // CreateCommitCmd creates a new commit chunk, printing the new chunk's hash on success. @@ -121,7 +122,7 @@ func (cmd CreateCommitCmd) ArgParser() *argparser.ArgParser { return cli.CreateCreateCommitParser() } -func (cmd CreateCommitCmd) Exec(ctx context.Context, commandStr string, args []string, _ *env.DoltEnv, cliCtx cli.CliContext) int { +func (cmd CreateCommitCmd) Exec(ctx context.Context, commandStr string, args []string, dEnv *env.DoltEnv, cliCtx cli.CliContext) int { ap := cmd.ArgParser() usage, _ := cli.HelpAndUsagePrinters(cli.CommandDocsForCommandString(commandStr, cli.CommandDocumentationContent{}, ap)) @@ -133,39 +134,94 @@ func (cmd CreateCommitCmd) Exec(ctx context.Context, commandStr string, args []s return 1 } - queryist, sqlCtx, closeFunc, err := cliCtx.QueryEngine(ctx) - if err != nil { - cli.PrintErrln(errhand.VerboseErrorFromError(err)) - return 1 - } - if closeFunc != nil { - defer closeFunc() + desc, _ := apr.GetValue("desc") + root, _ := apr.GetValue("root") + parents, _ := apr.GetValueList("parents") + branch, isBranchSet := apr.GetValue(cli.BranchParam) + force := apr.Contains(cli.ForceFlag) + + var name, email string + var err error + if authorStr, ok := apr.GetValue(cli.AuthorParam); ok { + name, email, err = cli.ParseAuthor(authorStr) + if err != nil { + cli.PrintErrln(errhand.VerboseErrorFromError(err)) + return 1 + } + } else { + name, email, err = env.GetNameAndEmail(cliCtx.Config()) + if err != nil { + cli.PrintErrln(errhand.VerboseErrorFromError(err)) + return 1 + } } - querySql, params, err := generateCreateCommitSQL(cliCtx, apr) - if err != nil { - cli.PrintErrln(errhand.VerboseErrorFromError(err)) + db := dEnv.DbData(ctx).Ddb + commitRootHash, ok := hash.MaybeParse(root) + if !ok { + cli.PrintErrf("invalid root value hash") return 1 } - interpolatedQuery, err := dbr.InterpolateForDialect(querySql, params, dialect.MySQL) + + var parentCommits []hash.Hash + for _, parent := range parents { + commitSpec, err := doltdb.NewCommitSpec(parent) + if err != nil { + cli.PrintErrln(errhand.VerboseErrorFromError(err)) + return 1 + } + + headRef := dEnv.RepoState.CWBHeadRef() + + optionalCommit, err := db.Resolve(ctx, commitSpec, headRef) + if err != nil { + cli.PrintErrln(errhand.VerboseErrorFromError(err)) + return 1 + } + parentCommits = append(parentCommits, optionalCommit.Addr) + } + + commitMeta, err := datas.NewCommitMeta(name, email, desc) if err != nil { cli.PrintErrln(errhand.VerboseErrorFromError(err)) return 1 } - _, rowIter, _, err := queryist.Query(sqlCtx, interpolatedQuery) + // This isn't technically an amend, but the Amend field controls whether the commit must be a child of the ref's current commit (if any) + commitOpts := datas.CommitOptions{ + Parents: parentCommits, + Meta: commitMeta, + Amend: force, + } + + rootVal, err := db.ValueReadWriter().ReadValue(ctx, commitRootHash) if err != nil { cli.PrintErrln(errhand.VerboseErrorFromError(err)) return 1 } - rows, err := sql.RowIterToRows(sqlCtx, rowIter) + var commit *doltdb.Commit + if isBranchSet { + commit, err = db.CommitValue(ctx, ref.NewBranchRef(branch), rootVal, commitOpts) + if errors.Is(err, datas.ErrMergeNeeded) { + cli.PrintErrf("branch %s already exists. If you wish to overwrite it, add the --force flag", branch) + return 1 + } + } else { + commit, err = db.CommitDangling(ctx, rootVal, commitOpts) + } if err != nil { cli.PrintErrln(errhand.VerboseErrorFromError(err)) return 1 } - cli.Println(rows[0][0]) + commitHash, err := commit.HashOf() + if err != nil { + cli.PrintErrln(errhand.VerboseErrorFromError(err)) + return 1 + } + + cli.Println(commitHash.String()) return 0 } diff --git a/go/libraries/doltcore/sqle/dprocedures/admin/dolt_admin_createchunk_commit.go b/go/libraries/doltcore/sqle/dprocedures/admin/dolt_admin_createchunk_commit.go deleted file mode 100644 index 24eb0790c9..0000000000 --- a/go/libraries/doltcore/sqle/dprocedures/admin/dolt_admin_createchunk_commit.go +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright 2025 Dolthub, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package admin - -import ( - "errors" - "fmt" - - "github.com/dolthub/go-mysql-server/sql" - - "github.com/dolthub/dolt/go/cmd/dolt/cli" - "github.com/dolthub/dolt/go/libraries/doltcore/branch_control" - "github.com/dolthub/dolt/go/libraries/doltcore/doltdb" - "github.com/dolthub/dolt/go/libraries/doltcore/ref" - "github.com/dolthub/dolt/go/libraries/doltcore/sqle/dsess" - "github.com/dolthub/dolt/go/store/datas" - "github.com/dolthub/dolt/go/store/hash" -) - -// rowToIter returns a sql.RowIter with a single row containing the values passed in. -func rowToIter(vals ...interface{}) sql.RowIter { - row := make(sql.Row, len(vals)) - for i, val := range vals { - row[i] = val - } - return sql.RowsToRowIter(row) -} - -func CreateCommit(ctx *sql.Context, args ...string) (sql.RowIter, error) { - dbName := ctx.GetCurrentDatabase() - - if len(dbName) == 0 { - return nil, fmt.Errorf("empty database name") - } - if err := branch_control.CheckAccess(ctx, branch_control.Permissions_Write); err != nil { - return nil, err - } - - apr, err := cli.CreateCreateCommitParser().Parse(args) - if err != nil { - return nil, err - } - - desc, _ := apr.GetValue("desc") - root, _ := apr.GetValue("root") - parents, _ := apr.GetValueList("parents") - branch, isBranchSet := apr.GetValue(cli.BranchParam) - force := apr.Contains(cli.ForceFlag) - - var name, email string - if authorStr, ok := apr.GetValue(cli.AuthorParam); ok { - name, email, err = cli.ParseAuthor(authorStr) - if err != nil { - return nil, err - } - } else { - // In SQL mode, use the current SQL user as the commit author, instead of the `dolt config` configured values. - // We won't have an email address for the SQL user though, so instead use the MySQL user@address notation. - name = ctx.Client().User - email = fmt.Sprintf("%s@%s", ctx.Client().User, ctx.Client().Address) - } - - dSess := dsess.DSessFromSess(ctx.Session) - - dbData, ok := dSess.GetDbData(ctx, dbName) - db := dbData.Ddb - commitRootHash, ok := hash.MaybeParse(root) - if !ok { - return nil, fmt.Errorf("invalid root value hash") - } - - var parentCommits []hash.Hash - for _, parent := range parents { - commitSpec, err := doltdb.NewCommitSpec(parent) - if err != nil { - return nil, err - } - - headRef, err := dSess.CWBHeadRef(ctx, dbName) - if err != nil { - return nil, err - } - - optionalCommit, err := db.Resolve(ctx, commitSpec, headRef) - if err != nil { - return nil, err - } - parentCommits = append(parentCommits, optionalCommit.Addr) - } - - commitMeta, err := datas.NewCommitMeta(name, email, desc) - if err != nil { - return nil, err - } - - // This isn't technically an amend, but the Amend field controls whether the commit must be a child of the ref's current commit (if any) - commitOpts := datas.CommitOptions{ - Parents: parentCommits, - Meta: commitMeta, - Amend: force, - } - - rootVal, err := dbData.Ddb.ValueReadWriter().ReadValue(ctx, commitRootHash) - if err != nil { - return nil, err - } - - var commit *doltdb.Commit - if isBranchSet { - commit, err = dbData.Ddb.CommitValue(ctx, ref.NewBranchRef(branch), rootVal, commitOpts) - if errors.Is(err, datas.ErrMergeNeeded) { - return nil, fmt.Errorf("branch %s already exists. If you wish to overwrite it, add the --force flag", branch) - } - } else { - commit, err = dbData.Ddb.CommitDangling(ctx, rootVal, commitOpts) - } - if err != nil { - return nil, err - } - - commitHash, err := commit.HashOf() - if err != nil { - return nil, err - } - return rowToIter(commitHash.String()), nil -} diff --git a/go/libraries/doltcore/sqle/dprocedures/init.go b/go/libraries/doltcore/sqle/dprocedures/init.go index 0801b56ee1..bc01e257b6 100644 --- a/go/libraries/doltcore/sqle/dprocedures/init.go +++ b/go/libraries/doltcore/sqle/dprocedures/init.go @@ -17,8 +17,6 @@ package dprocedures import ( "github.com/dolthub/go-mysql-server/sql" "github.com/dolthub/go-mysql-server/sql/types" - - "github.com/dolthub/dolt/go/libraries/doltcore/sqle/dprocedures/admin" ) var DoltProcedures = []sql.ExternalStoredProcedureDetails{ @@ -59,8 +57,6 @@ var DoltProcedures = []sql.ExternalStoredProcedureDetails{ {Name: "dolt_stats_once", Schema: statsFuncSchema, Function: statsFunc(statsOnce)}, {Name: "dolt_stats_gc", Schema: statsFuncSchema, Function: statsFunc(statsGc)}, {Name: "dolt_stats_timers", Schema: statsFuncSchema, Function: statsFunc(statsTimers)}, - - {Name: "dolt_admin_createchunk_commit", Schema: stringSchema("hash"), Function: admin.CreateCommit}, } // stringSchema returns a non-nullable schema with all columns as LONGTEXT. diff --git a/integration-tests/bats/createchunk.bats b/integration-tests/bats/createchunk.bats index 810d11ef2e..c21c56ab06 100644 --- a/integration-tests/bats/createchunk.bats +++ b/integration-tests/bats/createchunk.bats @@ -98,6 +98,7 @@ teardown() { # but overwriting an existing branch with a different history is an error run dolt admin createchunk commit --root "$newRootValueHash" --desc "flattened history" --parents "$newCommitHash" --branch existingBranch + echo "$output" [ "$status" -eq 1 ] [[ "$output" =~ "branch existingBranch already exists. If you wish to overwrite it, add the --force flag" ]] || false @@ -120,62 +121,3 @@ teardown() { [ "$status" -eq 1 ] [[ "$output" =~ "the --branch flag is required when creating a chunk using the CLI" ]] || false } - -@test "createchunk: create commit in SQL on existing branch" { - dolt branch existingBranch - run dolt sql -q "CALL DOLT_ADMIN_CREATECHUNK_COMMIT('--root', '$newRootValueHash', '--author', 'a ', \ - '--desc', 'flattened history', '--parents', 'refs/internal/create', '--branch', 'existingBranch', '--force');" -r csv - echo "$output" - [ "$status" -eq 0 ] - flattenedCommitHash=$(echo "$output" | tail -n 1) - run dolt show existingBranch - echo "$output" - [ "$status" -eq 0 ] - [[ "$output" =~ "Author: a " ]] || false - [[ "$output" =~ "flattened history" ]] || false - [[ "$output" =~ "added table" ]] || false - [[ "$output" =~ "| + | 1 |" ]] || false - - # check that there are only two commits in the history - run dolt log existingBranch - [ "$status" -eq 0 ] - [ "$(echo "$output" | grep -c commit)" -eq 2 ] - [[ "$output" =~ "Initialize data repository" ]] || false - [[ "$output" =~ "flattened history" ]] || false -} - -@test "createchunk: create commit in SQL on new branch" { - flattenedCommitHash=$(dolt sql -q "CALL DOLT_ADMIN_CREATECHUNK_COMMIT('--root', '$newRootValueHash', '--author', 'a ', '--desc',\ - 'flattened history', '--parents', 'refs/internal/create', '--branch', 'newBranch');" -r csv | tail -n 1) - - run dolt show newBranch - echo "$output" - [ "$status" -eq 0 ] - [[ "$output" =~ "Author: a " ]] || false - [[ "$output" =~ "flattened history" ]] || false - [[ "$output" =~ "added table" ]] || false - [[ "$output" =~ "| + | 1 |" ]] || false - - # check that there are only two commits in the history - run dolt log newBranch - [ "$status" -eq 0 ] - [ "$(echo "$output" | grep -c commit)" -eq 2 ] - [[ "$output" =~ "Initialize data repository" ]] || false - [[ "$output" =~ "flattened history" ]] || false -} - -@test "createchunk: create commit in SQL with no provided branch" { - run dolt sql -r csv <', '--desc', - 'flattened history', '--parents', '$initialCommitHash', '--branch', 'newBranch'); - SELECT * from dolt_log; -SQL - [ "$status" -eq 0 ] - # Just capture the last four lines (the select) - run echo "$(echo "$output" | tail -n 4)" - echo "$output" - [[ "${lines[0]}" =~ "commit_hash,committer,email,date,message" ]] || false - [[ "${lines[1]}" =~ "insert into table" ]] || false - [[ "${lines[2]}" =~ "create table" ]] || false - [[ "${lines[3]}" =~ "Initialize data repository" ]] || false -}