From 63a7558008a11acbc0d77448c2f63b3399788a3e Mon Sep 17 00:00:00 2001 From: srstack Date: Wed, 18 Nov 2026 00:47:41 +0800 Subject: [PATCH 1/2] fix(fs): require an explicit display-name confirmation to delete a file system delete-file-system accepted only --file-system-id and then called DeleteAdminTenant. Deletion is asynchronous, the backend keeps no recovery period, and a mistyped or stale ID therefore destroyed a file system with no human confirmation point. The command now requires --confirm-file-system-name in addition to --file-system-id. The confirmation must repeat the target File System display name (or its ID when the backend keeps no display name), matching the names list-file-systems and describe-file-system already report. - Missing flags are usage errors (fs.missing_file_system_id, fs.missing_confirmation, both exit 2) raised before profile and credential loading, so they never become authentication errors and never send a request. - Real execution reads the target, compares the confirmation with the authoritative remote display name, and only then sends the irreversible delete. A mismatch fails with fs.delete_confirmation_mismatch, names the actual display name, and leaves the resource and local credentials intact. - --dry-run stays offline: it validates the flags, reports a delete_confirmation check and the planned request, and is covered by e2e asserting no remote call. - DELETE is still not retried by the API client; local credentials are still removed only after the backend accepts deletion. e2e/cli_test.go drops the two assertions that pinned the flag's absence (help must not mention it, CLI must report unknown flag) and now covers the required flag in help, the missing-confirmation usage error, a mismatch that sends no DELETE, and the offline dry-run. Live e2e passes the authoritative display name for its dry-run and for cleanup of the resource it created itself. Docs: README.md, AGENTS.md, and docs/present.md document the new requirement. --- AGENTS.md | 14 +++- README.md | 4 +- docs/present.md | 14 +++- e2e/cli_test.go | 37 +++++++-- e2e/live_test.go | 53 +++++++++++-- internal/cli/commands.go | 45 +++++++++-- internal/fs/control.go | 7 +- internal/fs/drive9_companion_test.go | 5 +- internal/fs/tenant_control.go | 69 +++++++++++++++-- internal/fs/tenant_control_test.go | 107 +++++++++++++++++++++++++-- 10 files changed, 308 insertions(+), 47 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 87ffc980..b4211e2f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -433,7 +433,12 @@ Follow these rules unless `docs/priciples.md` is updated: root to become readable through the public Drive9 CLI. It must retain the resource and local credentials when waiting fails. - `ti fs delete-file-system` is asynchronous. After Drive9 accepts deletion, - output status is `deleting`, not `deleted`. + output status is `deleting`, not `deleted`. It always requires both + `--file-system-id` and `--confirm-file-system-name`; the confirmation must + equal the target File System display name (or its ID when the backend keeps + no display name), is checked before profile and credential loading, and is + matched against the remote display name before the irreversible delete + request. Deletion has no backend recovery period. - `ti fs mount-file-system` and `ti fs-vault mount-vault` are background-only public commands. They wait for readiness, return a structured result, and persist a local mount locator for the matching unmount command. Do not expose @@ -588,8 +593,8 @@ Implemented command behavior: - `ti fs enable-file-system-token --file-system-id --token-id ` - `ti fs delete-file-system-token --file-system-id --token-id ` - `ti fs refresh-file-system-token --file-system-id ` -- `ti fs delete-file-system --file-system-id ` -- `ti fs delete-file-system --file-system-id --dry-run` +- `ti fs delete-file-system --file-system-id --confirm-file-system-name ` +- `ti fs delete-file-system --file-system-id --confirm-file-system-name --dry-run` - `ti fs list-file-systems` - `ti fs list-regions` - `ti fs list-regions --output text` @@ -1014,7 +1019,8 @@ can therefore use an existing resource with only a canonical region and FS token; the ID is derived in memory from the token. Do not persist ephemeral flag/environment credentials or create a synthetic `[env]` profile. `ti fs create-file-system`, remote list/describe, and `ti fs delete-file-system` remain TiDB Cloud-authenticated. Delete requires an -ID but does not require a locally stored owner token. +ID and an explicit display-name confirmation but does not require a locally +stored owner token. Filesystem token generate/list/enable/disable/delete commands also use only TiDB Cloud public/private keys and always require an explicit File System ID. diff --git a/README.md b/README.md index 29c10841..aa7262ad 100644 --- a/README.md +++ b/README.md @@ -278,7 +278,7 @@ ti fs generate-file-system-scoped-token \ `TI_FS_TOKEN` may contain either token kind. Scoped tokens work only for allowed paths and operations and can self-refresh; they cannot generate child tokens or manage token inventory. Explicit `--fs-token` takes precedence over the environment. Token list, enable, disable, and delete use an explicit/environment owner token when present, otherwise they use configured TiDB Cloud API keys. With owner Bearer authentication, enable and disable apply only to scoped targets; TiDB Cloud credentials can manage either token kind. Because the token JWT does not expose its kind or scopes, the FS backend is the final permission authority. -An owner FS token authorizes Filesystem use and token management, but it is not a TiDB Cloud administrative credential. Creating, listing, describing, and deleting Filesystem resources require TiDB Cloud API keys. In particular, `ti fs delete-file-system` always requires an explicit `--file-system-id`; `TI_FS_TOKEN` cannot select or authorize deletion of the Filesystem itself. For token list, enable, disable, and delete commands, `--file-system-id` is required only when the command uses TiDB Cloud API keys. When an owner token is supplied through `--fs-token` or `TI_FS_TOKEN`, `ti` derives the Filesystem ID from that token. +An owner FS token authorizes Filesystem use and token management, but it is not a TiDB Cloud administrative credential. Creating, listing, describing, and deleting Filesystem resources require TiDB Cloud API keys. In particular, `ti fs delete-file-system` always requires an explicit `--file-system-id` plus `--confirm-file-system-name` matching the target Filesystem display name; deletion is asynchronous and irreversible because the backend keeps no recovery period, and `TI_FS_TOKEN` cannot select or authorize deletion of the Filesystem itself. For token list, enable, disable, and delete commands, `--file-system-id` is required only when the command uses TiDB Cloud API keys. When an owner token is supplied through `--fs-token` or `TI_FS_TOKEN`, `ti` derives the Filesystem ID from that token. Filesystem AI provider configuration is optional. Without it, existing create, mount, file, search, layer, vault, journal, and Git workflows continue to work normally. Organization administrators can inspect or customize image, audio, and video extraction and OpenAI-compatible 1024-dimension embedding for an explicit Filesystem ID: @@ -371,7 +371,7 @@ ti fs enable-file-system-token ti fs disable-file-system-token ti fs delete-file-system-token ti fs refresh-file-system-token -ti fs delete-file-system +ti fs delete-file-system --file-system-id --confirm-file-system-name ti fs list-file-systems ti fs describe-file-system ti fs describe-file-system-extract-configuration diff --git a/docs/present.md b/docs/present.md index 1325eb12..4d5d318f 100644 --- a/docs/present.md +++ b/docs/present.md @@ -147,6 +147,10 @@ export FILE_SYSTEM_ID="$(bin/ti fs create-file-system \ --wait \ --query file_system_id \ --output text)" +export FILE_SYSTEM_NAME="$(bin/ti fs describe-file-system \ + --file-system-id "$FILE_SYSTEM_ID" \ + --query display_name \ + --output text)" bin/ti fs list-file-systems --output text bin/ti fs describe-file-system \ @@ -373,11 +377,17 @@ bin/ti fs-vault delete-secret \ rm -f /tmp/ti-demo-token.txt ``` -删除 Filesystem 资源及其本地 credential entry: +删除 Filesystem 资源及其本地 credential entry。删除是异步且不可恢复的,因此必须用 `--confirm-file-system-name` 重复目标 Filesystem 的 display name;dry-run 只校验本地参数,真实执行会先读取远端 display name 再比对: ```bash bin/ti fs delete-file-system \ - --file-system-id "$FILE_SYSTEM_ID" + --file-system-id "$FILE_SYSTEM_ID" \ + --confirm-file-system-name "$FILE_SYSTEM_NAME" \ + --dry-run + +bin/ti fs delete-file-system \ + --file-system-id "$FILE_SYSTEM_ID" \ + --confirm-file-system-name "$FILE_SYSTEM_NAME" ``` 删除演示 cluster: diff --git a/e2e/cli_test.go b/e2e/cli_test.go index 49029182..19761bf7 100644 --- a/e2e/cli_test.go +++ b/e2e/cli_test.go @@ -89,9 +89,9 @@ func TestHelpAndVersion(t *testing.T) { deleteFileSystem := runTI(t, bin, "fs", "delete-file-system", "help") deleteFileSystem.wantExitCode(0) - deleteFileSystem.wantStdoutContains("--file-system-id") + deleteFileSystem.wantStdoutContains("--file-system-id (required)") + deleteFileSystem.wantStdoutContains("--confirm-file-system-name (required)") deleteFileSystem.wantStdoutNotContains("--file-system-name") - deleteFileSystem.wantStdoutNotContains("--confirm-file-system-name") createFileSystem := runTI(t, bin, "fs", "create-file-system", "help") createFileSystem.wantExitCode(0) createFileSystem.wantStdoutContains("[--display-name ]") @@ -210,9 +210,9 @@ func TestErrorsAreRenderedAtCLIBoundary(t *testing.T) { unknown.wantExitCode(2) unknown.wantStderrContains(`ti [ERROR]: unknown command "missing-command" for "ti db"`) - removedConfirmation := runTI(t, bin, "fs", "delete-file-system", "--file-system-id", "tenant-workspace", "--confirm-file-system-name", "workspace") - removedConfirmation.wantExitCode(2) - removedConfirmation.wantStderrContains(`unknown flag: --confirm-file-system-name`) + missingDeleteConfirmation := runTI(t, bin, "fs", "delete-file-system", "--file-system-id", "tenant-workspace") + missingDeleteConfirmation.wantExitCode(2) + missingDeleteConfirmation.wantStderrContains("--confirm-file-system-name is required") releaseServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/releases/latest" { @@ -1051,8 +1051,31 @@ func TestFSRemoteInventoryAndIDCredentialSelectionAcrossCommandFamilies(t *testi } deleteScratch := runTIWithInput(t, bin, "", append(baseEnv, "TI_FS_TOKEN="+drive9TestToken("tenant-aws-us-west-2")), "--profile", "stage", "--region", "aws-us-west-2", "fs", "delete-file-system", "--file-system-id", "tenant-aws-us-west-2") - deleteScratch.wantExitCode(0) - deleteScratch.wantStdoutContains(`"status": "deleting"`) + deleteScratch.wantExitCode(2) + deleteScratch.wantStderrContains("--confirm-file-system-name is required") + if got := westControl.requestCount(); got != requestsBeforeTokenOnlyDelete { + t.Fatalf("unconfirmed delete sent a remote request: before=%d after=%d", requestsBeforeTokenOnlyDelete, got) + } + + mismatchedDelete := runTIWithInput(t, bin, "", append(baseEnv, "TI_FS_TOKEN="+drive9TestToken("tenant-aws-us-west-2")), "--profile", "stage", "--region", "aws-us-west-2", "fs", "delete-file-system", "--file-system-id", "tenant-aws-us-west-2", "--confirm-file-system-name", "agent-workspace") + mismatchedDelete.wantExitCode(2) + mismatchedDelete.wantStderrContains(`--confirm-file-system-name "agent-workspace" does not match the target file system display name "tenant-aws-us-west-2"`) + if westControl.hasRequest(http.MethodDelete, "/v1/admin/tenants/tenant-aws-us-west-2") { + t.Fatalf("mismatched confirmation deleted the file system: %#v", westControl.requests) + } + + requestsBeforeDeleteDryRun := westControl.requestCount() + deleteDryRun := runTIWithInput(t, bin, "", append(baseEnv, "TI_FS_TOKEN="+drive9TestToken("tenant-aws-us-west-2")), "--profile", "stage", "--region", "aws-us-west-2", "fs", "delete-file-system", "--file-system-id", "tenant-aws-us-west-2", "--confirm-file-system-name", "tenant-aws-us-west-2", "--dry-run") + deleteDryRun.wantExitCode(0) + deleteDryRun.wantStdoutContains(`"delete_confirmation"`) + deleteDryRun.wantStdoutContains(`"dry_run": true`) + if got := westControl.requestCount(); got != requestsBeforeDeleteDryRun { + t.Fatalf("delete dry-run sent a remote request: before=%d after=%d", requestsBeforeDeleteDryRun, got) + } + + confirmedDelete := runTIWithInput(t, bin, "", append(baseEnv, "TI_FS_TOKEN="+drive9TestToken("tenant-aws-us-west-2")), "--profile", "stage", "--region", "aws-us-west-2", "fs", "delete-file-system", "--file-system-id", "tenant-aws-us-west-2", "--confirm-file-system-name", "tenant-aws-us-west-2") + confirmedDelete.wantExitCode(0) + confirmedDelete.wantStdoutContains(`"status": "deleting"`) afterDelete := runTIWithInput(t, bin, "", baseEnv, "--profile", "stage", "fs", "list-file-systems") afterDelete.wantExitCode(0) afterDelete.wantStdoutContains(`"file_system_id": "tenant-aws-us-east-1"`) diff --git a/e2e/live_test.go b/e2e/live_test.go index 1300bd2e..0fef3275 100644 --- a/e2e/live_test.go +++ b/e2e/live_test.go @@ -26,12 +26,13 @@ import ( const defaultLiveProfile = "live-e2e" var ( - liveFSResourceMu sync.Mutex - liveFSResourceAutoCreatedID string - liveFSTokenAutoCreatedID string - liveFSTokenAutoFileSystemID string - liveFSSelectedID string - liveProfileConfigureMu sync.Mutex + liveFSResourceMu sync.Mutex + liveFSResourceAutoCreatedID string + liveFSResourceAutoCreatedName string + liveFSTokenAutoCreatedID string + liveFSTokenAutoFileSystemID string + liveFSSelectedID string + liveProfileConfigureMu sync.Mutex ) func TestMain(m *testing.M) { @@ -117,6 +118,7 @@ func TestLiveFSRemoteInventoryLifecycle(t *testing.T) { } liveFSResourceMu.Lock() liveFSResourceAutoCreatedID = created.FileSystemID + liveFSResourceAutoCreatedName = created.DisplayName liveFSSelectedID = created.FileSystemID liveFSResourceMu.Unlock() @@ -297,6 +299,7 @@ func TestLiveFSCommandSurface(t *testing.T) { bin := tiBinary(t) profileName := liveProfileName(t) selected := ensureLiveFSResource(t, bin, profileName) + selectedDisplayName := liveFSDisplayName(t, bin, profileName, selected) testLiveHelpCommands(t, bin, [][]string{ {"fs", "help"}, {"fs", "create-file-system", "help"}, {"fs", "import-file-system-token", "help"}, {"fs", "list-file-systems", "help"}, @@ -323,7 +326,7 @@ func TestLiveFSCommandSurface(t *testing.T) { }) testLiveMutatingDryRuns(t, bin, profileName, [][]string{ {"fs", "create-file-system", "--display-name", "ti-e2e-dry-run", "--label", "environment=test", "--wait"}, - {"fs", "delete-file-system", "--file-system-id", selected.FSTenantID}, + {"fs", "delete-file-system", "--file-system-id", selected.FSTenantID, "--confirm-file-system-name", selectedDisplayName}, {"fs", "update-file-system-extract-configuration", "--file-system-id", selected.FSTenantID, "--media-type", "image", "--enabled", "false"}, {"fs", "update-file-system-embedding-configuration", "--file-system-id", selected.FSTenantID, "--enabled", "false"}, {"fs", "create-layer", "--layer-id", "layer-1", "--base-root-path", "/workspace", "--layer-name", "dev"}, @@ -2347,11 +2350,13 @@ func ensureLiveFSResource(t *testing.T, bin, profileName string) *config.Profile create.wantStdoutContains(`"status": "ready"`) var created struct { FileSystemID string `json:"file_system_id"` + DisplayName string `json:"display_name"` } if err := json.Unmarshal([]byte(create.stdout), &created); err != nil || created.FileSystemID == "" { t.Fatalf("decode created live fs resource: %v", err) } liveFSResourceAutoCreatedID = created.FileSystemID + liveFSResourceAutoCreatedName = created.DisplayName liveFSSelectedID = created.FileSystemID selected := resolveLiveFSResourceByID(t, profile, created.FileSystemID) return selected @@ -2497,6 +2502,7 @@ func cleanupAutoCreatedLiveFSResource() { "--profile", profileName, "fs", "delete-file-system", "--file-system-id", fileSystemID, + "--confirm-file-system-name", liveFSConfirmName(fileSystemID), ) output, err := cmd.CombinedOutput() if err != nil { @@ -2532,12 +2538,45 @@ func releaseAutoCreatedLiveFSResource(t *testing.T, bin, profileName string) { "--profile", profileName, "fs", "delete-file-system", "--file-system-id", fileSystemID, + "--confirm-file-system-name", liveFSConfirmName(fileSystemID), ) result.wantExitCode(0) liveFSResourceAutoCreatedID = "" + liveFSResourceAutoCreatedName = "" liveFSSelectedID = "" } +// liveFSDisplayName reads the authoritative display name of the selected live +// File System so destructive-command tests can pass the exact confirmation. +func liveFSDisplayName(t *testing.T, bin, profileName string, profile *config.Profile) string { + t.Helper() + args := []string{"--profile", profileName} + if profile.FSPlacementRegionCode != "" { + args = append(args, "--region", profile.FSPlacementRegionCode) + } + args = append(args, "fs", "describe-file-system", "--file-system-id", profile.FSTenantID) + result := runTI(t, bin, args...) + result.wantExitCode(0) + var described struct { + DisplayName string `json:"display_name"` + } + if err := json.Unmarshal([]byte(result.stdout), &described); err != nil || strings.TrimSpace(described.DisplayName) == "" { + t.Fatalf("decode live fs describe result: %v\n%s", err, result.stdout) + } + return described.DisplayName +} + +// liveFSConfirmName returns the delete confirmation for an FS the suite +// created itself. The create response reports the authoritative display name; +// an empty value means the backend kept no display name, so the effective name +// is the File System ID. +func liveFSConfirmName(fileSystemID string) string { + if name := strings.TrimSpace(liveFSResourceAutoCreatedName); name != "" { + return name + } + return fileSystemID +} + func liveProfileName(t *testing.T) string { t.Helper() profileName := liveProfileNameFromEnv() diff --git a/internal/cli/commands.go b/internal/cli/commands.go index d4677e6e..fee40ab8 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -1642,11 +1642,17 @@ func newFSUpdateFileSystemEmbeddingConfigurationCommand(info version.Info) *cobr func newFSDeleteFileSystemCommand(info version.Info) *cobra.Command { cmd := newControlPlaneCommand(controlPlaneCommandSpec{ - Use: "delete-file-system", - Short: "Delete a file system from TiDB Cloud.", + Use: "delete-file-system", + Short: "Delete a file system from TiDB Cloud.", + Long: "Delete a file system from TiDB Cloud. Deletion is asynchronous and irreversible: the backend keeps no recovery period, so the command requires " + + "--confirm-file-system-name to repeat the target file system display name exactly. Read it with ti fs describe-file-system first.", Mutation: mutatingCommand, Permission: authz.FSVolumeDelete, Run: func(ctx commandContext) (any, error) { + confirmName, err := fsDeleteFileSystemConfirmation(ctx) + if err != nil { + return nil, err + } service, profile, err := fsTIServiceAndProfile(ctx) if err != nil { return nil, err @@ -1656,11 +1662,16 @@ func newFSDeleteFileSystemCommand(info version.Info) *cobra.Command { return nil, err } return service.DeleteFileSystem(ctx.cmd.Context(), tifs.DeleteFileSystemOptions{ - Profile: profile, - FileSystemID: fileSystemID, + Profile: profile, + FileSystemID: fileSystemID, + ConfirmFileSystemName: confirmName, }) }, DryRun: func(ctx commandContext) (dryrun.Result, error) { + confirmName, err := fsDeleteFileSystemConfirmation(ctx) + if err != nil { + return dryrun.Result{}, err + } service, profile, err := fsTIServiceAndProfile(ctx) if err != nil { return dryrun.Result{}, err @@ -1670,16 +1681,36 @@ func newFSDeleteFileSystemCommand(info version.Info) *cobra.Command { return dryrun.Result{}, err } return service.DryRunDeleteFileSystem(ctx.cmd.Context(), ctx.CommandPath(), tifs.DeleteFileSystemOptions{ - Profile: profile, - FileSystemID: fileSystemID, + Profile: profile, + FileSystemID: fileSystemID, + ConfirmFileSystemName: confirmName, }) }, }, info) cmd.Flags().String("file-system-id", "", "The file system ID. FS tokens cannot select or authorize file system deletion.") - markUsageRequired(cmd, "file-system-id") + cmd.Flags().String("confirm-file-system-name", "", "The target file system display name. The value must match the remote display name exactly; deletion is irreversible.") + markUsageRequired(cmd, "file-system-id", "confirm-file-system-name") return cmd } +// fsDeleteFileSystemConfirmation enforces the explicit ID and confirmation +// requirements before profile and credential loading, so missing flags are +// usage errors instead of authentication errors. +func fsDeleteFileSystemConfirmation(ctx commandContext) (string, error) { + fileSystemID, err := ctx.StringFlag("file-system-id") + if err != nil { + return "", err + } + confirmName, err := ctx.StringFlag("confirm-file-system-name") + if err != nil { + return "", err + } + if err := tifs.ValidateDeleteFileSystemInputs(fileSystemID, confirmName); err != nil { + return "", err + } + return confirmName, nil +} + func newFSImportFileSystemTokenCommand(info version.Info) *cobra.Command { cmd := newControlPlaneCommand(controlPlaneCommandSpec{ Use: "import-file-system-token", diff --git a/internal/fs/control.go b/internal/fs/control.go index 847e1e5f..a8a1ac0c 100644 --- a/internal/fs/control.go +++ b/internal/fs/control.go @@ -66,6 +66,10 @@ type ListFileSystemsOptions struct { type DeleteFileSystemOptions struct { Profile *config.Profile FileSystemID string + // ConfirmFileSystemName is the explicit, irreversible-delete + // confirmation. It must match the target File System's display name + // (or its ID when the backend has no display name). + ConfirmFileSystemName string } type CheckFileSystemOptions struct { @@ -219,6 +223,7 @@ func (s Service) DryRunDeleteFileSystem(ctx context.Context, commandPath string, checks := []dryrun.Check{ {Name: "config_and_credentials", Status: "passed", Message: fmt.Sprintf("profile %q loaded", profileName(opts.Profile))}, {Name: "permission_requirement", Status: "passed", Message: string(authz.FSVolumeDelete)}, + {Name: "delete_confirmation", Status: "passed", Message: fmt.Sprintf("%q is compared with the target display name before deletion", strings.TrimSpace(opts.ConfirmFileSystemName))}, } checks = append(checks, dryrun.Check{Name: "file_system_id", Status: "passed", Message: fileSystemID}) homeDir, err := s.homeDir() @@ -241,7 +246,7 @@ func (s Service) DryRunDeleteFileSystem(ctx context.Context, commandPath string, dryrun.RequestSummary{ Method: http.MethodDelete, Path: "/v1/admin/tenants/" + fileSystemID, - Description: "normal execution authenticates with TiDB Cloud API-key headers and removes matching local credentials only after the backend accepts deletion", + Description: "normal execution authenticates with TiDB Cloud API-key headers, reads the target to match --confirm-file-system-name against its display name, sends the irreversible delete request, and removes matching local credentials only after the backend accepts deletion", }, checks..., ), nil diff --git a/internal/fs/drive9_companion_test.go b/internal/fs/drive9_companion_test.go index 95a1d1ec..05049238 100644 --- a/internal/fs/drive9_companion_test.go +++ b/internal/fs/drive9_companion_test.go @@ -635,8 +635,9 @@ func TestDryRunDeleteFileSystemReportsCredentialFile(t *testing.T) { t.Fatal(err) } result, err := (Service{HomeDir: home, Resolver: testFSRegionResolver(t, "aws-us-east-1", "https://fs.test")}).DryRunDeleteFileSystem(context.Background(), "ti fs delete-file-system", DeleteFileSystemOptions{ - Profile: profile, - FileSystemID: "tenant-1", + Profile: profile, + FileSystemID: "tenant-1", + ConfirmFileSystemName: "tenant-1", }) if err != nil { t.Fatalf("DryRunDeleteFileSystem failed: %v", err) diff --git a/internal/fs/tenant_control.go b/internal/fs/tenant_control.go index 7688963d..c79c74cb 100644 --- a/internal/fs/tenant_control.go +++ b/internal/fs/tenant_control.go @@ -242,6 +242,16 @@ func (s Service) deleteFileSystem(ctx context.Context, opts DeleteFileSystemOpti if err != nil { return DeleteResult{}, err } + target, err := client.GetAdminTenant(ctx, creds, id) + if err != nil { + return DeleteResult{}, mapAdminTenantError(err, "get", id, opts.Profile.PlacementRegionCode) + } + if target.TenantID != "" && target.TenantID != id { + return DeleteResult{}, apiContractError(fmt.Sprintf("delete target identified file system %q instead of %q", target.TenantID, id), nil) + } + if err := matchDeleteConfirmation(opts.ConfirmFileSystemName, effectiveTenantDisplayName(id, target.DisplayName)); err != nil { + return DeleteResult{}, err + } response, err := client.DeleteAdminTenant(ctx, creds, id) if err != nil { return DeleteResult{}, mapAdminTenantError(err, "delete", id, opts.Profile.PlacementRegionCode) @@ -280,23 +290,66 @@ func (s Service) adminCreateInputs(ctx context.Context, opts CreateFileSystemOpt } func (s Service) adminDeleteInputs(ctx context.Context, opts DeleteFileSystemOptions) (string, *apifs.Client, apifs.TiDBCloudCredentials, endpoints.Endpoint, error) { - return s.adminItemEndpointInputs(ctx, opts.Profile, opts.FileSystemID, authz.FSVolumeDelete, "delete a file system") + id, err := adminFileSystemID(opts.FileSystemID, authz.FSVolumeDelete) + if err != nil { + return "", nil, apifs.TiDBCloudCredentials{}, endpoints.Endpoint{}, err + } + if err := ValidateDeleteConfirmation(opts.ConfirmFileSystemName); err != nil { + return "", nil, apifs.TiDBCloudCredentials{}, endpoints.Endpoint{}, err + } + client, creds, endpoint, err := s.adminTenantClient(ctx, opts.Profile, authz.FSVolumeDelete, "delete a file system") + return id, client, creds, endpoint, err +} + +// ValidateDeleteFileSystemInputs validates the local delete-file-system flags. +// The CLI calls it before profile and credential loading so missing or invalid +// flags are usage errors, and the service calls it again before remote work. +func ValidateDeleteFileSystemInputs(fileSystemID, confirm string) error { + if _, err := adminFileSystemID(fileSystemID, authz.FSVolumeDelete); err != nil { + return err + } + return ValidateDeleteConfirmation(confirm) +} + +// ValidateDeleteConfirmation rejects a deletion that carries no explicit +// confirmation. The CLI calls it before loading credentials or a profile, and +// the service calls it again before any credential, region, or network work. +func ValidateDeleteConfirmation(confirm string) error { + if strings.TrimSpace(confirm) == "" { + return apperr.New("fs.missing_confirmation", "usage", 2, "--confirm-file-system-name is required for delete-file-system; deletion is irreversible, so the value must repeat the target file system display name") + } + return nil +} + +// matchDeleteConfirmation requires the explicit confirmation to repeat the +// target File System display name, which the backend falls back to its ID when +// no display name is set. +func matchDeleteConfirmation(confirm, displayName string) error { + confirm = strings.TrimSpace(confirm) + if confirm == displayName { + return nil + } + return apperr.New("fs.delete_confirmation_mismatch", "usage", 2, fmt.Sprintf("--confirm-file-system-name %q does not match the target file system display name %q; confirm the exact display name reported by ti fs describe-file-system", confirm, displayName)) } func (s Service) adminItemEndpointInputs(ctx context.Context, profile *config.Profile, fileSystemID string, permission authz.Permission, action string) (string, *apifs.Client, apifs.TiDBCloudCredentials, endpoints.Endpoint, error) { + id, err := adminFileSystemID(fileSystemID, permission) + if err != nil { + return "", nil, apifs.TiDBCloudCredentials{}, endpoints.Endpoint{}, err + } + client, creds, endpoint, err := s.adminTenantClient(ctx, profile, permission, action) + return id, client, creds, endpoint, err +} + +func adminFileSystemID(fileSystemID string, permission authz.Permission) (string, error) { if strings.TrimSpace(fileSystemID) == "" { message := "--file-system-id is required for describe-file-system; describing a file system requires TiDB Cloud API credentials" if permission == authz.FSVolumeDelete { message = "--file-system-id is required for delete-file-system; FS tokens cannot select or authorize file system deletion" } - return "", nil, apifs.TiDBCloudCredentials{}, endpoints.Endpoint{}, apperr.New("fs.missing_file_system_id", "usage", 2, message) - } - id, err := fscred.ValidateFileSystemID(fileSystemID) - if err != nil { - return "", nil, apifs.TiDBCloudCredentials{}, endpoints.Endpoint{}, err + return "", apperr.New("fs.missing_file_system_id", "usage", 2, message) } - client, creds, endpoint, err := s.adminTenantClient(ctx, profile, permission, action) - return id, client, creds, endpoint, err + return fscred.ValidateFileSystemID(fileSystemID) } func (s Service) adminTenantClient(ctx context.Context, profile *config.Profile, permission authz.Permission, action string) (*apifs.Client, apifs.TiDBCloudCredentials, endpoints.Endpoint, error) { diff --git a/internal/fs/tenant_control_test.go b/internal/fs/tenant_control_test.go index ff16bd4d..716007fc 100644 --- a/internal/fs/tenant_control_test.go +++ b/internal/fs/tenant_control_test.go @@ -9,6 +9,7 @@ import ( "os" "path/filepath" "strings" + "sync" "sync/atomic" "testing" "time" @@ -215,7 +216,7 @@ func TestTenantControlDescribeAndDeleteUseIDs(t *testing.T) { if text := described.Human(); !strings.Contains(text, "Quota max media LLM files: 100") || !strings.Contains(text, "Usage video file count: 3") { t.Fatalf("describe text = %q", text) } - deleted, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1"}) + deleted, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1", ConfirmFileSystemName: "workspace-one"}) if err != nil { t.Fatal(err) } @@ -246,14 +247,17 @@ func TestTenantControlDescribeAndDeleteRequireExplicitIDAndTiDBCloudCredentials( if _, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile}); apperr.CodeFor(err) != "fs.missing_file_system_id" || !strings.Contains(err.Error(), "FS tokens cannot select or authorize file system deletion") { t.Fatalf("missing delete ID error = %v", err) } + if _, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1"}); apperr.CodeFor(err) != "fs.missing_confirmation" { + t.Fatalf("missing delete confirmation error = %v", err) + } if requests != 0 { - t.Fatalf("missing IDs sent %d remote requests", requests) + t.Fatalf("missing IDs or confirmation sent %d remote requests", requests) } withoutCredentials := *profile withoutCredentials.TiDBCloudPublicKey = "" withoutCredentials.TiDBCloudPrivateKey = "" - if _, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: &withoutCredentials, FileSystemID: "tenant-1"}); apperr.CodeFor(err) != "auth.missing_credentials" { + if _, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: &withoutCredentials, FileSystemID: "tenant-1", ConfirmFileSystemName: "tenant-1"}); apperr.CodeFor(err) != "auth.missing_credentials" { t.Fatalf("missing TiDB Cloud credentials error = %v", err) } if requests != 0 { @@ -438,12 +442,16 @@ func TestTenantControlDeleteFailurePreservesCredential(t *testing.T) { if _, err := fscred.StoreCredential(home, profile, "tenant-1", "aws-us-east-1", fsTestToken(t, "tenant-1"), false); err != nil { t.Fatal(err) } - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + _ = json.NewEncoder(w).Encode(map[string]any{"tenant_id": "tenant-1", "display_name": "workspace-one"}) + return + } w.WriteHeader(http.StatusInternalServerError) _, _ = w.Write([]byte(`{"error":"temporary backend failure"}`)) })) defer server.Close() - if _, err := directTenantService(home, server.URL).DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1"}); err == nil { + if _, err := directTenantService(home, server.URL).DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1", ConfirmFileSystemName: "workspace-one"}); err == nil { t.Fatal("delete should fail") } if _, err := fscred.GetCredential(home, profile.Name, "tenant-1"); err != nil { @@ -451,6 +459,91 @@ func TestTenantControlDeleteFailurePreservesCredential(t *testing.T) { } } +// TestTenantControlDeleteRequiresMatchingConfirmation pins the irreversible +// delete guard: a missing confirmation never reaches the network, and a +// confirmation that does not repeat the target display name reads the target +// but never sends the delete request. +func TestTenantControlDeleteRequiresMatchingConfirmation(t *testing.T) { + home := t.TempDir() + profile := testProfile() + if _, err := fscred.StoreCredential(home, profile, "tenant-1", "aws-us-east-1", fsTestToken(t, "tenant-1"), false); err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + requests = append(requests, r.Method+" "+r.URL.Path) + mu.Unlock() + switch r.Method { + case http.MethodGet: + _ = json.NewEncoder(w).Encode(map[string]any{"tenant_id": "tenant-1", "display_name": "workspace-one"}) + case http.MethodDelete: + w.WriteHeader(http.StatusAccepted) + _ = json.NewEncoder(w).Encode(map[string]any{"tenant_id": "tenant-1", "status": "deleting"}) + } + })) + defer server.Close() + service := directTenantService(home, server.URL) + + if _, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1"}); apperr.CodeFor(err) != "fs.missing_confirmation" || !strings.Contains(apperr.MessageFor(err), "--confirm-file-system-name is required") { + t.Fatalf("missing confirmation error = %v", err) + } + if _, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1", ConfirmFileSystemName: " "}); apperr.CodeFor(err) != "fs.missing_confirmation" { + t.Fatalf("blank confirmation error = %v", err) + } + if len(requests) != 0 { + t.Fatalf("missing confirmation sent remote requests: %#v", requests) + } + + _, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1", ConfirmFileSystemName: "workspace-two"}) + if apperr.CodeFor(err) != "fs.delete_confirmation_mismatch" || !strings.Contains(apperr.MessageFor(err), `"workspace-two" does not match the target file system display name "workspace-one"`) { + t.Fatalf("mismatched confirmation error = %v", err) + } + mu.Lock() + mismatchRequests := append([]string(nil), requests...) + mu.Unlock() + if len(mismatchRequests) != 1 || mismatchRequests[0] != "GET /v1/admin/tenants/tenant-1" { + t.Fatalf("mismatched confirmation requests = %#v", mismatchRequests) + } + if _, err := fscred.GetCredential(home, profile.Name, "tenant-1"); err != nil { + t.Fatalf("rejected delete removed credentials: %v", err) + } + + deleted, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1", ConfirmFileSystemName: " workspace-one "}) + if err != nil || deleted.Status != "deleting" || !deleted.CredentialsRemoved { + t.Fatalf("confirmed delete = %#v err=%v", deleted, err) + } + mu.Lock() + confirmedRequests := append([]string(nil), requests...) + mu.Unlock() + if len(confirmedRequests) != 3 || confirmedRequests[2] != "DELETE /v1/admin/tenants/tenant-1" { + t.Fatalf("confirmed delete requests = %#v", confirmedRequests) + } +} + +// TestTenantControlDeleteConfirmationFallsBackToID covers a File System whose +// backend metadata carries no display name; its effective name is the ID, which +// list and describe already report. +func TestTenantControlDeleteConfirmationFallsBackToID(t *testing.T) { + home := t.TempDir() + profile := testProfile() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + _ = json.NewEncoder(w).Encode(map[string]any{"tenant_id": "tenant-1", "display_name": ""}) + case http.MethodDelete: + w.WriteHeader(http.StatusAccepted) + _ = json.NewEncoder(w).Encode(map[string]any{"tenant_id": "tenant-1", "status": "deleting"}) + } + })) + defer server.Close() + service := directTenantService(home, server.URL) + if _, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1", ConfirmFileSystemName: "tenant-1"}); err != nil { + t.Fatalf("ID confirmation on a display-name-less file system failed: %v", err) + } +} + func directTenantService(homeDir, baseURL string) Service { return Service{HomeDir: homeDir, Resolver: testFSRegionResolver(nil, "aws-us-east-1", baseURL), CompanionPath: filepath.Join(homeDir, "companion-must-not-run")} } @@ -577,7 +670,7 @@ func TestTenantControlMissingCredentialsFailBeforeNetwork(t *testing.T) { return err }}, {name: "delete", run: func() error { - _, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1"}) + _, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-1", ConfirmFileSystemName: "tenant-1"}) return err }}, } @@ -690,7 +783,7 @@ func TestTenantControlMigratesLegacyCredentialForDescribeAndDelete(t *testing.T) if err != nil || !described.HasLocalToken { t.Fatalf("describe = %#v err=%v", described, err) } - deleted, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-legacy"}) + deleted, err := service.DeleteFileSystem(context.Background(), DeleteFileSystemOptions{Profile: profile, FileSystemID: "tenant-legacy", ConfirmFileSystemName: "legacy-workspace"}) if err != nil || !deleted.CredentialsRemoved { t.Fatalf("delete = %#v err=%v", deleted, err) } From fe06eebb77140193fb4d196a01450b2cef5bb704 Mon Sep 17 00:00:00 2001 From: srstack Date: Wed, 18 Nov 2026 00:56:42 +0800 Subject: [PATCH 2/2] test(fs): fall back to the file system ID in the live delete confirmation liveFSDisplayName failed the live suite when describe-file-system returned an empty display_name, but delete-file-system confirms the effective name, which the backend falls back to the File System ID. Return the ID in that case instead of failing, so destructive-command dry-runs still cover Filesystems that keep no display name. Decode failures still fail the test. --- e2e/live_test.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/e2e/live_test.go b/e2e/live_test.go index 0fef3275..c0e89cfa 100644 --- a/e2e/live_test.go +++ b/e2e/live_test.go @@ -2560,10 +2560,16 @@ func liveFSDisplayName(t *testing.T, bin, profileName string, profile *config.Pr var described struct { DisplayName string `json:"display_name"` } - if err := json.Unmarshal([]byte(result.stdout), &described); err != nil || strings.TrimSpace(described.DisplayName) == "" { + if err := json.Unmarshal([]byte(result.stdout), &described); err != nil { t.Fatalf("decode live fs describe result: %v\n%s", err, result.stdout) } - return described.DisplayName + // The backend falls back to the File System ID when no display name is set, + // and delete-file-system confirms that same effective name, so a File System + // without a display name must be confirmed by its ID instead of failing. + if name := strings.TrimSpace(described.DisplayName); name != "" { + return name + } + return profile.FSTenantID } // liveFSConfirmName returns the delete confirmation for an FS the suite