From f62fba190e1cb05fe3cf359391e3722dcfdba80f Mon Sep 17 00:00:00 2001 From: atreyadbrx Date: Tue, 24 Nov 2026 17:09:38 +0000 Subject: [PATCH] Add bundle auto-deploy get and list `get` shows the trigger of the bundle target and `list` lists the triggers of all the bundle's targets. Both call ListWebhookTriggers, filtered on the bundle's repository and path, plus the target for `get`. The fake list handler supports the filter fields the CLI sends and returns one trigger per page, so the CLI's paging is exercised. Co-authored-by: Isaac Signed-off-by: atreyadbrx --- .../bundle/auto-deploy/get/.databrickscfg | 3 + .../bundle/auto-deploy/get/databricks.yml | 9 ++ .../bundle/auto-deploy/get/out.test.toml | 2 + acceptance/bundle/auto-deploy/get/output.txt | 103 +++++++++++++ acceptance/bundle/auto-deploy/get/script | 25 +++ .../bundle/auto-deploy/list/databricks.yml | 9 ++ .../auto-deploy/list/other/databricks.yml | 9 ++ .../bundle/auto-deploy/list/out.test.toml | 2 + acceptance/bundle/auto-deploy/list/output.txt | 115 ++++++++++++++ acceptance/bundle/auto-deploy/list/script | 18 +++ cmd/bundle/autodeploy/autodeploy.go | 4 +- cmd/bundle/autodeploy/get.go | 47 ++++++ cmd/bundle/autodeploy/list.go | 37 +++++ cmd/bundle/autodeploy/trigger.go | 60 ++++++++ cmd/bundle/autodeploy/trigger_test.go | 4 + libs/gitwebhooks/api.go | 25 +++ libs/gitwebhooks/model.go | 23 ++- libs/testserver/gitwebhooks.go | 144 +++++++++++++++++- libs/testserver/gitwebhooks_test.go | 24 +++ libs/testserver/handlers.go | 3 + 20 files changed, 660 insertions(+), 6 deletions(-) create mode 100644 acceptance/bundle/auto-deploy/get/.databrickscfg create mode 100644 acceptance/bundle/auto-deploy/get/databricks.yml create mode 100644 acceptance/bundle/auto-deploy/get/out.test.toml create mode 100644 acceptance/bundle/auto-deploy/get/output.txt create mode 100644 acceptance/bundle/auto-deploy/get/script create mode 100644 acceptance/bundle/auto-deploy/list/databricks.yml create mode 100644 acceptance/bundle/auto-deploy/list/other/databricks.yml create mode 100644 acceptance/bundle/auto-deploy/list/out.test.toml create mode 100644 acceptance/bundle/auto-deploy/list/output.txt create mode 100644 acceptance/bundle/auto-deploy/list/script create mode 100644 cmd/bundle/autodeploy/get.go create mode 100644 cmd/bundle/autodeploy/list.go create mode 100644 libs/testserver/gitwebhooks_test.go diff --git a/acceptance/bundle/auto-deploy/get/.databrickscfg b/acceptance/bundle/auto-deploy/get/.databrickscfg new file mode 100644 index 00000000000..582d7b34c52 --- /dev/null +++ b/acceptance/bundle/auto-deploy/get/.databrickscfg @@ -0,0 +1,3 @@ +[my workspace] +host = $DATABRICKS_HOST +token = $DATABRICKS_TOKEN diff --git a/acceptance/bundle/auto-deploy/get/databricks.yml b/acceptance/bundle/auto-deploy/get/databricks.yml new file mode 100644 index 00000000000..caa4824bc21 --- /dev/null +++ b/acceptance/bundle/auto-deploy/get/databricks.yml @@ -0,0 +1,9 @@ +bundle: + name: auto-deploy + +targets: + dev: + default: true + prod: + git: + branch: main diff --git a/acceptance/bundle/auto-deploy/get/out.test.toml b/acceptance/bundle/auto-deploy/get/out.test.toml new file mode 100644 index 00000000000..2ab253adc73 --- /dev/null +++ b/acceptance/bundle/auto-deploy/get/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = [] diff --git a/acceptance/bundle/auto-deploy/get/output.txt b/acceptance/bundle/auto-deploy/get/output.txt new file mode 100644 index 00000000000..d39a44c8197 --- /dev/null +++ b/acceptance/bundle/auto-deploy/get/output.txt @@ -0,0 +1,103 @@ + +=== A target without a trigger + +>>> musterr [CLI] bundle auto-deploy get +Error: target dev has no auto-deploy trigger that you can view. Only a trigger's creator and workspace admins can view it. To create one, run: databricks bundle auto-deploy create -t dev + +=== The suggested command quotes the profile + +>>> musterr env -u DATABRICKS_HOST -u DATABRICKS_TOKEN DATABRICKS_CONFIG_FILE=.databrickscfg [CLI] bundle auto-deploy get -p my workspace +Error: target dev has no auto-deploy trigger that you can view. Only a trigger's creator and workspace admins can view it. To create one, run: databricks bundle auto-deploy create -t dev -p 'my workspace' + +=== The target's trigger + +>>> [CLI] bundle auto-deploy get +Trigger ID: [UUID][0] +Repository: https://github.com/acme/repo +Bundle: databricks.yml +Target: dev +Branch: main +Deploy as: a user (not shown) + +>>> [CLI] bundle auto-deploy get -t prod +Trigger ID: [UUID][1] +Repository: https://github.com/acme/repo +Bundle: databricks.yml +Target: prod +Branch: main +Deploy as: [UUID][2] + +>>> [CLI] bundle auto-deploy get -t prod -o json +{ + "name": "webhook-triggers/[UUID][1]", + "repo_url": "https://github.com/acme/repo", + "git_provider": "GITHUB", + "trigger_config": { + "push_event": { + "branch": "main" + }, + "dabs_deploy": { + "bundle_yml_repo_path": "databricks.yml", + "deployment_mode": "prod", + "deploy_as": { + "service_principal_client_id": "[UUID][2]" + } + }, + "trigger_id": "[UUID][1]" + } +} +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\" AND trigger_config.dabs_deploy.deployment_mode = \"dev\"" + } +} +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\" AND trigger_config.dabs_deploy.deployment_mode = \"prod\"" + } +} +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\" AND trigger_config.dabs_deploy.deployment_mode = \"prod\"", + "page_token": "1" + } +} +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\" AND trigger_config.dabs_deploy.deployment_mode = \"prod\"" + } +} +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\" AND trigger_config.dabs_deploy.deployment_mode = \"prod\"", + "page_token": "1" + } +} + +=== Another caller does not see the trigger + +>>> musterr as-test-sp [CLI] bundle auto-deploy get +Error: target dev has no auto-deploy trigger that you can view. Only a trigger's creator and workspace admins can view it. To create one, run: databricks bundle auto-deploy create -t dev + +=== Another caller cannot change the trigger + +>>> musterr as-test-sp [CLI] bundle auto-deploy create +Error: Only the trigger's creator or a workspace admin can change or delete it + +Host: [DATABRICKS_URL] +Auth type: Personal Access Token (pat) + +Next steps: + - Verify you have the required permissions for this operation + - Check your identity: databricks auth describe + - Consider setting up a profile: databricks auth login --profile diff --git a/acceptance/bundle/auto-deploy/get/script b/acceptance/bundle/auto-deploy/get/script new file mode 100644 index 00000000000..8c679252bcc --- /dev/null +++ b/acceptance/bundle/auto-deploy/get/script @@ -0,0 +1,25 @@ +git-repo-init +git remote add origin https://github.com/acme/repo + +title "A target without a trigger" +trace musterr $CLI bundle auto-deploy get + +title "The suggested command quotes the profile" +envsubst < .databrickscfg > LOG.databrickscfg && mv LOG.databrickscfg .databrickscfg +trace musterr env -u DATABRICKS_HOST -u DATABRICKS_TOKEN DATABRICKS_CONFIG_FILE=.databrickscfg $CLI bundle auto-deploy get -p 'my workspace' + +$CLI bundle auto-deploy create >> LOG.setup 2>&1 +$CLI bundle auto-deploy create -t prod --deploy-as 692bc6d0-ffa3-11ed-be56-0242ac120002 >> LOG.setup 2>&1 +rm "$OUT_REQUESTS" + +title "The target's trigger" +trace $CLI bundle auto-deploy get +trace $CLI bundle auto-deploy get -t prod +trace $CLI bundle auto-deploy get -t prod -o json +print_requests.py --get //git-webhooks + +title "Another caller does not see the trigger" +trace musterr as-test-sp $CLI bundle auto-deploy get + +title "Another caller cannot change the trigger" +trace musterr as-test-sp $CLI bundle auto-deploy create diff --git a/acceptance/bundle/auto-deploy/list/databricks.yml b/acceptance/bundle/auto-deploy/list/databricks.yml new file mode 100644 index 00000000000..caa4824bc21 --- /dev/null +++ b/acceptance/bundle/auto-deploy/list/databricks.yml @@ -0,0 +1,9 @@ +bundle: + name: auto-deploy + +targets: + dev: + default: true + prod: + git: + branch: main diff --git a/acceptance/bundle/auto-deploy/list/other/databricks.yml b/acceptance/bundle/auto-deploy/list/other/databricks.yml new file mode 100644 index 00000000000..caa4824bc21 --- /dev/null +++ b/acceptance/bundle/auto-deploy/list/other/databricks.yml @@ -0,0 +1,9 @@ +bundle: + name: auto-deploy + +targets: + dev: + default: true + prod: + git: + branch: main diff --git a/acceptance/bundle/auto-deploy/list/out.test.toml b/acceptance/bundle/auto-deploy/list/out.test.toml new file mode 100644 index 00000000000..2ab253adc73 --- /dev/null +++ b/acceptance/bundle/auto-deploy/list/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = [] diff --git a/acceptance/bundle/auto-deploy/list/output.txt b/acceptance/bundle/auto-deploy/list/output.txt new file mode 100644 index 00000000000..647782a79de --- /dev/null +++ b/acceptance/bundle/auto-deploy/list/output.txt @@ -0,0 +1,115 @@ + +=== A bundle without triggers + +>>> [CLI] bundle auto-deploy list +Target Branch Deploy as Trigger ID + +=== Another bundle in the same repository, whose trigger is not this bundle's + +>>> withdir other [CLI] bundle auto-deploy create +Pushes to branch main now deploy target dev as you. +Trigger ID: [UUID][0] +{ + "method": "PUT", + "path": "/api/2.0/git-webhooks", + "body": { + "repo_url": "https://github.com/acme/repo", + "git_provider": "GITHUB", + "trigger_config": { + "push_event": { + "branch": "main" + }, + "dabs_deploy": { + "bundle_yml_repo_path": "other/databricks.yml", + "deployment_mode": "dev" + } + } + } +} + +=== The triggers of this bundle's targets + +>>> [CLI] bundle auto-deploy list +Target Branch Deploy as Trigger ID +dev main a user (not shown) [UUID][1] +prod main a user (not shown) [UUID][2] + +>>> [CLI] bundle auto-deploy list -o json +[ + { + "name": "webhook-triggers/[UUID][1]", + "repo_url": "https://github.com/acme/repo", + "git_provider": "GITHUB", + "trigger_config": { + "push_event": { + "branch": "main" + }, + "dabs_deploy": { + "bundle_yml_repo_path": "databricks.yml", + "deployment_mode": "dev" + }, + "trigger_id": "[UUID][1]" + } + }, + { + "name": "webhook-triggers/[UUID][2]", + "repo_url": "https://github.com/acme/repo", + "git_provider": "GITHUB", + "trigger_config": { + "push_event": { + "branch": "main" + }, + "dabs_deploy": { + "bundle_yml_repo_path": "databricks.yml", + "deployment_mode": "prod" + }, + "trigger_id": "[UUID][2]" + } + } +] +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\"" + } +} +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\"", + "page_token": "1" + } +} +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\"", + "page_token": "2" + } +} +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\"" + } +} +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\"", + "page_token": "1" + } +} +{ + "method": "GET", + "path": "/api/2.0/git-webhooks/webhook-triggers", + "q": { + "filter": "repo_url = \"https://github.com/acme/repo\" AND trigger_config.dabs_deploy.bundle_yml_repo_path = \"databricks.yml\"", + "page_token": "2" + } +} diff --git a/acceptance/bundle/auto-deploy/list/script b/acceptance/bundle/auto-deploy/list/script new file mode 100644 index 00000000000..0319397f446 --- /dev/null +++ b/acceptance/bundle/auto-deploy/list/script @@ -0,0 +1,18 @@ +git-repo-init +git remote add origin https://github.com/acme/repo + +title "A bundle without triggers" +trace $CLI bundle auto-deploy list + +$CLI bundle auto-deploy create >> LOG.setup 2>&1 +$CLI bundle auto-deploy create -t prod >> LOG.setup 2>&1 +rm "$OUT_REQUESTS" + +title "Another bundle in the same repository, whose trigger is not this bundle's" +trace withdir other $CLI bundle auto-deploy create +print_requests.py //git-webhooks + +title "The triggers of this bundle's targets" +trace $CLI bundle auto-deploy list +trace $CLI bundle auto-deploy list -o json +print_requests.py --get //git-webhooks diff --git a/cmd/bundle/autodeploy/autodeploy.go b/cmd/bundle/autodeploy/autodeploy.go index 5e155897cf0..71903d4818f 100644 --- a/cmd/bundle/autodeploy/autodeploy.go +++ b/cmd/bundle/autodeploy/autodeploy.go @@ -8,7 +8,7 @@ func NewAutoDeployCommand() *cobra.Command { cmd := &cobra.Command{ Use: "auto-deploy", Short: "Deploy a bundle target on every push to a Git branch", - Long: `Set up auto-deploy for a bundle target. + Long: `Set up and inspect auto-deploy for a bundle target. Auto-deploy deploys a bundle target whenever commits are pushed to a branch of the bundle's Git repository. Run these commands from the bundle directory. The @@ -23,5 +23,7 @@ Example: } cmd.AddCommand(newCreateCommand()) + cmd.AddCommand(newGetCommand()) + cmd.AddCommand(newListCommand()) return cmd } diff --git a/cmd/bundle/autodeploy/get.go b/cmd/bundle/autodeploy/get.go new file mode 100644 index 00000000000..2b83b99a78d --- /dev/null +++ b/cmd/bundle/autodeploy/get.go @@ -0,0 +1,47 @@ +package autodeploy + +import ( + "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/cmdio" + "github.com/spf13/cobra" +) + +// The service shows deploy_as only for a service principal other than the caller, so an unset +// value is the caller or a user, which an admin's update can make someone other than the creator. +// The service omits deploy_as unless it is a service principal other than the caller, so an unset +// one doesn't say which user the deploys run as. +const deployAsTemplate = `{{with .TriggerConfig.DabsDeploy.DeployAs}}{{or .ServicePrincipalClientID .UserEmail}}{{else}}a user (not shown){{end}}` + +const getTemplate = `Trigger ID: {{.TriggerConfig.TriggerID}} +Repository: {{.RepoURL}} +Bundle: {{.TriggerConfig.DabsDeploy.BundleYmlRepoPath}} +Target: {{.TriggerConfig.DabsDeploy.DeploymentMode}} +Branch: {{.TriggerConfig.PushEvent.Branch}} +Deploy as: ` + deployAsTemplate + ` +` + +func newGetCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "get", + Short: "Show the auto-deploy trigger of this bundle target", + Args: root.NoArgs, + Annotations: map[string]string{ + "template": getTemplate, + }, + } + + cmd.RunE = func(cmd *cobra.Command, args []string) error { + t, api, err := loadTrigger(cmd) + if err != nil { + return err + } + ctx := cmd.Context() + found, err := findTrigger(ctx, api, t) + if err != nil { + return err + } + return cmdio.Render(ctx, found) + } + + return cmd +} diff --git a/cmd/bundle/autodeploy/list.go b/cmd/bundle/autodeploy/list.go new file mode 100644 index 00000000000..021f828e6ec --- /dev/null +++ b/cmd/bundle/autodeploy/list.go @@ -0,0 +1,37 @@ +package autodeploy + +import ( + "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/gitwebhooks" + "github.com/spf13/cobra" +) + +func newListCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "list", + Short: "List the auto-deploy triggers of this bundle's targets", + Long: `List the auto-deploy triggers of this bundle's targets. + +The triggers are those for the origin URL and workspace of the selected target +(-t). A target with another workspace or origin has its triggers there.`, + Args: root.NoArgs, + Annotations: map[string]string{ + "headerTemplate": `{{header "Target"}} {{header "Branch"}} {{header "Deploy as"}} {{header "Trigger ID"}}`, + "template": cmdio.Heredoc(` + {{range .}}{{.TriggerConfig.DabsDeploy.DeploymentMode | green}} {{.TriggerConfig.PushEvent.Branch}} ` + deployAsTemplate + ` {{.TriggerConfig.TriggerID}} + {{end}}`), + }, + } + + cmd.RunE = func(cmd *cobra.Command, args []string) error { + t, api, err := loadTrigger(cmd) + if err != nil { + return err + } + ctx := cmd.Context() + return cmdio.RenderIterator(ctx, api.ListWebhookTriggers(ctx, gitwebhooks.ListWebhookTriggersRequest{Filter: t.bundleFilter()})) + } + + return cmd +} diff --git a/cmd/bundle/autodeploy/trigger.go b/cmd/bundle/autodeploy/trigger.go index 7728e724784..b40fd9a2b5d 100644 --- a/cmd/bundle/autodeploy/trigger.go +++ b/cmd/bundle/autodeploy/trigger.go @@ -17,6 +17,8 @@ import ( "github.com/databricks/cli/libs/dyn/dynvar" "github.com/databricks/cli/libs/gitwebhooks" "github.com/databricks/cli/libs/logdiag" + "github.com/databricks/cli/libs/shellquote" + "github.com/databricks/databricks-sdk-go/listing" "github.com/spf13/cobra" ) @@ -27,6 +29,9 @@ type trigger struct { // bundlePath is the repository-relative path to the bundle's configuration file. bundlePath string target string + + // profile is the -p flag, which the commands that this one suggests need too. + profile string } // Auto-deploy infers only these providers. Any other host takes --git-provider, since @@ -132,6 +137,61 @@ func parseGitProvider(value string) (gitwebhooks.GitProvider, error) { return "", fmt.Errorf("--git-provider %s is not supported. Supported values: %s", value, strings.Join(names, ", ")) } +// loadTrigger loads the bundle and returns the trigger of its target, with the API to look it up. +func loadTrigger(cmd *cobra.Command) (trigger, *gitwebhooks.API, error) { + b, err := loadBundle(cmd, nil) + if err != nil { + return trigger{}, nil, err + } + t, err := resolveTrigger(b) + if err != nil { + return trigger{}, nil, err + } + if f := cmd.Flag("profile"); f != nil && f.Changed { + t.profile = f.Value.String() + } + api, err := gitwebhooks.New(b.WorkspaceClient(cmd.Context())) + return t, api, err +} + +// createCommand is the command that creates the trigger of the bundle's target. +func (t trigger) createCommand() string { + command := "databricks bundle auto-deploy create -t " + shellquote.BashArg(t.target) + if t.profile != "" { + command += " -p " + shellquote.BashArg(t.profile) + } + return command +} + +// bundleFilter matches the triggers of every target of the bundle. +func (t trigger) bundleFilter() string { + return fmt.Sprintf("repo_url = %s AND trigger_config.dabs_deploy.bundle_yml_repo_path = %s", quote(t.repoURL), quote(t.bundlePath)) +} + +// targetFilter matches the trigger of the bundle's target. The service has at most one. +func (t trigger) targetFilter() string { + return t.bundleFilter() + " AND trigger_config.dabs_deploy.deployment_mode = " + quote(t.target) +} + +// quote quotes s as an AIP-160 string. Not strconv.Quote: the filter takes only \" and \\ as escapes. +func quote(s string) string { + return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(s) + `"` +} + +// findTrigger returns the trigger of the bundle's target, or an error if it has none. +func findTrigger(ctx context.Context, api *gitwebhooks.API, t trigger) (*gitwebhooks.WebhookTrigger, error) { + // The first match is the only one, so stop there: the service pages over all of the + // repository's triggers, and the page with the match can still have a next page. + found, err := api.ListWebhookTriggers(ctx, gitwebhooks.ListWebhookTriggersRequest{Filter: t.targetFilter()}).Next(ctx) + if errors.Is(err, listing.ErrNoMoreItems) { + return nil, fmt.Errorf("target %s has no auto-deploy trigger that you can view. Only a trigger's creator and workspace admins can view it. To create one, run: %s", t.target, t.createCommand()) + } + if err != nil { + return nil, err + } + return &found, nil +} + // resolveProvider returns the provider flag if set, or the one inferred from the repository URL. func resolveProvider(repoURL string, flag gitwebhooks.GitProvider) (gitwebhooks.GitProvider, error) { if flag != "" { diff --git a/cmd/bundle/autodeploy/trigger_test.go b/cmd/bundle/autodeploy/trigger_test.go index 79a210353ae..b8c04950a81 100644 --- a/cmd/bundle/autodeploy/trigger_test.go +++ b/cmd/bundle/autodeploy/trigger_test.go @@ -33,3 +33,7 @@ func TestParseGitProvider(t *testing.T) { _, err = parseGitProvider("gitea") assert.ErrorContains(t, err, "Supported values: gitHub,") } + +func TestQuote(t *testing.T) { + assert.Equal(t, `"a\"b\\c"`, quote(`a"b\c`)) +} diff --git a/libs/gitwebhooks/api.go b/libs/gitwebhooks/api.go index caf80efe49f..c2bfa786cba 100644 --- a/libs/gitwebhooks/api.go +++ b/libs/gitwebhooks/api.go @@ -12,6 +12,7 @@ import ( "github.com/databricks/cli/libs/auth" "github.com/databricks/databricks-sdk-go" databricksclient "github.com/databricks/databricks-sdk-go/client" + "github.com/databricks/databricks-sdk-go/listing" ) const basePath = "/api/2.0/git-webhooks" @@ -35,3 +36,27 @@ func (a *API) UpsertWebhookTrigger(ctx context.Context, req UpsertWebhookTrigger err := a.client.Do(ctx, http.MethodPut, basePath, auth.WorkspaceIDHeaders(a.client.Config), nil, req, &resp) return &resp, err } + +// ListWebhookTriggers lists the triggers that the caller can view and that match the filter. +func (a *API) ListWebhookTriggers(ctx context.Context, req ListWebhookTriggersRequest) listing.Iterator[WebhookTrigger] { + return listing.NewIterator( + &req, + a.listWebhookTriggersPage, + func(resp *ListWebhookTriggersResponse) []WebhookTrigger { + return resp.WebhookTriggers + }, + func(resp *ListWebhookTriggersResponse) *ListWebhookTriggersRequest { + if resp.NextPageToken == "" { + return nil + } + req.PageToken = resp.NextPageToken + return &req + }, + ) +} + +func (a *API) listWebhookTriggersPage(ctx context.Context, req ListWebhookTriggersRequest) (*ListWebhookTriggersResponse, error) { + var resp ListWebhookTriggersResponse + err := a.client.Do(ctx, http.MethodGet, basePath+"/webhook-triggers", auth.WorkspaceIDHeaders(a.client.Config), nil, req, &resp) + return &resp, err +} diff --git a/libs/gitwebhooks/model.go b/libs/gitwebhooks/model.go index 6e3390db4ad..a627eb2d25d 100644 --- a/libs/gitwebhooks/model.go +++ b/libs/gitwebhooks/model.go @@ -28,9 +28,15 @@ type DeployAsIdentity struct { // DabsDeployTarget deploys a bundle target. The service keys a DABs trigger on // BundleYmlRepoPath and DeploymentMode, which is the bundle target. type DabsDeployTarget struct { - BundleYmlRepoPath string `json:"bundle_yml_repo_path"` - DeploymentMode string `json:"deployment_mode"` - DeployAs *DeployAsIdentity `json:"deploy_as,omitempty"` + BundleYmlRepoPath string `json:"bundle_yml_repo_path"` + DeploymentMode string `json:"deployment_mode"` + + // A response sets DeployAs only to a service principal other than the caller. Unset means the + // caller or a user. + DeployAs *DeployAsIdentity `json:"deploy_as,omitempty"` + + // BundleDeploymentID is output only, and unset until an attempt reports it. + BundleDeploymentID string `json:"bundle_deployment_id,omitempty"` } // DeploymentTriggerConfig combines the event that triggers a deploy with what it deploys. @@ -62,3 +68,14 @@ type UpsertWebhookTriggerResponse struct { WebhookID string `json:"webhook_id,omitempty"` TriggerID string `json:"trigger_id,omitempty"` } + +type ListWebhookTriggersRequest struct { + // Filter is an AIP-160 expression: `field = value` terms joined by AND. + Filter string `json:"-" url:"filter,omitempty"` + PageToken string `json:"-" url:"page_token,omitempty"` +} + +type ListWebhookTriggersResponse struct { + WebhookTriggers []WebhookTrigger `json:"webhook_triggers,omitempty"` + NextPageToken string `json:"next_page_token,omitempty"` +} diff --git a/libs/testserver/gitwebhooks.go b/libs/testserver/gitwebhooks.go index b2dd5845669..d9a96c450ed 100644 --- a/libs/testserver/gitwebhooks.go +++ b/libs/testserver/gitwebhooks.go @@ -3,6 +3,10 @@ package testserver import ( "encoding/json" "fmt" + "maps" + "slices" + "strconv" + "strings" "github.com/databricks/cli/libs/gitwebhooks" ) @@ -14,12 +18,22 @@ import ( type fakeWebhookTrigger struct { webhookID string trigger gitwebhooks.WebhookTrigger + + // creator is the user name of the caller that created the trigger. An update keeps it. + creator string } +// gitWebhooksPageSize is small so that a list of two triggers already takes two pages. +const gitWebhooksPageSize = 1 + func gitWebhooksBadRequest(message string) Response { + return gitWebhooksError(400, "BAD_REQUEST", message) +} + +func gitWebhooksError(statusCode int, errorCode, message string) Response { return Response{ - StatusCode: 400, - Body: map[string]string{"error_code": "BAD_REQUEST", "message": message}, + StatusCode: statusCode, + Body: map[string]string{"error_code": errorCode, "message": message}, } } @@ -72,9 +86,17 @@ func (s *FakeWorkspace) GitWebhooksUpsert(req Request) Response { triggerID = nextUUID() } + // The service lets only a trigger's creator or a workspace admin change it, and the fake's + // callers are not admins. + creator := s.MeUser(req.Token).UserName + if existing, ok := s.GitWebhookTriggers[triggerID]; ok && existing.creator != creator { + return gitWebhooksError(403, "PERMISSION_DENIED", "Only the trigger's creator or a workspace admin can change or delete it") + } + stored.TriggerID = triggerID s.GitWebhookTriggers[triggerID] = &fakeWebhookTrigger{ webhookID: webhookID, + creator: creator, trigger: gitwebhooks.WebhookTrigger{ Name: "webhook-triggers/" + triggerID, RepoURL: request.RepoURL, @@ -84,3 +106,121 @@ func (s *FakeWorkspace) GitWebhooksUpsert(req Request) Response { } return Response{Body: gitwebhooks.UpsertWebhookTriggerResponse{WebhookID: webhookID, TriggerID: triggerID}} } + +// GitWebhooksList pages over the triggers in name order, and returns the ones on the page that +// match the filter and that the caller created. Like the service for a caller that isn't an admin, +// a page can have no matches and still have a next page. +func (s *FakeWorkspace) GitWebhooksList(req Request) Response { + query := req.URL.Query() + terms, err := parseGitWebhooksFilter(query.Get("filter")) + if err != nil { + return gitWebhooksError(400, "INVALID_PARAMETER_VALUE", err.Error()) + } + offset := 0 + if token := query.Get("page_token"); token != "" { + offset, err = strconv.Atoi(token) + if err != nil || offset < 0 { + return gitWebhooksError(400, "INVALID_PARAMETER_VALUE", "invalid page_token") + } + } + caller := s.MeUser(req.Token).UserName + + defer s.LockUnlock()() + + all := slices.SortedFunc(maps.Values(s.GitWebhookTriggers), func(a, b *fakeWebhookTrigger) int { + return strings.Compare(a.trigger.Name, b.trigger.Name) + }) + offset = min(offset, len(all)) + end := min(offset+gitWebhooksPageSize, len(all)) + + var resp gitwebhooks.ListWebhookTriggersResponse + for _, t := range all[offset:end] { + if t.creator == caller && gitWebhookTriggerMatches(t.trigger, terms) { + resp.WebhookTriggers = append(resp.WebhookTriggers, t.trigger) + } + } + if end < len(all) { + resp.NextPageToken = strconv.Itoa(end) + } + return Response{Body: resp} +} + +// parseGitWebhooksFilter parses the subset of AIP-160 that the service supports: `field = value` +// terms joined by AND, each field at most once, with values in double quotes. +func parseGitWebhooksFilter(filter string) (map[string]string, error) { + terms := map[string]string{} + rest := filter + for rest != "" { + field, after, ok := strings.Cut(rest, " = ") + if !ok { + return nil, fmt.Errorf("unsupported filter term: %s", rest) + } + if _, ok := gitWebhookFilterFields[field]; !ok { + return nil, fmt.Errorf("unsupported filter field: %s", field) + } + if _, ok := terms[field]; ok { + return nil, fmt.Errorf("filter field %s appears more than once", field) + } + value, after, err := readGitWebhooksFilterString(after) + if err != nil { + return nil, err + } + terms[field] = value + if after == "" { + break + } + rest, ok = strings.CutPrefix(after, " AND ") + if !ok { + return nil, fmt.Errorf("expected AND after the value of %s", field) + } + } + return terms, nil +} + +// readGitWebhooksFilterString reads the quoted string at the start of s, which takes only \" and \\ +// as escapes, and returns it with the rest of s. +func readGitWebhooksFilterString(s string) (string, string, error) { + if !strings.HasPrefix(s, `"`) { + return "", "", fmt.Errorf("filter value is not a quoted string: %s", s) + } + var value strings.Builder + for i := 1; i < len(s); i++ { + switch s[i] { + case '"': + return value.String(), s[i+1:], nil + case '\\': + if i+1 < len(s) && (s[i+1] == '"' || s[i+1] == '\\') { + i++ + value.WriteByte(s[i]) + continue + } + return "", "", fmt.Errorf("unsupported escape in filter value: %s", s) + default: + value.WriteByte(s[i]) + } + } + return "", "", fmt.Errorf("unterminated string in filter: %s", s) +} + +func gitWebhookTriggerMatches(t gitwebhooks.WebhookTrigger, terms map[string]string) bool { + for field, value := range terms { + if gitWebhookFilterFields[field](t) != value { + return false + } + } + return true +} + +// gitWebhookFilterFields are the filter fields that the fake supports. The fake only stores DABs +// triggers, so their DABs target is always set. +var gitWebhookFilterFields = map[string]func(gitwebhooks.WebhookTrigger) string{ + "repo_url": func(t gitwebhooks.WebhookTrigger) string { + return t.RepoURL + }, + "trigger_config.dabs_deploy.bundle_yml_repo_path": func(t gitwebhooks.WebhookTrigger) string { + return t.TriggerConfig.DabsDeploy.BundleYmlRepoPath + }, + "trigger_config.dabs_deploy.deployment_mode": func(t gitwebhooks.WebhookTrigger) string { + return t.TriggerConfig.DabsDeploy.DeploymentMode + }, +} diff --git a/libs/testserver/gitwebhooks_test.go b/libs/testserver/gitwebhooks_test.go new file mode 100644 index 00000000000..a51de9c51dc --- /dev/null +++ b/libs/testserver/gitwebhooks_test.go @@ -0,0 +1,24 @@ +package testserver + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParseGitWebhooksFilter(t *testing.T) { + terms, err := parseGitWebhooksFilter(`repo_url = "https://github.com/acme/repo" AND trigger_config.dabs_deploy.bundle_yml_repo_path = "R AND D/\"x\"\\databricks.yml"`) + require.NoError(t, err) + assert.Equal(t, map[string]string{ + "repo_url": "https://github.com/acme/repo", + "trigger_config.dabs_deploy.bundle_yml_repo_path": `R AND D/"x"\databricks.yml`, + }, terms) + + // The service takes only \" and \\ as escapes. + _, err = parseGitWebhooksFilter(`repo_url = "a\nb"`) + assert.ErrorContains(t, err, "unsupported escape") + + _, err = parseGitWebhooksFilter(`repo_url = "a" AND repo_url = "b"`) + assert.ErrorContains(t, err, "more than once") +} diff --git a/libs/testserver/handlers.go b/libs/testserver/handlers.go index 56a5db7181b..15e87978f67 100644 --- a/libs/testserver/handlers.go +++ b/libs/testserver/handlers.go @@ -576,6 +576,9 @@ func AddDefaultHandlers(server *Server) { server.Handle("PUT", "/api/2.0/git-webhooks", func(req Request) any { return req.Workspace.GitWebhooksUpsert(req) }) + server.Handle("GET", "/api/2.0/git-webhooks/webhook-triggers", func(req Request) any { + return req.Workspace.GitWebhooksList(req) + }) server.Handle("POST", "/api/2.2/jobs/delete", func(req Request) any { var request jobs.DeleteJob