From 7292e12c77958fb668747a24ff5c0970b82c2df1 Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Mon, 16 Nov 2026 16:24:02 +0000 Subject: [PATCH 01/17] Redact sensitive variables from bundle plan and saved plans bundle plan no longer prints or saves sensitive values: new_state is redacted once planning is done. A saved plan does not carry them, so deploy --plan requires every sensitive variable of the bundle to be set with --var or BUNDLE_VAR_, and restores each sensitive field from the config when the config sets it. One check runs before approval and reports all missing values in one error. The prepareChanges warning no longer prints the change values, which were visible before redaction. Co-authored-by: Isaac --- bundle/direct/bundle_plan.go | 119 ++++++++++++++++++++++++++++++----- bundle/direct/redact.go | 96 +++++++++++++++++++++++++--- bundle/phases/deploy.go | 2 +- cmd/bundle/utils/process.go | 5 ++ 4 files changed, 198 insertions(+), 24 deletions(-) diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index 145402cdef2..fbf964c1747 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -19,6 +19,7 @@ import ( "github.com/databricks/cli/bundle/terraform_dabs_map" "github.com/databricks/cli/libs/dyn" "github.com/databricks/cli/libs/dyn/dynvar" + "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/logdiag" "github.com/databricks/cli/libs/retry" @@ -69,9 +70,105 @@ func ValidatePlanAgainstState(stateDB *dstate.DeploymentState, plan *deployplan. return nil } -// InitForApply initializes the DeploymentBundle for applying a pre-computed plan. +// CheckSensitivePlanValues rejects a saved plan that cannot be applied until its sensitive values are +// supplied again, and returns one error that lists every problem. When the plan has a sensitive +// resource, every sensitive variable of the bundle must be set with --var or BUNDLE_VAR_, since +// telling used variables from unused ones needs reference resolution. +func CheckSensitivePlanValues(ctx context.Context, root *config.Root, plan *deployplan.Plan, flagVars []string) error { + adapters, err := dresources.InitAll(nil) + if err != nil { + return err + } + + var problems []string + needsValues := false + for _, resourceKey := range slices.Sorted(maps.Keys(plan.Plan)) { + entry := plan.Plan[resourceKey] + if entry.NewState == nil { + continue + } + adapter, ok := adapters[config.GetResourceTypeFromKey(resourceKey)] + if !ok { + problems = append(problems, fmt.Sprintf("resource %s: unknown resource type", resourceKey)) + continue + } + if len(adapter.GetSensitiveFields()) == 0 { + continue + } + needsValues = true + sv, err := entry.NewState.ToStructVar(adapter.StateType()) + if err != nil { + problems = append(problems, fmt.Sprintf("resource %s: %s", resourceKey, err)) + continue + } + paths, err := sensitivePaths(adapter) + if err != nil { + problems = append(problems, fmt.Sprintf("resource %s: %s", resourceKey, err)) + continue + } + for _, path := range paths { + planned, err := structaccess.Get(sv.Value, path) + if err != nil { + continue + } + if _, err := sensitiveConfigValue(root, resourceKey, path, planned); err != nil { + problems = append(problems, err.Error()) + } + } + } + + var missing []string + if needsValues { + for name, v := range root.Variables { + if v == nil || !config.IsExplicitlyEnabled(v.Sensitive) || variableSupplied(ctx, name, flagVars) { + continue + } + missing = append(missing, name) + } + slices.Sort(missing) + } + if len(missing) > 0 { + problems = append(problems, missingVariablesError(missing)) + } + + if len(problems) == 0 { + return nil + } + return errors.New(strings.Join(problems, "; ")) +} + +// missingVariablesError names the sensitive variables that have no --var or BUNDLE_VAR_ value. +func missingVariablesError(missing []string) string { + const overrides = "the variable-overrides file is not read for sensitive variables" + if len(missing) == 1 { + name := missing[0] + return fmt.Sprintf("sensitive variable %s has no value; pass it with --var %s=... or BUNDLE_VAR_%s when deploying from a saved plan (%s)", name, name, name, overrides) + } + return fmt.Sprintf("sensitive variables %s have no value; pass each with --var NAME=... or BUNDLE_VAR_NAME when deploying from a saved plan (%s)", strings.Join(missing, ", "), overrides) +} + +// variableSupplied reports whether a sensitive variable has a value from --var or BUNDLE_VAR_. +// The resolved value also carries values from the variable-overrides file, so the check reads only +// flags and the environment. A --var given with an empty value wins over the environment. +func variableSupplied(ctx context.Context, name string, flagVars []string) bool { + flagged, found := "", false + for _, assignment := range flagVars { + key, value, _ := strings.Cut(assignment, "=") + if key == name { + flagged, found = value, true + } + } + if found { + return flagged != "" + } + value, _ := env.Lookup(ctx, "BUNDLE_VAR_"+name) + return value != "" +} + +// InitForApply initializes the DeploymentBundle for applying a pre-computed plan. The sensitive +// values the plan redacted are restored from root, the current config. // StateDB must already be open for write before calling this function. -func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks.WorkspaceClient, plan *deployplan.Plan) error { +func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks.WorkspaceClient, plan *deployplan.Plan, root *config.Root) error { b.StateDB.AssertOpenedForWrite() err := b.init(client) @@ -102,6 +199,9 @@ func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks. if err != nil { return fmt.Errorf("loading plan entry %s: %w", resourceKey, err) } + if err := restoreSensitiveFields(adapter, resourceKey, sv.Value, root); err != nil { + return err + } b.StateCache.Store(resourceKey, sv) } @@ -510,7 +610,7 @@ func prepareChanges(ctx context.Context, adapter *dresources.Adapter, localDiff, entry.Remote = ch.Old if !structdiff.IsEqual(entry.New, ch.New) { // this is not fatal (may result in unexpected drift or undetected change but not incorrect deploy), but good to log this - log.Warnf(ctx, "unexpected local and remote diffs (%T, %T); entry=%v ch=%v", entry.New, ch.New, entry, ch) + log.Warnf(ctx, "unexpected local and remote diffs at %s (%T, %T)", ch.Path, entry.New, ch.New) } } } @@ -1700,8 +1800,7 @@ func (b *DeploymentBundle) makePlan(ctx context.Context, configRoot *config.Root }) // Store an unredacted copy in the cache so Apply can deploy with the - // actual values. The original newStateConfig is redacted below and used - // only for the plan output. + // actual values. newStateConfig is serialised into the plan and redacted there. stateType := adapter.StateType() cacheCopyPtr := reflect.New(stateType.Elem()) cacheCopyPtr.Elem().Set(reflect.ValueOf(newStateConfig).Elem()) @@ -1710,20 +1809,12 @@ func (b *DeploymentBundle) makePlan(ctx context.Context, configRoot *config.Root Refs: refs, }) - // Redact sensitive fields before serialising. Sensitive values always come - // from bundle variables (enforced by ValidateSecretValueIsVariable), which - // are resolved before plan time, so SyncToJSON (called when cross-resource - // refs are resolved during planNode) will never re-serialise these fields. - if err := redactStruct(adapter, newStateConfig); err != nil { - return nil, fmt.Errorf("%s: cannot redact state: %w", node, err) - } - newState := &structvar.StructVar{ Value: newStateConfig, Refs: refs, } - // Convert to JSON for serialization in plan (values already redacted above). + // Convert to JSON for serialization in plan. newStateJSON, err := newState.ToJSON() if err != nil { return nil, fmt.Errorf("%s: cannot serialize state: %w", node, err) diff --git a/bundle/direct/redact.go b/bundle/direct/redact.go index b44ab74e7b4..ff0c0bc485c 100644 --- a/bundle/direct/redact.go +++ b/bundle/direct/redact.go @@ -4,6 +4,7 @@ import ( "fmt" "slices" + "github.com/databricks/cli/bundle/config" "github.com/databricks/cli/bundle/deployplan" "github.com/databricks/cli/bundle/direct/dresources" "github.com/databricks/cli/libs/structs/structaccess" @@ -12,6 +13,19 @@ import ( const sensitiveRedactedValue = "[redacted]" +// sensitivePaths parses the sensitive field paths of the adapter. +func sensitivePaths(adapter *dresources.Adapter) ([]*structpath.PathNode, error) { + var paths []*structpath.PathNode + for _, field := range adapter.GetSensitiveFields() { + path, err := structpath.ParsePath(field) + if err != nil { + return nil, fmt.Errorf("parsing sensitive field path %q: %w", field, err) + } + paths = append(paths, path) + } + return paths, nil +} + // redactSensitiveFields replaces (or zeros) scalar fields in s (a pointer to a typed struct) // that the adapter marks as sensitive. replacement is what to set the field to; pass // sensitiveRedactedValue for plan output display, or "" for state-file storage. @@ -20,13 +34,11 @@ func redactSensitiveFields(adapter *dresources.Adapter, s any, replacement strin return nil } - fields := adapter.GetSensitiveFields() - for _, field := range fields { - path, err := structpath.ParsePath(field) - if err != nil { - return fmt.Errorf("parsing sensitive field path %q: %w", field, err) - } - + paths, err := sensitivePaths(adapter) + if err != nil { + return err + } + for _, path := range paths { fv, err := structaccess.Get(s, path) if err != nil { continue @@ -76,13 +88,29 @@ func redactChanges(adapter *dresources.Adapter, changes deployplan.Changes) erro return nil } -// redactPlanEntry redacts sensitive fields from remote_state and changes of a plan -// entry. new_state is already redacted before serialization in makePlan. +// redactPlanEntry redacts new_state, remote_state and changes of a plan entry. It runs once planning +// is done: reference resolution re-serializes new_state from the unredacted cache, and apply reads +// that cache, so the plan must not be serialized after this. func redactPlanEntry(adapter *dresources.Adapter, entry *deployplan.PlanEntry) error { if len(adapter.GetSensitiveFields()) == 0 { return nil } + if entry.NewState != nil { + sv, err := entry.NewState.ToStructVar(adapter.StateType()) + if err != nil { + return fmt.Errorf("redacting new_state: %w", err) + } + if err := redactStruct(adapter, sv.Value); err != nil { + return fmt.Errorf("redacting new_state: %w", err) + } + redacted, err := sv.ToJSON() + if err != nil { + return fmt.Errorf("redacting new_state: %w", err) + } + *entry.NewState = *redacted + } + if entry.RemoteState != nil { if err := redactStruct(adapter, entry.RemoteState); err != nil { return fmt.Errorf("redacting remote_state: %w", err) @@ -97,3 +125,53 @@ func redactPlanEntry(adapter *dresources.Adapter, entry *deployplan.PlanEntry) e return nil } + +// sensitiveConfigValue returns the value the config sets for a sensitive field, which a deploy sends. +// The config value is used whenever it is set. An empty config value is an error only when the plan +// holds the field non-zero, since the plan then expects a value the config cannot supply. A field +// that is zero in both is output-only and yields "". +func sensitiveConfigValue(root *config.Root, resourceKey string, path *structpath.PathNode, planned any) (string, error) { + rc, err := root.GetResourceConfig(resourceKey) + if err != nil { + return "", err + } + var value string + if rc != nil { + if v, err := structaccess.Get(rc, path); err == nil { + value, _ = v.(string) + } + } + if value != "" || planned == nil || planned == "" { + return value, nil + } + if rc == nil { + return "", fmt.Errorf("resource %s is not in the config; run 'bundle plan' again", resourceKey) + } + return "", fmt.Errorf("resource %s: the config has no value for sensitive field %s; pass the value", resourceKey, path) +} + +// restoreSensitiveFields replaces the sensitive values in s, a saved plan's state, with the values +// the current config sets. CheckSensitivePlanValues runs the same rule before the plan is approved. +func restoreSensitiveFields(adapter *dresources.Adapter, resourceKey string, s any, root *config.Root) error { + paths, err := sensitivePaths(adapter) + if err != nil { + return err + } + for _, path := range paths { + planned, err := structaccess.Get(s, path) + if err != nil { + continue + } + value, err := sensitiveConfigValue(root, resourceKey, path, planned) + if err != nil { + return err + } + if value == "" { + continue + } + if err := structaccess.Set(s, path, value); err != nil { + return fmt.Errorf("resource %s: restoring sensitive field %s: %w", resourceKey, path, err) + } + } + return nil +} diff --git a/bundle/phases/deploy.go b/bundle/phases/deploy.go index 1f6831281ea..b460d4ed046 100644 --- a/bundle/phases/deploy.go +++ b/bundle/phases/deploy.go @@ -310,7 +310,7 @@ func Deploy(ctx context.Context, b *bundle.Bundle, outputHandler sync.OutputHand if planFromFile { // Initialize DeploymentBundle for applying the loaded plan - err := b.DeploymentBundle.InitForApply(ctx, b.WorkspaceClient(ctx), plan) + err := b.DeploymentBundle.InitForApply(ctx, b.WorkspaceClient(ctx), plan, &b.Config) if err != nil { logdiag.LogError(ctx, err) return diff --git a/cmd/bundle/utils/process.go b/cmd/bundle/utils/process.go index 68798a4bb01..49de5da4d62 100644 --- a/cmd/bundle/utils/process.go +++ b/cmd/bundle/utils/process.go @@ -499,6 +499,11 @@ func ProcessBundleRet(cmd *cobra.Command, opts ProcessOptions) (b *bundle.Bundle logdiag.LogError(ctx, err) return b, stateDesc, root.ErrAlreadyPrinted } + + if err := direct.CheckSensitivePlanValues(ctx, &b.Config, plan, variables); err != nil { + logdiag.LogError(ctx, err) + return b, stateDesc, root.ErrAlreadyPrinted + } } // Reject an unknown --select before PreDeployChecks and the predeploy script From 2847789972860193d73ce2609bf97d697e99d4b0 Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Mon, 16 Nov 2026 16:24:03 +0000 Subject: [PATCH 02/17] Document sensitive variable redaction in plan and saved plans Co-authored-by: Isaac --- .nextchanges/bundles/7713.md | 1 + bundle/config/variable/variable.go | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) create mode 100644 .nextchanges/bundles/7713.md diff --git a/.nextchanges/bundles/7713.md b/.nextchanges/bundles/7713.md new file mode 100644 index 00000000000..59ab5752890 --- /dev/null +++ b/.nextchanges/bundles/7713.md @@ -0,0 +1 @@ +* `bundle plan` no longer shows or saves sensitive variable values, and `bundle deploy --plan` requires them to be passed again with `--var` or `BUNDLE_VAR_`; `deploy --plan` applies the values supplied at deploy time, not those at plan time. ([#7713](https://github.com/databricks/cli/pull/7713)) diff --git a/bundle/config/variable/variable.go b/bundle/config/variable/variable.go index f5a5fd6ee75..a86a6264b9e 100644 --- a/bundle/config/variable/variable.go +++ b/bundle/config/variable/variable.go @@ -41,9 +41,9 @@ type Variable struct { // Marks the variable as holding a secret. Set automatically for a variable used as the // value of a sensitive resource field (e.g. the value of a UC secret). Its value is - // redacted in the output of `bundle validate -o json` and `bundle summary -o json`, and - // it may only be referenced from sensitive resource fields or from other sensitive - // variables, so that the secret never ends up in plain text. + // redacted in the output of `bundle validate -o json`, `bundle summary -o json` and + // `bundle plan`. It may only be referenced from sensitive resource fields or from other + // sensitive variables, so that the secret never ends up in plain text. Sensitive *bool `json:"sensitive,omitempty"` // This field stores the resolved value for the variable. The variable are From f9e47503f7e0f7c22ea29e843e86e43c8033fd45 Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Mon, 16 Nov 2026 16:24:04 +0000 Subject: [PATCH 03/17] Test sensitive value restore and the saved plan check Co-authored-by: Isaac --- bundle/direct/redact_test.go | 274 +++++++++++++++++++++++++++++++++++ 1 file changed, 274 insertions(+) create mode 100644 bundle/direct/redact_test.go diff --git a/bundle/direct/redact_test.go b/bundle/direct/redact_test.go new file mode 100644 index 00000000000..5a806971799 --- /dev/null +++ b/bundle/direct/redact_test.go @@ -0,0 +1,274 @@ +package direct + +import ( + "encoding/json" + "testing" + + "github.com/databricks/cli/bundle/config" + "github.com/databricks/cli/bundle/config/resources" + "github.com/databricks/cli/bundle/config/variable" + "github.com/databricks/cli/bundle/deployplan" + "github.com/databricks/cli/bundle/direct/dresources" + "github.com/databricks/cli/libs/dyn" + "github.com/databricks/cli/libs/env" + "github.com/databricks/cli/libs/structs/structpath" + "github.com/databricks/cli/libs/structs/structvar" + "github.com/databricks/databricks-sdk-go/service/catalog" + "github.com/databricks/databricks-sdk-go/service/jobs" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const secretLiteral = "dummy-credential" + +func secretAdapter(t *testing.T) *dresources.Adapter { + t.Helper() + adapters, err := dresources.InitAll(nil) + require.NoError(t, err) + adapter, ok := adapters["secrets"] + require.True(t, ok) + return adapter +} + +// syncedRoot gives a Go-literal config the dynamic value that a loaded bundle has, which GetResourceConfig reads. +func syncedRoot(t *testing.T, root *config.Root) *config.Root { + t.Helper() + require.NoError(t, root.Mutate(func(v dyn.Value) (dyn.Value, error) { return v, nil })) + return root +} + +// TestRedactPlanEntryRedactsNewStateAndChanges checks that the literal is absent from the new_state +// and changes of a plan entry, and that the non-sensitive fields are kept. +func TestRedactPlanEntryRedactsNewStateAndChanges(t *testing.T) { + adapter := secretAdapter(t) + + newState := &structvar.StructVarJSON{} + var err error + newState.Value, err = json.Marshal(map[string]any{ + "name": "s", + "catalog_name": "main", + "schema_name": "default", + "value": secretLiteral, + }) + require.NoError(t, err) + + entry := &deployplan.PlanEntry{ + Action: deployplan.Update, + NewState: newState, + Changes: deployplan.Changes{ + "value": {Action: deployplan.Update, Old: "", New: secretLiteral, Remote: secretLiteral}, + "name": {Action: deployplan.Skip, Old: "s", New: "s", Remote: "s"}, + }, + } + + require.NoError(t, redactPlanEntry(adapter, entry)) + + out, err := json.Marshal(entry) + require.NoError(t, err) + assert.NotContains(t, string(out), secretLiteral) + + var redacted struct { + NewState struct { + Value map[string]any `json:"value"` + } `json:"new_state"` + } + require.NoError(t, json.Unmarshal(out, &redacted)) + assert.Equal(t, "[redacted]", redacted.NewState.Value["value"]) + assert.Equal(t, "main", redacted.NewState.Value["catalog_name"]) + assert.Equal(t, "[redacted]", entry.Changes["value"].New) + assert.Equal(t, "s", entry.Changes["name"].New) +} + +func secretRoot(t *testing.T, value string, variables map[string]*variable.Variable) *config.Root { + t.Helper() + root := &config.Root{ + Variables: variables, + Resources: config.Resources{ + Secrets: map[string]*resources.Secret{ + "s": {Secret: catalog.Secret{Name: "s", Value: value}}, + }, + }, + } + return syncedRoot(t, root) +} + +const ( + msgValueMissing = "resource resources.secrets.s: the config has no value for sensitive field value; pass the value" + msgNotInConfig = "resource resources.secrets.gone is not in the config; run 'bundle plan' again" + msgCredentialMissing = "sensitive variable api_credential has no value; pass it with --var api_credential=... or BUNDLE_VAR_api_credential when deploying from a saved plan (the variable-overrides file is not read for sensitive variables)" + msgVarsMissing = "sensitive variables api_credential, api_header have no value; pass each with --var NAME=... or BUNDLE_VAR_NAME when deploying from a saved plan (the variable-overrides file is not read for sensitive variables)" +) + +func TestRestoreSensitiveFields(t *testing.T) { + adapter := secretAdapter(t) + + tests := []struct { + name string + resourceKey string + state *catalog.Secret + configValue string + wantValue string + wantErr string + }{ + { + name: "redaction marker is replaced by the config value", + resourceKey: "resources.secrets.s", + state: &catalog.Secret{Name: "s", Value: sensitiveRedactedValue}, + configValue: secretLiteral, + wantValue: secretLiteral, + }, + { + name: "plaintext from a plan saved by an older CLI is replaced by the config value", + resourceKey: "resources.secrets.s", + state: &catalog.Secret{Name: "s", Value: "stale-plaintext"}, + configValue: secretLiteral, + wantValue: secretLiteral, + }, + { + name: "zero in the plan but set in the config is restored", + resourceKey: "resources.secrets.s", + state: &catalog.Secret{Name: "s"}, + configValue: secretLiteral, + wantValue: secretLiteral, + }, + { + name: "zero in both is skipped", + resourceKey: "resources.secrets.s", + state: &catalog.Secret{Name: "s"}, + configValue: "", + wantValue: "", + }, + { + name: "non-zero in the plan with an empty config value is an error", + resourceKey: "resources.secrets.s", + state: &catalog.Secret{Name: "s", Value: sensitiveRedactedValue}, + configValue: "", + wantErr: msgValueMissing, + }, + { + name: "non-zero in the plan with the resource missing from config is an error", + resourceKey: "resources.secrets.gone", + state: &catalog.Secret{Name: "s", Value: sensitiveRedactedValue}, + configValue: secretLiteral, + wantErr: msgNotInConfig, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + root := secretRoot(t, tc.configValue, nil) + err := restoreSensitiveFields(adapter, tc.resourceKey, tc.state, root) + if tc.wantErr != "" { + assert.EqualError(t, err, tc.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tc.wantValue, tc.state.Value) + assert.Empty(t, tc.state.EffectiveValue) + }) + } +} + +// TestSensitiveConfigValueNestedField checks that a dotted sensitive field path is read from the +// resource config, not only a top-level field. +func TestSensitiveConfigValueNestedField(t *testing.T) { + root := syncedRoot(t, &config.Root{Resources: config.Resources{Jobs: map[string]*resources.Job{ + "j": {JobSettings: jobs.JobSettings{Schedule: &jobs.CronSchedule{QuartzCronExpression: "0 0 * * *"}}}, + }}}) + path, err := structpath.ParsePath("schedule.quartz_cron_expression") + require.NoError(t, err) + + value, err := sensitiveConfigValue(root, "resources.jobs.j", path, "planned") + require.NoError(t, err) + assert.Equal(t, "0 0 * * *", value) +} + +func TestCheckSensitivePlanValues(t *testing.T) { + sensitive := true + variables := func() map[string]*variable.Variable { + return map[string]*variable.Variable{ + "api_credential": {Sensitive: &sensitive}, + "api_header": {Sensitive: &sensitive}, + "target_schema": {}, + } + } + secretPlan := &deployplan.Plan{Plan: map[string]*deployplan.PlanEntry{ + "resources.secrets.s": {NewState: &structvar.StructVarJSON{Value: []byte(`{"name":"s","value":"[redacted]"}`)}}, + }} + zeroPlan := &deployplan.Plan{Plan: map[string]*deployplan.PlanEntry{ + "resources.secrets.s": {NewState: &structvar.StructVarJSON{Value: []byte(`{"name":"s"}`)}}, + }} + jobsPlan := &deployplan.Plan{Plan: map[string]*deployplan.PlanEntry{ + "resources.jobs.j": {NewState: &structvar.StructVarJSON{Value: []byte(`{"name":"j"}`)}}, + }} + + tests := []struct { + name string + root *config.Root + plan *deployplan.Plan + flags []string + env map[string]string + wantErr string + }{ + { + name: "plan without sensitive resources needs nothing", + root: secretRoot(t, secretLiteral, variables()), + plan: jobsPlan, + }, + { + name: "missing variables are named", + root: secretRoot(t, secretLiteral, variables()), + plan: secretPlan, + wantErr: msgVarsMissing, + }, + { + name: "empty flag counts as missing even when the environment is set", + root: secretRoot(t, secretLiteral, variables()), + plan: secretPlan, + flags: []string{"api_credential="}, + env: map[string]string{"BUNDLE_VAR_api_credential": "y", "BUNDLE_VAR_api_header": "y"}, + wantErr: msgCredentialMissing, + }, + { + name: "environment supplies both variables", + root: secretRoot(t, secretLiteral, variables()), + plan: secretPlan, + flags: []string{"api_credential=x"}, + env: map[string]string{"BUNDLE_VAR_api_header": "y"}, + }, + { + name: "zero in the plan and set in the config passes", + root: secretRoot(t, secretLiteral, variables()), + plan: zeroPlan, + flags: []string{"api_credential=x", "api_header=y"}, + }, + { + name: "empty config value", + root: secretRoot(t, "", variables()), + plan: secretPlan, + flags: []string{"api_credential=x", "api_header=y"}, + wantErr: msgValueMissing, + }, + { + name: "resource problem comes before the variable problem", + root: secretRoot(t, "", variables()), + plan: secretPlan, + wantErr: msgValueMissing + "; " + msgVarsMissing, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ctx := t.Context() + for k, v := range tc.env { + ctx = env.Set(ctx, k, v) //nolint:fatcontext // the variables accumulate on one context by design + } + err := CheckSensitivePlanValues(ctx, tc.root, tc.plan, tc.flags) + if tc.wantErr == "" { + assert.NoError(t, err) + return + } + assert.EqualError(t, err, tc.wantErr) + }) + } +} From 2212f0cc4c54c408f4279254d6d107c4978007a2 Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Mon, 16 Nov 2026 16:24:06 +0000 Subject: [PATCH 04/17] Cover sensitive variables in plan and saved plan deploys The acceptance test checks that the literals stay out of plan output, the saved plan and local state, that a saved plan needs the values passed again, that an empty value fails before any state-changing request, and that a rotated value reaches only the PATCH request. Co-authored-by: Isaac --- .../variables/sensitive/plan/databricks.yml | 26 +++++ .../variables/sensitive/plan/out.test.toml | 2 + .../variables/sensitive/plan/output.txt | 103 ++++++++++++++++++ .../bundle/variables/sensitive/plan/script | 49 +++++++++ .../bundle/variables/sensitive/plan/test.toml | 2 + 5 files changed, 182 insertions(+) create mode 100644 acceptance/bundle/variables/sensitive/plan/databricks.yml create mode 100644 acceptance/bundle/variables/sensitive/plan/out.test.toml create mode 100644 acceptance/bundle/variables/sensitive/plan/output.txt create mode 100644 acceptance/bundle/variables/sensitive/plan/script create mode 100644 acceptance/bundle/variables/sensitive/plan/test.toml diff --git a/acceptance/bundle/variables/sensitive/plan/databricks.yml b/acceptance/bundle/variables/sensitive/plan/databricks.yml new file mode 100644 index 00000000000..bcf245d43f5 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan/databricks.yml @@ -0,0 +1,26 @@ +bundle: + name: sensitive-variables + +variables: + api_credential: + description: Credential for the external API, passed via BUNDLE_VAR_api_credential. + sensitive: true + api_header: + description: Header value for the plain secret, passed via BUNDLE_VAR_api_header. + sensitive: true + +resources: + catalogs: + audit_catalog: + name: audit_catalog + secrets: + ref_secret: + name: ref_secret + catalog_name: ${resources.catalogs.audit_catalog.name} + schema_name: default + value: ${var.api_credential} + plain_secret: + name: plain_secret + catalog_name: main + schema_name: default + value: ${var.api_header} diff --git a/acceptance/bundle/variables/sensitive/plan/out.test.toml b/acceptance/bundle/variables/sensitive/plan/out.test.toml new file mode 100644 index 00000000000..a927a5fbc06 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = ["", "true"] diff --git a/acceptance/bundle/variables/sensitive/plan/output.txt b/acceptance/bundle/variables/sensitive/plan/output.txt new file mode 100644 index 00000000000..b72d9d38dc5 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan/output.txt @@ -0,0 +1,103 @@ + +=== bundle plan (text) + +>>> [CLI] bundle plan +create catalogs.audit_catalog +create secrets.plain_secret +create secrets.ref_secret + +Plan: 3 to add, 0 to change, 0 to delete, 0 unchanged + +=== bundle plan -o json, saved to a file + +>>> jq -S .plan | map_values(.new_state) .databricks/plan.json +{ + "resources.catalogs.audit_catalog": { + "value": { + "name": "audit_catalog" + } + }, + "resources.secrets.plain_secret": { + "value": { + "catalog_name": "main", + "name": "plain_secret", + "schema_name": "default", + "value": "[redacted]" + } + }, + "resources.secrets.ref_secret": { + "value": { + "catalog_name": "audit_catalog", + "name": "ref_secret", + "schema_name": "default", + "value": "[redacted]" + } + } +} + +=== deploy from the saved plan with the sensitive variable only in a variable file + +>>> env -u BUNDLE_VAR_api_header [CLI] bundle deploy --plan .databricks/plan.json +Error: sensitive variable api_header has no value; pass it with --var api_header=... or BUNDLE_VAR_api_header when deploying from a saved plan (the variable-overrides file is not read for sensitive variables) + + +=== deploy from the saved plan with an empty sensitive variable + +>>> env BUNDLE_VAR_api_credential= [CLI] bundle deploy --plan .databricks/plan.json +Error: resource resources.secrets.ref_secret: the config has no value for sensitive field value; pass the value; sensitive variable api_credential has no value; pass it with --var api_credential=... or BUNDLE_VAR_api_credential when deploying from a saved plan (the variable-overrides file is not read for sensitive variables) + +state-changing requests sent by the failed deploy: 0 + +=== deploy from the saved plan with the sensitive variables supplied + +>>> [CLI] bundle deploy --plan .databricks/plan.json +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created catalogs.audit_catalog +Created secrets.plain_secret +Created secrets.ref_secret +Files: 1 uploaded, 0 deleted +Resources: 3 created, 0 changed, 0 deleted, 0 unchanged + +=== bundle destroy, then a plain bundle deploy creates the secrets again + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.catalogs.audit_catalog + delete resources.secrets.plain_secret + delete resources.secrets.ref_secret + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 3 deleted + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created catalogs.audit_catalog +Created secrets.plain_secret +Created secrets.ref_secret +Files: 1 uploaded, 0 deleted +Resources: 3 created, 0 changed, 0 deleted, 0 unchanged + +=== bundle plan -o json after deploy: remote_state holds the marker + +>>> jq -S .plan | map_values(.remote_state.value) .databricks/plan-after.json +{ + "resources.catalogs.audit_catalog": null, + "resources.secrets.plain_secret": "[redacted]", + "resources.secrets.ref_secret": "[redacted]" +} + +=== rotate the plain secret: plan and deploy with a new value +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Updated secrets.plain_secret +Files: 0 uploaded, 0 deleted +Resources: 0 created, 1 changed, 0 deleted, 2 unchanged + +=== requests carrying a secret literal: path, name and value +{"path":"/api/2.1/unity-catalog/secrets","name":"plain_secret","value":"dummy-header"} +{"path":"/api/2.1/unity-catalog/secrets","name":"plain_secret","value":"dummy-header"} +{"path":"/api/2.1/unity-catalog/secrets","name":"ref_secret","value":"dummy-credential"} +{"path":"/api/2.1/unity-catalog/secrets","name":"ref_secret","value":"dummy-credential"} +{"path":"/api/2.1/unity-catalog/secrets/main.default.plain_secret","name":"plain_secret","value":"dummy-rotated"} + +=== no secret value in the local state (the dump differs per DMS variant, so it is not shown) diff --git a/acceptance/bundle/variables/sensitive/plan/script b/acceptance/bundle/variables/sensitive/plan/script new file mode 100644 index 00000000000..5c5ed7c6da3 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan/script @@ -0,0 +1,49 @@ +# The values of the sensitive variables must not appear in any CLI output, the saved plan or the +# local state. The request log is checked for the real values instead, since the API needs them. +SECRETS=('!dummy-credential' '!dummy-header') +ROTATED=dummy-rotated + +title "bundle plan (text)" +trace $CLI bundle plan | contains.py "${SECRETS[@]}" + +title "bundle plan -o json, saved to a file" +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan.json +trace jq -S '.plan | map_values(.new_state)' .databricks/plan.json + +# A variable file supplies a value, but a saved plan only accepts --var and BUNDLE_VAR_. +title "deploy from the saved plan with the sensitive variable only in a variable file" +mkdir -p .databricks/bundle/default +echo '{"api_header": "dummy-header"}' > .databricks/bundle/default/variable-overrides.json +musterr trace env -u BUNDLE_VAR_api_header $CLI bundle deploy --plan .databricks/plan.json +rm .databricks/bundle/default/variable-overrides.json + +# An empty value counts as missing. The deploy reads the workspace before the check, and the number of +# those reads differs per DMS variant, so only the state-changing requests are counted. +title "deploy from the saved plan with an empty sensitive variable" +before=$(wc -l < "$OUT_REQUESTS") +musterr trace env BUNDLE_VAR_api_credential= $CLI bundle deploy --plan .databricks/plan.json +echo "state-changing requests sent by the failed deploy: $(tail -n +$((before+1)) "$OUT_REQUESTS" | jq -s 'map(select(.method != "GET" and .path != "/telemetry-ext")) | length')" + +title "deploy from the saved plan with the sensitive variables supplied" +trace $CLI bundle deploy --plan .databricks/plan.json | contains.py "${SECRETS[@]}" + +# A plain deploy sends the values from the state cache, a different path from the saved plan. +title "bundle destroy, then a plain bundle deploy creates the secrets again" +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" + +title "bundle plan -o json after deploy: remote_state holds the marker" +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan-after.json +trace jq -S '.plan | map_values(.remote_state.value)' .databricks/plan-after.json + +# Rotating a value: the saved plan is applied with the new value, which only the PATCH may carry. +title "rotate the plain secret: plan and deploy with a new value" +BUNDLE_VAR_api_header=$ROTATED $CLI bundle plan -o json | contains.py "${SECRETS[@]}" "!$ROTATED" > .databricks/plan-rotate.json +BUNDLE_VAR_api_header=$ROTATED $CLI bundle deploy --plan .databricks/plan-rotate.json | contains.py "${SECRETS[@]}" "!$ROTATED" + +title "requests carrying a secret literal: path, name and value" +jq -c --arg rotated "$ROTATED" 'select(tostring | contains("dummy-credential") or contains("dummy-header") or contains($rotated)) | {path, name: .body.name, value: .body.value}' < "$OUT_REQUESTS" | sort + +# The state dump differs per DMS variant, so only the match is checked, not the output. +title "no secret value in the local state (the dump differs per DMS variant, so it is not shown)" +find .databricks -type f -exec cat {} + | contains.py "${SECRETS[@]}" "!$ROTATED" > /dev/null diff --git a/acceptance/bundle/variables/sensitive/plan/test.toml b/acceptance/bundle/variables/sensitive/plan/test.toml new file mode 100644 index 00000000000..54fc177c9f1 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan/test.toml @@ -0,0 +1,2 @@ +RecordRequests = true +Env.BUNDLE_VAR_api_header = "dummy-header" From fcecb403f7035aef193689718029765f4f94b459 Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Fri, 20 Nov 2026 14:01:02 +0000 Subject: [PATCH 05/17] Check resolved sensitive values for saved plan deploys deploy --plan rejected every sensitive variable that had no --var or BUNDLE_VAR_ value, including variables a resource never uses and variables set by a default, a target or the variable-overrides file. The check now looks only at the resolved config value of each sensitive field the plan sets, so every source of a value counts the same, and the variable-overrides file is no longer a special case. The check reports one error per problem, and it reads the adapter only for resource types with sensitive fields. The acceptance case variables/sensitive/plan-derived covers unused derived, literal-default and target-set sensitive variables. Co-authored-by: Isaac --- .nextchanges/bundles/7713.md | 2 +- .../sensitive/plan-derived/databricks.yml | 34 +++++++ .../sensitive/plan-derived/out.test.toml | 2 + .../sensitive/plan-derived/output.txt | 25 +++++ .../variables/sensitive/plan-derived/script | 17 ++++ .../sensitive/plan-derived/test.toml | 3 + .../variables/sensitive/plan/output.txt | 6 +- .../bundle/variables/sensitive/plan/script | 6 +- bundle/direct/bundle_plan.go | 93 ++++++------------- bundle/direct/dresources/redact_config.go | 5 + bundle/direct/redact.go | 13 +-- bundle/direct/redact_test.go | 93 ++++++++----------- cmd/bundle/utils/process.go | 6 +- 13 files changed, 169 insertions(+), 136 deletions(-) create mode 100644 acceptance/bundle/variables/sensitive/plan-derived/databricks.yml create mode 100644 acceptance/bundle/variables/sensitive/plan-derived/out.test.toml create mode 100644 acceptance/bundle/variables/sensitive/plan-derived/output.txt create mode 100644 acceptance/bundle/variables/sensitive/plan-derived/script create mode 100644 acceptance/bundle/variables/sensitive/plan-derived/test.toml diff --git a/.nextchanges/bundles/7713.md b/.nextchanges/bundles/7713.md index 59ab5752890..8e4743c6e97 100644 --- a/.nextchanges/bundles/7713.md +++ b/.nextchanges/bundles/7713.md @@ -1 +1 @@ -* `bundle plan` no longer shows or saves sensitive variable values, and `bundle deploy --plan` requires them to be passed again with `--var` or `BUNDLE_VAR_`; `deploy --plan` applies the values supplied at deploy time, not those at plan time. ([#7713](https://github.com/databricks/cli/pull/7713)) +* `bundle plan` no longer shows or saves sensitive variable values, and `bundle deploy --plan` requires them to be supplied again at deploy time (for example with `--var` or `BUNDLE_VAR_`). `deploy --plan` applies the sensitive values supplied at deploy time, which are not checked against the values used at plan time. ([#7713](https://github.com/databricks/cli/pull/7713)) diff --git a/acceptance/bundle/variables/sensitive/plan-derived/databricks.yml b/acceptance/bundle/variables/sensitive/plan-derived/databricks.yml new file mode 100644 index 00000000000..f8bc0bee2d9 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-derived/databricks.yml @@ -0,0 +1,34 @@ +bundle: + name: sensitive-variables + +# Sensitive variables that no resource uses need no value for a saved plan to apply. A variable used as a +# secret value cannot have a default or a target value, so the other sensitive variables are unused. +variables: + api_credential: + description: Credential for the external API, passed via the variable-overrides file. + sensitive: true + api_header: + description: Sensitive, derived from another sensitive variable, and not used by a resource. + sensitive: true + default: "Bearer ${var.api_credential}" + api_literal: + description: Sensitive with a literal default, and not used by a resource. + sensitive: true + default: dummy-literal + api_token: + description: Sensitive, not used by a resource, and set only for the dev target. + sensitive: true + +targets: + dev: + default: true + variables: + api_token: dummy-target + +resources: + secrets: + credential_secret: + name: credential_secret + catalog_name: main + schema_name: default + value: ${var.api_credential} diff --git a/acceptance/bundle/variables/sensitive/plan-derived/out.test.toml b/acceptance/bundle/variables/sensitive/plan-derived/out.test.toml new file mode 100644 index 00000000000..a927a5fbc06 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-derived/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = ["", "true"] diff --git a/acceptance/bundle/variables/sensitive/plan-derived/output.txt b/acceptance/bundle/variables/sensitive/plan-derived/output.txt new file mode 100644 index 00000000000..2bb715c67f6 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-derived/output.txt @@ -0,0 +1,25 @@ + +=== bundle plan -o json, saved to a file + +>>> jq -S .plan | map_values(.new_state) .databricks/plan.json +{ + "resources.secrets.credential_secret": { + "value": { + "catalog_name": "main", + "name": "credential_secret", + "schema_name": "default", + "value": "[redacted]" + } + } +} + +=== deploy from the saved plan with the credential in the variable-overrides file + +>>> env -u BUNDLE_VAR_api_credential [CLI] bundle deploy --plan .databricks/plan.json +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/dev/files... +Created secrets.credential_secret +Files: 1 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +=== requests carrying a secret literal: path, name and value +{"path":"/api/2.1/unity-catalog/secrets","name":"credential_secret","value":"dummy-credential"} diff --git a/acceptance/bundle/variables/sensitive/plan-derived/script b/acceptance/bundle/variables/sensitive/plan-derived/script new file mode 100644 index 00000000000..5cc78bd6f57 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-derived/script @@ -0,0 +1,17 @@ +# The secret values must not appear in CLI output or the saved plan, only in the requests. +SECRETS=('!dummy-credential' '!Bearer dummy-credential' '!dummy-literal' '!dummy-target') + +title "bundle plan -o json, saved to a file" +mkdir -p .databricks +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan.json +trace jq -S '.plan | map_values(.new_state)' .databricks/plan.json + +# The variable-overrides file supplies the credential, and the unused derived and literal variables need no value. +title "deploy from the saved plan with the credential in the variable-overrides file" +mkdir -p .databricks/bundle/dev +echo '{"api_credential": "dummy-credential"}' > .databricks/bundle/dev/variable-overrides.json +trace env -u BUNDLE_VAR_api_credential $CLI bundle deploy --plan .databricks/plan.json | contains.py "${SECRETS[@]}" +rm .databricks/bundle/dev/variable-overrides.json + +title "requests carrying a secret literal: path, name and value" +jq -c 'select(tostring | contains("dummy-credential")) | {path, name: .body.name, value: .body.value}' < "$OUT_REQUESTS" | sort diff --git a/acceptance/bundle/variables/sensitive/plan-derived/test.toml b/acceptance/bundle/variables/sensitive/plan-derived/test.toml new file mode 100644 index 00000000000..b9864165e0c --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-derived/test.toml @@ -0,0 +1,3 @@ +RecordRequests = true +Cloud = false +EnvMatrix.DMS = ["", "true"] diff --git a/acceptance/bundle/variables/sensitive/plan/output.txt b/acceptance/bundle/variables/sensitive/plan/output.txt index b72d9d38dc5..f190193ef33 100644 --- a/acceptance/bundle/variables/sensitive/plan/output.txt +++ b/acceptance/bundle/variables/sensitive/plan/output.txt @@ -35,16 +35,16 @@ Plan: 3 to add, 0 to change, 0 to delete, 0 unchanged } } -=== deploy from the saved plan with the sensitive variable only in a variable file +=== deploy from the saved plan without the sensitive variable >>> env -u BUNDLE_VAR_api_header [CLI] bundle deploy --plan .databricks/plan.json -Error: sensitive variable api_header has no value; pass it with --var api_header=... or BUNDLE_VAR_api_header when deploying from a saved plan (the variable-overrides file is not read for sensitive variables) +Error: no value assigned to required variable api_header. Variables are usually assigned in databricks.yml, and they can be overridden using "--var", the BUNDLE_VAR_api_header environment variable, or .databricks/bundle//variable-overrides.json === deploy from the saved plan with an empty sensitive variable >>> env BUNDLE_VAR_api_credential= [CLI] bundle deploy --plan .databricks/plan.json -Error: resource resources.secrets.ref_secret: the config has no value for sensitive field value; pass the value; sensitive variable api_credential has no value; pass it with --var api_credential=... or BUNDLE_VAR_api_credential when deploying from a saved plan (the variable-overrides file is not read for sensitive variables) +Error: resource resources.secrets.ref_secret: the config has no value for sensitive field value; set the variable it uses with --var or BUNDLE_VAR_ state-changing requests sent by the failed deploy: 0 diff --git a/acceptance/bundle/variables/sensitive/plan/script b/acceptance/bundle/variables/sensitive/plan/script index 5c5ed7c6da3..a26543c56e1 100644 --- a/acceptance/bundle/variables/sensitive/plan/script +++ b/acceptance/bundle/variables/sensitive/plan/script @@ -10,12 +10,8 @@ title "bundle plan -o json, saved to a file" $CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan.json trace jq -S '.plan | map_values(.new_state)' .databricks/plan.json -# A variable file supplies a value, but a saved plan only accepts --var and BUNDLE_VAR_. -title "deploy from the saved plan with the sensitive variable only in a variable file" -mkdir -p .databricks/bundle/default -echo '{"api_header": "dummy-header"}' > .databricks/bundle/default/variable-overrides.json +title "deploy from the saved plan without the sensitive variable" musterr trace env -u BUNDLE_VAR_api_header $CLI bundle deploy --plan .databricks/plan.json -rm .databricks/bundle/default/variable-overrides.json # An empty value counts as missing. The deploy reads the workspace before the check, and the number of # those reads differs per DMS variant, so only the state-changing requests are counted. diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index ab956a8b952..b96734bd316 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -19,7 +19,6 @@ import ( "github.com/databricks/cli/bundle/terraform_dabs_map" "github.com/databricks/cli/libs/dyn" "github.com/databricks/cli/libs/dyn/dynvar" - "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/logdiag" "github.com/databricks/cli/libs/retry" @@ -70,40 +69,48 @@ func ValidatePlanAgainstState(stateDB *dstate.DeploymentState, plan *deployplan. return nil } -// CheckSensitivePlanValues rejects a saved plan that cannot be applied until its sensitive values are -// supplied again, and returns one error that lists every problem. When the plan has a sensitive -// resource, every sensitive variable of the bundle must be set with --var or BUNDLE_VAR_, since -// telling used variables from unused ones needs reference resolution. -func CheckSensitivePlanValues(ctx context.Context, root *config.Root, plan *deployplan.Plan, flagVars []string) error { - adapters, err := dresources.InitAll(nil) - if err != nil { - return err +// CheckSensitivePlanValues returns one error per problem that stops a saved plan from being applied: +// a sensitive field the plan sets whose resolved config value is empty. The resolved config holds the +// values from --var, BUNDLE_VAR_, defaults, targets and the variable-overrides file alike, so any of +// them supplies a value. Sensitive variables the plan does not use need no value. +func CheckSensitivePlanValues(root *config.Root, plan *deployplan.Plan) []error { + var problems []error + seen := make(map[string]bool) + addProblem := func(err error) { + if !seen[err.Error()] { + seen[err.Error()] = true + problems = append(problems, err) + } } - var problems []string - needsValues := false for _, resourceKey := range slices.Sorted(maps.Keys(plan.Plan)) { entry := plan.Plan[resourceKey] if entry.NewState == nil { continue } - adapter, ok := adapters[config.GetResourceTypeFromKey(resourceKey)] + resourceType := config.GetResourceTypeFromKey(resourceKey) + typedNil, ok := dresources.SupportedResources[resourceType] if !ok { - problems = append(problems, fmt.Sprintf("resource %s: unknown resource type", resourceKey)) + addProblem(fmt.Errorf("resource %s: unknown resource type", resourceKey)) + continue + } + rules := dresources.SensitiveFieldRules(resourceType) + if len(rules) == 0 { continue } - if len(adapter.GetSensitiveFields()) == 0 { + adapter, err := dresources.NewAdapter(typedNil, resourceType, nil) + if err != nil { + addProblem(fmt.Errorf("resource %s: %w", resourceKey, err)) continue } - needsValues = true sv, err := entry.NewState.ToStructVar(adapter.StateType()) if err != nil { - problems = append(problems, fmt.Sprintf("resource %s: %s", resourceKey, err)) + addProblem(fmt.Errorf("resource %s: %w", resourceKey, err)) continue } - paths, err := sensitivePaths(adapter) + paths, err := sensitivePaths(rules) if err != nil { - problems = append(problems, fmt.Sprintf("resource %s: %s", resourceKey, err)) + addProblem(fmt.Errorf("resource %s: %w", resourceKey, err)) continue } for _, path := range paths { @@ -112,57 +119,11 @@ func CheckSensitivePlanValues(ctx context.Context, root *config.Root, plan *depl continue } if _, err := sensitiveConfigValue(root, resourceKey, path, planned); err != nil { - problems = append(problems, err.Error()) - } - } - } - - var missing []string - if needsValues { - for name, v := range root.Variables { - if v == nil || !config.IsExplicitlyEnabled(v.Sensitive) || variableSupplied(ctx, name, flagVars) { - continue + addProblem(err) } - missing = append(missing, name) } - slices.Sort(missing) - } - if len(missing) > 0 { - problems = append(problems, missingVariablesError(missing)) - } - - if len(problems) == 0 { - return nil - } - return errors.New(strings.Join(problems, "; ")) -} - -// missingVariablesError names the sensitive variables that have no --var or BUNDLE_VAR_ value. -func missingVariablesError(missing []string) string { - const overrides = "the variable-overrides file is not read for sensitive variables" - if len(missing) == 1 { - name := missing[0] - return fmt.Sprintf("sensitive variable %s has no value; pass it with --var %s=... or BUNDLE_VAR_%s when deploying from a saved plan (%s)", name, name, name, overrides) - } - return fmt.Sprintf("sensitive variables %s have no value; pass each with --var NAME=... or BUNDLE_VAR_NAME when deploying from a saved plan (%s)", strings.Join(missing, ", "), overrides) -} - -// variableSupplied reports whether a sensitive variable has a value from --var or BUNDLE_VAR_. -// The resolved value also carries values from the variable-overrides file, so the check reads only -// flags and the environment. A --var given with an empty value wins over the environment. -func variableSupplied(ctx context.Context, name string, flagVars []string) bool { - flagged, found := "", false - for _, assignment := range flagVars { - key, value, _ := strings.Cut(assignment, "=") - if key == name { - flagged, found = value, true - } - } - if found { - return flagged != "" } - value, _ := env.Lookup(ctx, "BUNDLE_VAR_"+name) - return value != "" + return problems } // InitForApply initializes the DeploymentBundle for applying a pre-computed plan. The sensitive diff --git a/bundle/direct/dresources/redact_config.go b/bundle/direct/dresources/redact_config.go index 185713ea830..b45ea11deb8 100644 --- a/bundle/direct/dresources/redact_config.go +++ b/bundle/direct/dresources/redact_config.go @@ -60,6 +60,11 @@ func redactSensitiveVariables(root *config.Root) { } } +// SensitiveFieldRules returns the sensitive fields of a resource type without building its adapter. +func SensitiveFieldRules(resourceType string) []FieldRule { + return getSensitiveFields()[resourceType] +} + // getSensitiveFields returns the map of resource type to list of sensitive fields. func getSensitiveFields() map[string][]FieldRule { cfg := MustLoadConfig() diff --git a/bundle/direct/redact.go b/bundle/direct/redact.go index ff0c0bc485c..9a14b5fd746 100644 --- a/bundle/direct/redact.go +++ b/bundle/direct/redact.go @@ -13,10 +13,11 @@ import ( const sensitiveRedactedValue = "[redacted]" -// sensitivePaths parses the sensitive field paths of the adapter. -func sensitivePaths(adapter *dresources.Adapter) ([]*structpath.PathNode, error) { +// sensitivePaths parses the sensitive field rules of a resource type. +func sensitivePaths(rules []dresources.FieldRule) ([]*structpath.PathNode, error) { var paths []*structpath.PathNode - for _, field := range adapter.GetSensitiveFields() { + for _, rule := range rules { + field := rule.Field.String() path, err := structpath.ParsePath(field) if err != nil { return nil, fmt.Errorf("parsing sensitive field path %q: %w", field, err) @@ -34,7 +35,7 @@ func redactSensitiveFields(adapter *dresources.Adapter, s any, replacement strin return nil } - paths, err := sensitivePaths(adapter) + paths, err := sensitivePaths(adapter.ResourceConfig().SensitiveFields) if err != nil { return err } @@ -147,13 +148,13 @@ func sensitiveConfigValue(root *config.Root, resourceKey string, path *structpat if rc == nil { return "", fmt.Errorf("resource %s is not in the config; run 'bundle plan' again", resourceKey) } - return "", fmt.Errorf("resource %s: the config has no value for sensitive field %s; pass the value", resourceKey, path) + return "", fmt.Errorf("resource %s: the config has no value for sensitive field %s; set the variable it uses with --var or BUNDLE_VAR_", resourceKey, path) } // restoreSensitiveFields replaces the sensitive values in s, a saved plan's state, with the values // the current config sets. CheckSensitivePlanValues runs the same rule before the plan is approved. func restoreSensitiveFields(adapter *dresources.Adapter, resourceKey string, s any, root *config.Root) error { - paths, err := sensitivePaths(adapter) + paths, err := sensitivePaths(adapter.ResourceConfig().SensitiveFields) if err != nil { return err } diff --git a/bundle/direct/redact_test.go b/bundle/direct/redact_test.go index 5a806971799..8081387392c 100644 --- a/bundle/direct/redact_test.go +++ b/bundle/direct/redact_test.go @@ -10,7 +10,6 @@ import ( "github.com/databricks/cli/bundle/deployplan" "github.com/databricks/cli/bundle/direct/dresources" "github.com/databricks/cli/libs/dyn" - "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/structs/structpath" "github.com/databricks/cli/libs/structs/structvar" "github.com/databricks/databricks-sdk-go/service/catalog" @@ -93,10 +92,8 @@ func secretRoot(t *testing.T, value string, variables map[string]*variable.Varia } const ( - msgValueMissing = "resource resources.secrets.s: the config has no value for sensitive field value; pass the value" - msgNotInConfig = "resource resources.secrets.gone is not in the config; run 'bundle plan' again" - msgCredentialMissing = "sensitive variable api_credential has no value; pass it with --var api_credential=... or BUNDLE_VAR_api_credential when deploying from a saved plan (the variable-overrides file is not read for sensitive variables)" - msgVarsMissing = "sensitive variables api_credential, api_header have no value; pass each with --var NAME=... or BUNDLE_VAR_NAME when deploying from a saved plan (the variable-overrides file is not read for sensitive variables)" + msgValueMissing = "resource resources.secrets.s: the config has no value for sensitive field value; set the variable it uses with --var or BUNDLE_VAR_" + msgNotInConfig = "resource resources.secrets.gone is not in the config; run 'bundle plan' again" ) func TestRestoreSensitiveFields(t *testing.T) { @@ -185,12 +182,9 @@ func TestSensitiveConfigValueNestedField(t *testing.T) { func TestCheckSensitivePlanValues(t *testing.T) { sensitive := true - variables := func() map[string]*variable.Variable { - return map[string]*variable.Variable{ - "api_credential": {Sensitive: &sensitive}, - "api_header": {Sensitive: &sensitive}, - "target_schema": {}, - } + variables := map[string]*variable.Variable{ + "api_credential": {Sensitive: &sensitive}, + "target_schema": {}, } secretPlan := &deployplan.Plan{Plan: map[string]*deployplan.PlanEntry{ "resources.secrets.s": {NewState: &structvar.StructVarJSON{Value: []byte(`{"name":"s","value":"[redacted]"}`)}}, @@ -206,69 +200,62 @@ func TestCheckSensitivePlanValues(t *testing.T) { name string root *config.Root plan *deployplan.Plan - flags []string - env map[string]string wantErr string }{ { name: "plan without sensitive resources needs nothing", - root: secretRoot(t, secretLiteral, variables()), + root: secretRoot(t, "", variables), plan: jobsPlan, }, { - name: "missing variables are named", - root: secretRoot(t, secretLiteral, variables()), - plan: secretPlan, - wantErr: msgVarsMissing, - }, - { - name: "empty flag counts as missing even when the environment is set", - root: secretRoot(t, secretLiteral, variables()), - plan: secretPlan, - flags: []string{"api_credential="}, - env: map[string]string{"BUNDLE_VAR_api_credential": "y", "BUNDLE_VAR_api_header": "y"}, - wantErr: msgCredentialMissing, + name: "sensitive value set in the config passes", + root: secretRoot(t, secretLiteral, variables), + plan: secretPlan, }, { - name: "environment supplies both variables", - root: secretRoot(t, secretLiteral, variables()), - plan: secretPlan, - flags: []string{"api_credential=x"}, - env: map[string]string{"BUNDLE_VAR_api_header": "y"}, + name: "zero in the plan and set in the config passes", + root: secretRoot(t, secretLiteral, variables), + plan: zeroPlan, }, { - name: "zero in the plan and set in the config passes", - root: secretRoot(t, secretLiteral, variables()), - plan: zeroPlan, - flags: []string{"api_credential=x", "api_header=y"}, - }, - { - name: "empty config value", - root: secretRoot(t, "", variables()), + name: "empty config value is reported", + root: secretRoot(t, "", variables), plan: secretPlan, - flags: []string{"api_credential=x", "api_header=y"}, wantErr: msgValueMissing, }, - { - name: "resource problem comes before the variable problem", - root: secretRoot(t, "", variables()), - plan: secretPlan, - wantErr: msgValueMissing + "; " + msgVarsMissing, - }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - ctx := t.Context() - for k, v := range tc.env { - ctx = env.Set(ctx, k, v) //nolint:fatcontext // the variables accumulate on one context by design - } - err := CheckSensitivePlanValues(ctx, tc.root, tc.plan, tc.flags) + errs := CheckSensitivePlanValues(tc.root, tc.plan) if tc.wantErr == "" { - assert.NoError(t, err) + assert.Empty(t, errs) return } - assert.EqualError(t, err, tc.wantErr) + require.Len(t, errs, 1) + assert.EqualError(t, errs[0], tc.wantErr) }) } } + +// TestCheckSensitivePlanValuesOneErrorPerProblem checks that each resource with a missing value gets its +// own error, and that a resource missing from the config is reported once, not once per sensitive field. +func TestCheckSensitivePlanValuesOneErrorPerProblem(t *testing.T) { + root := syncedRoot(t, &config.Root{Resources: config.Resources{ + Secrets: map[string]*resources.Secret{ + "a": {Secret: catalog.Secret{Name: "a"}}, + "b": {Secret: catalog.Secret{Name: "b"}}, + }, + }}) + plan := &deployplan.Plan{Plan: map[string]*deployplan.PlanEntry{ + "resources.secrets.a": {NewState: &structvar.StructVarJSON{Value: []byte(`{"name":"a","value":"[redacted]"}`)}}, + "resources.secrets.b": {NewState: &structvar.StructVarJSON{Value: []byte(`{"name":"b","value":"[redacted]"}`)}}, + "resources.secrets.gone": {NewState: &structvar.StructVarJSON{Value: []byte(`{"name":"gone","value":"[redacted]"}`)}}, + }} + + errs := CheckSensitivePlanValues(root, plan) + require.Len(t, errs, 3) + assert.EqualError(t, errs[0], "resource resources.secrets.a: the config has no value for sensitive field value; set the variable it uses with --var or BUNDLE_VAR_") + assert.EqualError(t, errs[1], "resource resources.secrets.b: the config has no value for sensitive field value; set the variable it uses with --var or BUNDLE_VAR_") + assert.EqualError(t, errs[2], msgNotInConfig) +} diff --git a/cmd/bundle/utils/process.go b/cmd/bundle/utils/process.go index 5d5b827c944..22059254c50 100644 --- a/cmd/bundle/utils/process.go +++ b/cmd/bundle/utils/process.go @@ -496,8 +496,10 @@ func ProcessBundleRet(cmd *cobra.Command, opts ProcessOptions) (b *bundle.Bundle return b, stateDesc, root.ErrAlreadyPrinted } - if err := direct.CheckSensitivePlanValues(ctx, &b.Config, plan, variables); err != nil { - logdiag.LogError(ctx, err) + if errs := direct.CheckSensitivePlanValues(&b.Config, plan); len(errs) > 0 { + for _, err := range errs { + logdiag.LogError(ctx, err) + } return b, stateDesc, root.ErrAlreadyPrinted } } From 0b2cd9c34074d2fe5fdc93435651b1b54a6e511d Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Wed, 25 Nov 2026 15:25:13 +0000 Subject: [PATCH 06/17] Shorten the changelog entry for sensitive plan values Co-authored-by: Isaac --- .nextchanges/bundles/7713.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.nextchanges/bundles/7713.md b/.nextchanges/bundles/7713.md index 8e4743c6e97..9523789148b 100644 --- a/.nextchanges/bundles/7713.md +++ b/.nextchanges/bundles/7713.md @@ -1 +1 @@ -* `bundle plan` no longer shows or saves sensitive variable values, and `bundle deploy --plan` requires them to be supplied again at deploy time (for example with `--var` or `BUNDLE_VAR_`). `deploy --plan` applies the sensitive values supplied at deploy time, which are not checked against the values used at plan time. ([#7713](https://github.com/databricks/cli/pull/7713)) +* `bundle plan` no longer shows or saves sensitive variable values, and `bundle deploy --plan` requires them to be supplied again at deploy time (for example with `--var` or `BUNDLE_VAR_`). ([#7713](https://github.com/databricks/cli/pull/7713)) From 4af7b6538267c69b544f59e4a8a27b6bbd56d28f Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Wed, 25 Nov 2026 15:52:28 +0000 Subject: [PATCH 07/17] Redact secret values in plan output in renamed-parent acceptance goldens Plan JSON now shows sensitive values as [redacted]. Deploy and destroy requests still send the real value. Only the three plan "value" lines changed. Co-authored-by: Isaac --- acceptance/bundle/resources/secrets/parent_rename/output.txt | 4 ++-- .../resources/secrets/recreate_in_renamed_schema/output.txt | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/acceptance/bundle/resources/secrets/parent_rename/output.txt b/acceptance/bundle/resources/secrets/parent_rename/output.txt index 6cac5f13385..7b4928e2cf1 100644 --- a/acceptance/bundle/resources/secrets/parent_rename/output.txt +++ b/acceptance/bundle/resources/secrets/parent_rename/output.txt @@ -111,7 +111,7 @@ Resources: 3 created, 0 changed, 0 deleted, 0 unchanged "comment": "c1", "name": "mysecret", "schema_name": "myschema2", - "value": "secret-value" + "value": "[redacted]" } }, "remote_state": { @@ -308,7 +308,7 @@ Resources: 0 created, 1 changed, 0 deleted, 2 unchanged "comment": "c2", "name": "mysecret", "schema_name": "myschema2", - "value": "secret-value" + "value": "[redacted]" } }, "remote_state": { diff --git a/acceptance/bundle/resources/secrets/recreate_in_renamed_schema/output.txt b/acceptance/bundle/resources/secrets/recreate_in_renamed_schema/output.txt index c292b659090..8629bad2d41 100644 --- a/acceptance/bundle/resources/secrets/recreate_in_renamed_schema/output.txt +++ b/acceptance/bundle/resources/secrets/recreate_in_renamed_schema/output.txt @@ -84,7 +84,7 @@ Resources: 3 created, 0 changed, 0 deleted, 0 unchanged "catalog_name": "test_catalog_[UNIQUE_NAME]", "name": "mysecret2", "schema_name": "myschema2", - "value": "secret-value" + "value": "[redacted]" } }, "remote_state": { From d6090e8a9bcdfdc1cd58e5ec4c938fc96d261c5c Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Sat, 28 Nov 2026 09:20:22 +0000 Subject: [PATCH 08/17] Test that a saved plan sends the same secret values as a plain deploy A resource reference and an escaped reference in a sensitive value are restored verbatim from the config, so the create requests of deploy --plan differ from a plain deploy. The test compares the two request bodies and fails on this branch. Co-authored-by: Isaac --- .../sensitive/plan-restore/databricks.yml | 23 +++++++ .../sensitive/plan-restore/out.test.toml | 2 + .../sensitive/plan-restore/output.txt | 69 +++++++++++++++++++ .../variables/sensitive/plan-restore/script | 24 +++++++ .../sensitive/plan-restore/test.toml | 4 ++ 5 files changed, 122 insertions(+) create mode 100644 acceptance/bundle/variables/sensitive/plan-restore/databricks.yml create mode 100644 acceptance/bundle/variables/sensitive/plan-restore/out.test.toml create mode 100644 acceptance/bundle/variables/sensitive/plan-restore/output.txt create mode 100644 acceptance/bundle/variables/sensitive/plan-restore/script create mode 100644 acceptance/bundle/variables/sensitive/plan-restore/test.toml diff --git a/acceptance/bundle/variables/sensitive/plan-restore/databricks.yml b/acceptance/bundle/variables/sensitive/plan-restore/databricks.yml new file mode 100644 index 00000000000..bf083f164c7 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-restore/databricks.yml @@ -0,0 +1,23 @@ +bundle: + name: sensitive-variables + +variables: + api_header: + description: Sensitive value supplied with BUNDLE_VAR_api_header, containing an escaped reference. + sensitive: true + +resources: + catalogs: + source_catalog: + name: dummy-catalog-name + secrets: + ref_secret: + name: ref_secret + catalog_name: main + schema_name: default + value: ${resources.catalogs.source_catalog.name} + escaped_secret: + name: escaped_secret + catalog_name: main + schema_name: default + value: ${var.api_header} diff --git a/acceptance/bundle/variables/sensitive/plan-restore/out.test.toml b/acceptance/bundle/variables/sensitive/plan-restore/out.test.toml new file mode 100644 index 00000000000..a927a5fbc06 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-restore/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = ["", "true"] diff --git a/acceptance/bundle/variables/sensitive/plan-restore/output.txt b/acceptance/bundle/variables/sensitive/plan-restore/output.txt new file mode 100644 index 00000000000..78a4e4f3518 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-restore/output.txt @@ -0,0 +1,69 @@ + +=== plain deploy + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created catalogs.source_catalog +Created secrets.escaped_secret +Created secrets.ref_secret +Files: 1 uploaded, 0 deleted +Resources: 3 created, 0 changed, 0 deleted, 0 unchanged + +=== bundle destroy, then a saved plan + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.catalogs.source_catalog + delete resources.secrets.escaped_secret + delete resources.secrets.ref_secret + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 3 deleted + +>>> jq -S .plan | map_values(.new_state) .databricks/plan.json +{ + "resources.catalogs.source_catalog": { + "value": { + "name": "dummy-catalog-name" + } + }, + "resources.secrets.escaped_secret": { + "value": { + "catalog_name": "main", + "name": "escaped_secret", + "schema_name": "default", + "value": "[redacted]" + } + }, + "resources.secrets.ref_secret": { + "value": { + "catalog_name": "main", + "name": "ref_secret", + "schema_name": "default", + "value": "[redacted]" + } + } +} + +=== deploy from the saved plan + +>>> [CLI] bundle deploy --plan .databricks/plan.json +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created catalogs.source_catalog +Created secrets.escaped_secret +Created secrets.ref_secret +Files: 2 uploaded, 0 deleted +Resources: 3 created, 0 changed, 0 deleted, 0 unchanged + +=== create requests of the plain deploy and the saved plan match +{"name":"escaped_secret","value":"escaped-${x}"} +{"name":"ref_secret","value":"dummy-catalog-name"} +1,2c1,2 +< {"name":"escaped_secret","value":"escaped-${x}"} +< {"name":"ref_secret","value":"dummy-catalog-name"} +--- +> {"name":"escaped_secret","value":"escaped-$${x}"} +> {"name":"ref_secret","value":"${resources.catalogs.source_catalog.name}"} + +Exit code: 1 diff --git a/acceptance/bundle/variables/sensitive/plan-restore/script b/acceptance/bundle/variables/sensitive/plan-restore/script new file mode 100644 index 00000000000..7ba45201fc2 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-restore/script @@ -0,0 +1,24 @@ +# A plain deploy sends the value the config resolves to. A saved plan must send the same value, so the +# create requests of the two deploys are compared. The API needs the values, so they are read from the +# request log only and never appear in CLI output. +# The catalog name is not a secret, so only the escaped variable value is checked for in the output. +SECRETS=('!escaped-') +CREATES='select(.method == "POST" and .path == "/api/2.1/unity-catalog/secrets") | {name: .body.name, value: .body.value}' + +title "plain deploy" +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" +jq -c "$CREATES" < "$OUT_REQUESTS" | sort > plain.json + +title "bundle destroy, then a saved plan" +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan.json +trace jq -S '.plan | map_values(.new_state)' .databricks/plan.json + +title "deploy from the saved plan" +before=$(wc -l < "$OUT_REQUESTS") +trace $CLI bundle deploy --plan .databricks/plan.json | contains.py "${SECRETS[@]}" +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$CREATES" | sort > saved.json + +title "create requests of the plain deploy and the saved plan match" +cat plain.json +diff plain.json saved.json diff --git a/acceptance/bundle/variables/sensitive/plan-restore/test.toml b/acceptance/bundle/variables/sensitive/plan-restore/test.toml new file mode 100644 index 00000000000..3f5a71b07fa --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-restore/test.toml @@ -0,0 +1,4 @@ +RecordRequests = true +Env.BUNDLE_VAR_api_header = 'escaped-$${x}' +Cloud = false +EnvMatrix.DMS = ["", "true"] From 43402631c316e7b8ce31eac5e72bda8de9cd3b29 Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Sat, 28 Nov 2026 09:26:22 +0000 Subject: [PATCH 09/17] Restore saved plan secrets the way a plain deploy builds them The deploy from a saved plan restored the sensitive fields from the raw config string, so a reference was sent as its literal text and an escaped reference as its escaped form. The restore now builds the state the way makePlan does (PrepareInputConfig, PrepareState, unescapeRefs) and keeps the references of sensitive fields for apply to resolve. A value that still holds an unresolved reference is an error. The check before apply and the apply share one restore (restoreSavedPlanStates), so they cannot disagree. A resource missing from the config is reported once. Apply no longer serializes resolved references back into the plan entry, so the redacted plan entries keep no secret after a deploy. Co-authored-by: Isaac --- .../sensitive/plan-restore/output.txt | 10 +- .../variables/sensitive/plan-restore/script | 8 +- bundle/direct/bundle_plan.go | 108 ++++++++---------- bundle/direct/dresources/redact_config.go | 5 - bundle/direct/redact.go | 102 ++++++++++++----- bundle/direct/redact_test.go | 87 +++++++++----- 6 files changed, 183 insertions(+), 137 deletions(-) diff --git a/acceptance/bundle/variables/sensitive/plan-restore/output.txt b/acceptance/bundle/variables/sensitive/plan-restore/output.txt index 78a4e4f3518..c0350a07e47 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/output.txt +++ b/acceptance/bundle/variables/sensitive/plan-restore/output.txt @@ -53,17 +53,9 @@ Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variable Created catalogs.source_catalog Created secrets.escaped_secret Created secrets.ref_secret -Files: 2 uploaded, 0 deleted +Files: 1 uploaded, 0 deleted Resources: 3 created, 0 changed, 0 deleted, 0 unchanged === create requests of the plain deploy and the saved plan match {"name":"escaped_secret","value":"escaped-${x}"} {"name":"ref_secret","value":"dummy-catalog-name"} -1,2c1,2 -< {"name":"escaped_secret","value":"escaped-${x}"} -< {"name":"ref_secret","value":"dummy-catalog-name"} ---- -> {"name":"escaped_secret","value":"escaped-$${x}"} -> {"name":"ref_secret","value":"${resources.catalogs.source_catalog.name}"} - -Exit code: 1 diff --git a/acceptance/bundle/variables/sensitive/plan-restore/script b/acceptance/bundle/variables/sensitive/plan-restore/script index 7ba45201fc2..725200d9cc6 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/script +++ b/acceptance/bundle/variables/sensitive/plan-restore/script @@ -7,7 +7,7 @@ CREATES='select(.method == "POST" and .path == "/api/2.1/unity-catalog/secrets") title "plain deploy" trace $CLI bundle deploy | contains.py "${SECRETS[@]}" -jq -c "$CREATES" < "$OUT_REQUESTS" | sort > plain.json +jq -c "$CREATES" < "$OUT_REQUESTS" | sort > .databricks/plain.json title "bundle destroy, then a saved plan" trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" @@ -17,8 +17,8 @@ trace jq -S '.plan | map_values(.new_state)' .databricks/plan.json title "deploy from the saved plan" before=$(wc -l < "$OUT_REQUESTS") trace $CLI bundle deploy --plan .databricks/plan.json | contains.py "${SECRETS[@]}" -tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$CREATES" | sort > saved.json +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$CREATES" | sort > .databricks/saved.json title "create requests of the plain deploy and the saved plan match" -cat plain.json -diff plain.json saved.json +cat .databricks/plain.json +diff .databricks/plain.json .databricks/saved.json diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index c8be0824720..6a9508c0b26 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -69,61 +69,54 @@ func ValidatePlanAgainstState(stateDB *dstate.DeploymentState, plan *deployplan. return nil } -// CheckSensitivePlanValues returns one error per problem that stops a saved plan from being applied: -// a sensitive field the plan sets whose resolved config value is empty. The resolved config holds the -// values from --var, BUNDLE_VAR_, defaults, targets and the variable-overrides file alike, so any of -// them supplies a value. Sensitive variables the plan does not use need no value. +// CheckSensitivePlanValues returns one error per resource that stops a saved plan from being applied: +// a sensitive field the plan sets whose config value is empty, or a resource the config no longer has. +// It runs the same restore as InitForApply, so the check and the apply cannot disagree. The config +// holds the values from --var, BUNDLE_VAR_, defaults, targets and the variable-overrides file alike. func CheckSensitivePlanValues(root *config.Root, plan *deployplan.Plan) []error { - var problems []error - seen := make(map[string]bool) - addProblem := func(err error) { - if !seen[err.Error()] { - seen[err.Error()] = true - problems = append(problems, err) - } + _, errs := restoreSavedPlanStates(root, plan, newAdapterForKey) + return errs +} + +// newAdapterForKey returns an adapter for a plan entry without a client, for the checks that run +// before the bundle is initialized for apply. +func newAdapterForKey(resourceKey string) (*dresources.Adapter, error) { + resourceType := config.GetResourceTypeFromKey(resourceKey) + typedNil, ok := dresources.SupportedResources[resourceType] + if !ok { + return nil, fmt.Errorf("unknown resource type %q", resourceType) } + return dresources.NewAdapter(typedNil, resourceType, nil) +} +// restoreSavedPlanStates returns the typed state that apply deploys for each plan entry with a new +// state, with the sensitive fields the plan redacted restored from root. Every problem is returned, one +// per resource. +func restoreSavedPlanStates(root *config.Root, plan *deployplan.Plan, adapterFor func(string) (*dresources.Adapter, error)) (map[string]*structvar.StructVar, []error) { + states := make(map[string]*structvar.StructVar) + var errs []error for _, resourceKey := range slices.Sorted(maps.Keys(plan.Plan)) { entry := plan.Plan[resourceKey] - if entry.NewState == nil { - continue - } - resourceType := config.GetResourceTypeFromKey(resourceKey) - typedNil, ok := dresources.SupportedResources[resourceType] - if !ok { - addProblem(fmt.Errorf("resource %s: unknown resource type", resourceKey)) - continue - } - rules := dresources.SensitiveFieldRules(resourceType) - if len(rules) == 0 { + if entry.NewState == nil || len(entry.NewState.Value) == 0 { continue } - adapter, err := dresources.NewAdapter(typedNil, resourceType, nil) + adapter, err := adapterFor(resourceKey) if err != nil { - addProblem(fmt.Errorf("resource %s: %w", resourceKey, err)) + errs = append(errs, fmt.Errorf("converting plan entry %s: %w", resourceKey, err)) continue } sv, err := entry.NewState.ToStructVar(adapter.StateType()) if err != nil { - addProblem(fmt.Errorf("resource %s: %w", resourceKey, err)) + errs = append(errs, fmt.Errorf("loading plan entry %s: %w", resourceKey, err)) continue } - paths, err := sensitivePaths(rules) - if err != nil { - addProblem(fmt.Errorf("resource %s: %w", resourceKey, err)) + if err := restoreSensitiveFields(adapter, resourceKey, sv, root); err != nil { + errs = append(errs, err) continue } - for _, path := range paths { - planned, err := structaccess.Get(sv.Value, path) - if err != nil { - continue - } - if _, err := sensitiveConfigValue(root, resourceKey, path, planned); err != nil { - addProblem(err) - } - } + states[resourceKey] = sv } - return problems + return states, errs } // InitForApply initializes the DeploymentBundle for applying a pre-computed plan. The sensitive @@ -137,36 +130,26 @@ func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks. return err } - // Eagerly parse plan entries loaded from JSON: - // - NewState.Value contains raw JSON bytes; parse into typed structs and cache. + states, errs := restoreSavedPlanStates(root, plan, b.getAdapterForKey) + if len(errs) > 0 { + return errors.Join(errs...) + } + for resourceKey, sv := range states { + b.StateCache.Store(resourceKey, sv) + } + + // Eagerly parse remote state loaded from JSON: // - RemoteState is decoded as map[string]interface{}; round-trip through the // adapter's StateType to recover the correct typed struct so that type // assertions in resource adapters (e.g. entry.RemoteState.(*GrantsState)) // work identically whether the plan came from a file or from memory. for resourceKey, entry := range plan.Plan { - hasNewState := entry.NewState != nil && len(entry.NewState.Value) > 0 - hasRemoteState := entry.RemoteState != nil - if !hasNewState && !hasRemoteState { - continue - } - - adapter, err := b.getAdapterForKey(resourceKey) - if err != nil { - return fmt.Errorf("converting plan entry %s: %w", resourceKey, err) - } - - if hasNewState { - sv, err := entry.NewState.ToStructVar(adapter.StateType()) + if entry.RemoteState != nil { + adapter, err := b.getAdapterForKey(resourceKey) if err != nil { - return fmt.Errorf("loading plan entry %s: %w", resourceKey, err) - } - if err := restoreSensitiveFields(adapter, resourceKey, sv.Value, root); err != nil { - return err + return fmt.Errorf("converting plan entry %s: %w", resourceKey, err) } - b.StateCache.Store(resourceKey, sv) - } - if hasRemoteState { data, err := json.Marshal(entry.RemoteState) if err != nil { return fmt.Errorf("re-serializing remote state for %s: %w", resourceKey, err) @@ -1599,8 +1582,9 @@ func (b *DeploymentBundle) resolveReferences(ctx context.Context, resourceKey st } } - // Sync resolved values back to StructVarJSON for serialization - if resolved { + // Sync resolved values back to StructVarJSON for serialization. Only planning serializes: after + // apply the plan entries stay redacted, so the plaintext of the cache is not written back into them. + if resolved && isPreDeploy { if err := sv.SyncToJSON(entry.NewState); err != nil { logdiag.LogError(ctx, fmt.Errorf("%s: cannot save state: %w", errorPrefix, err)) return false diff --git a/bundle/direct/dresources/redact_config.go b/bundle/direct/dresources/redact_config.go index faa89f3c60f..ec02895d3fb 100644 --- a/bundle/direct/dresources/redact_config.go +++ b/bundle/direct/dresources/redact_config.go @@ -61,11 +61,6 @@ func redactSensitiveVariables(root *config.Root) { } } -// SensitiveFieldRules returns the sensitive fields of a resource type without building its adapter. -func SensitiveFieldRules(resourceType string) []FieldRule { - return getSensitiveFields()[resourceType] -} - // getSensitiveFields returns the map of resource type to list of sensitive fields. func getSensitiveFields() map[string][]FieldRule { cfg := MustLoadConfig() diff --git a/bundle/direct/redact.go b/bundle/direct/redact.go index 9a14b5fd746..d53b9d3ceef 100644 --- a/bundle/direct/redact.go +++ b/bundle/direct/redact.go @@ -2,13 +2,16 @@ package direct import ( "fmt" + "maps" "slices" "github.com/databricks/cli/bundle/config" "github.com/databricks/cli/bundle/deployplan" "github.com/databricks/cli/bundle/direct/dresources" + "github.com/databricks/cli/libs/dyn/dynvar" "github.com/databricks/cli/libs/structs/structaccess" "github.com/databricks/cli/libs/structs/structpath" + "github.com/databricks/cli/libs/structs/structvar" ) const sensitiveRedactedValue = "[redacted]" @@ -90,8 +93,8 @@ func redactChanges(adapter *dresources.Adapter, changes deployplan.Changes) erro } // redactPlanEntry redacts new_state, remote_state and changes of a plan entry. It runs once planning -// is done: reference resolution re-serializes new_state from the unredacted cache, and apply reads -// that cache, so the plan must not be serialized after this. +// is done: the plan must not be serialized before this, and apply reads the unredacted cache, not +// new_state, so nothing after this point re-serializes the values into the entry. func redactPlanEntry(adapter *dresources.Adapter, entry *deployplan.PlanEntry) error { if len(adapter.GetSensitiveFields()) == 0 { return nil @@ -127,52 +130,95 @@ func redactPlanEntry(adapter *dresources.Adapter, entry *deployplan.PlanEntry) e return nil } -// sensitiveConfigValue returns the value the config sets for a sensitive field, which a deploy sends. -// The config value is used whenever it is set. An empty config value is an error only when the plan -// holds the field non-zero, since the plan then expects a value the config cannot supply. A field -// that is zero in both is output-only and yields "". -func sensitiveConfigValue(root *config.Root, resourceKey string, path *structpath.PathNode, planned any) (string, error) { - rc, err := root.GetResourceConfig(resourceKey) +// restoreSensitiveFields restores the sensitive fields of a saved plan's state, planned, from the +// config. The values are built the way makePlan builds them, so a deploy from the plan sends what a +// plain deploy sends: a reference stays in the refs and is resolved at apply, and an escaped "$${...}" +// is sent as the literal "${...}". A field the plan holds non-zero must have a config value. +func restoreSensitiveFields(adapter *dresources.Adapter, resourceKey string, planned *structvar.StructVar, root *config.Root) error { + rules := dresources.GetResourceConfig(config.GetResourceTypeFromKey(resourceKey)).SensitiveFields + if len(rules) == 0 { + return nil + } + paths, err := sensitivePaths(rules) + if err != nil { + return err + } + + // Each resource is looked up once, so a missing one is reported once rather than once per field. + inputConfig, err := root.GetResourceConfig(resourceKey) if err != nil { - return "", err + return err } - var value string - if rc != nil { - if v, err := structaccess.Get(rc, path); err == nil { - value, _ = v.(string) + if inputConfig == nil { + for _, path := range paths { + if v, err := structaccess.Get(planned.Value, path); err == nil && !isZeroValue(v) { + return fmt.Errorf("resource %s is not in the config; run 'bundle plan' again", resourceKey) + } } + return nil } - if value != "" || planned == nil || planned == "" { - return value, nil + + inputStructVar, err := adapter.PrepareInputConfig(inputConfig, resourceKey) + if err != nil { + return fmt.Errorf("resource %s: %w", resourceKey, err) } - if rc == nil { - return "", fmt.Errorf("resource %s is not in the config; run 'bundle plan' again", resourceKey) + built, err := adapter.PrepareState(inputStructVar.Value) + if err != nil { + return fmt.Errorf("resource %s: %w", resourceKey, err) } - return "", fmt.Errorf("resource %s: the config has no value for sensitive field %s; set the variable it uses with --var or BUNDLE_VAR_", resourceKey, path) -} -// restoreSensitiveFields replaces the sensitive values in s, a saved plan's state, with the values -// the current config sets. CheckSensitivePlanValues runs the same rule before the plan is approved. -func restoreSensitiveFields(adapter *dresources.Adapter, resourceKey string, s any, root *config.Root) error { - paths, err := sensitivePaths(adapter.ResourceConfig().SensitiveFields) + // The references are the same ones makePlan records for the resource. + refs, err := extractReferences(root.Value(), resourceKey, adapter.StateType()) if err != nil { - return err + return fmt.Errorf("resource %s: reading references: %w", resourceKey, err) } + maps.Copy(refs, inputStructVar.Refs) + + // Checked before unescaping: an escaped "$${...}" is a literal, but an unescaped reference + // without a recorded ref would be sent as it is. for _, path := range paths { - planned, err := structaccess.Get(s, path) + raw, err := structaccess.Get(built, path) if err != nil { continue } - value, err := sensitiveConfigValue(root, resourceKey, path, planned) + if s, _ := raw.(string); dynvar.ContainsVariableReference(s) && refs[path.String()] == "" { + return fmt.Errorf("resource %s: sensitive field %s holds an unresolved reference %q", resourceKey, path, s) + } + } + + if err := unescapeRefs(built); err != nil { + return fmt.Errorf("resource %s: %w", resourceKey, err) + } + + for _, path := range paths { + v, err := structaccess.Get(built, path) if err != nil { - return err + continue + } + value, _ := v.(string) + plannedValue, err := structaccess.Get(planned.Value, path) + if err != nil { + continue } if value == "" { + if !isZeroValue(plannedValue) { + return fmt.Errorf("resource %s: the config has no value for sensitive field %s; set the variable it uses with --var or BUNDLE_VAR_", resourceKey, path) + } continue } - if err := structaccess.Set(s, path, value); err != nil { + if err := structaccess.Set(planned.Value, path, value); err != nil { return fmt.Errorf("resource %s: restoring sensitive field %s: %w", resourceKey, path, err) } + if ref, ok := refs[path.String()]; ok { + if planned.Refs == nil { + planned.Refs = make(map[string]string) + } + planned.Refs[path.String()] = ref + } } return nil } + +func isZeroValue(v any) bool { + return v == nil || v == "" +} diff --git a/bundle/direct/redact_test.go b/bundle/direct/redact_test.go index 8081387392c..3a3aa3faaae 100644 --- a/bundle/direct/redact_test.go +++ b/bundle/direct/redact_test.go @@ -1,6 +1,7 @@ package direct import ( + "context" "encoding/json" "testing" @@ -10,10 +11,8 @@ import ( "github.com/databricks/cli/bundle/deployplan" "github.com/databricks/cli/bundle/direct/dresources" "github.com/databricks/cli/libs/dyn" - "github.com/databricks/cli/libs/structs/structpath" "github.com/databricks/cli/libs/structs/structvar" "github.com/databricks/databricks-sdk-go/service/catalog" - "github.com/databricks/databricks-sdk-go/service/jobs" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -96,90 +95,98 @@ const ( msgNotInConfig = "resource resources.secrets.gone is not in the config; run 'bundle plan' again" ) +// TestRestoreSensitiveFields checks the value a saved plan's sensitive field is restored to: what a +// plain deploy sends from the same config. A reference is kept for apply to resolve, and an escaped +// reference is sent as the literal it escapes. func TestRestoreSensitiveFields(t *testing.T) { adapter := secretAdapter(t) tests := []struct { name string resourceKey string - state *catalog.Secret + planned string configValue string wantValue string + wantRefs map[string]string wantErr string }{ { name: "redaction marker is replaced by the config value", resourceKey: "resources.secrets.s", - state: &catalog.Secret{Name: "s", Value: sensitiveRedactedValue}, + planned: sensitiveRedactedValue, configValue: secretLiteral, wantValue: secretLiteral, }, { name: "plaintext from a plan saved by an older CLI is replaced by the config value", resourceKey: "resources.secrets.s", - state: &catalog.Secret{Name: "s", Value: "stale-plaintext"}, + planned: "stale-plaintext", configValue: secretLiteral, wantValue: secretLiteral, }, { name: "zero in the plan but set in the config is restored", resourceKey: "resources.secrets.s", - state: &catalog.Secret{Name: "s"}, + planned: "", configValue: secretLiteral, wantValue: secretLiteral, }, { name: "zero in both is skipped", resourceKey: "resources.secrets.s", - state: &catalog.Secret{Name: "s"}, + planned: "", configValue: "", wantValue: "", }, { name: "non-zero in the plan with an empty config value is an error", resourceKey: "resources.secrets.s", - state: &catalog.Secret{Name: "s", Value: sensitiveRedactedValue}, + planned: sensitiveRedactedValue, configValue: "", wantErr: msgValueMissing, }, { name: "non-zero in the plan with the resource missing from config is an error", resourceKey: "resources.secrets.gone", - state: &catalog.Secret{Name: "s", Value: sensitiveRedactedValue}, + planned: sensitiveRedactedValue, configValue: secretLiteral, wantErr: msgNotInConfig, }, + { + name: "a reference in the config is kept for apply to resolve", + resourceKey: "resources.secrets.s", + planned: sensitiveRedactedValue, + configValue: "${resources.catalogs.c.name}", + wantValue: "${resources.catalogs.c.name}", + wantRefs: map[string]string{"value": "${resources.catalogs.c.name}"}, + }, + { + name: "an escaped reference is sent as the literal it escapes", + resourceKey: "resources.secrets.s", + planned: sensitiveRedactedValue, + configValue: "pre-$${x}", + wantValue: "pre-${x}", + }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { root := secretRoot(t, tc.configValue, nil) - err := restoreSensitiveFields(adapter, tc.resourceKey, tc.state, root) + planned := &structvar.StructVar{Value: &catalog.Secret{Name: "s", Value: tc.planned}} + err := restoreSensitiveFields(adapter, tc.resourceKey, planned, root) if tc.wantErr != "" { assert.EqualError(t, err, tc.wantErr) return } require.NoError(t, err) - assert.Equal(t, tc.wantValue, tc.state.Value) - assert.Empty(t, tc.state.EffectiveValue) + secret := planned.Value.(*catalog.Secret) + assert.Equal(t, tc.wantValue, secret.Value) + assert.Empty(t, secret.EffectiveValue) + assert.Equal(t, tc.wantRefs, planned.Refs) }) } } -// TestSensitiveConfigValueNestedField checks that a dotted sensitive field path is read from the -// resource config, not only a top-level field. -func TestSensitiveConfigValueNestedField(t *testing.T) { - root := syncedRoot(t, &config.Root{Resources: config.Resources{Jobs: map[string]*resources.Job{ - "j": {JobSettings: jobs.JobSettings{Schedule: &jobs.CronSchedule{QuartzCronExpression: "0 0 * * *"}}}, - }}}) - path, err := structpath.ParsePath("schedule.quartz_cron_expression") - require.NoError(t, err) - - value, err := sensitiveConfigValue(root, "resources.jobs.j", path, "planned") - require.NoError(t, err) - assert.Equal(t, "0 0 * * *", value) -} - func TestCheckSensitivePlanValues(t *testing.T) { sensitive := true variables := map[string]*variable.Variable{ @@ -238,9 +245,9 @@ func TestCheckSensitivePlanValues(t *testing.T) { } } -// TestCheckSensitivePlanValuesOneErrorPerProblem checks that each resource with a missing value gets its -// own error, and that a resource missing from the config is reported once, not once per sensitive field. -func TestCheckSensitivePlanValuesOneErrorPerProblem(t *testing.T) { +// TestCheckSensitivePlanValuesOneErrorPerResource checks that each resource with a missing value gets its +// own error, and that a resource missing from the config is reported once. +func TestCheckSensitivePlanValuesOneErrorPerResource(t *testing.T) { root := syncedRoot(t, &config.Root{Resources: config.Resources{ Secrets: map[string]*resources.Secret{ "a": {Secret: catalog.Secret{Name: "a"}}, @@ -259,3 +266,25 @@ func TestCheckSensitivePlanValuesOneErrorPerProblem(t *testing.T) { assert.EqualError(t, errs[1], "resource resources.secrets.b: the config has no value for sensitive field value; set the variable it uses with --var or BUNDLE_VAR_") assert.EqualError(t, errs[2], msgNotInConfig) } + +// TestResolveReferencesAfterApplyKeepsRedactedEntry checks that apply resolving a reference does not write +// the resolved value back into the plan entry, which would put the secret back into memory after redaction. +func TestResolveReferencesAfterApplyKeepsRedactedEntry(t *testing.T) { + b := &DeploymentBundle{Plan: deployplan.NewPlanDirect()} + b.Plan.Plan["resources.catalogs.c"] = &deployplan.PlanEntry{Action: deployplan.Skip} + b.RemoteStateCache.Store("resources.catalogs.c", &catalog.CatalogInfo{Name: "resolved-name"}) + + redactedJSON := []byte(`{"name":"s","value":"[redacted]"}`) + entry := &deployplan.PlanEntry{Action: deployplan.Create, NewState: &structvar.StructVarJSON{Value: redactedJSON}} + b.StateCache.Store("resources.secrets.s", &structvar.StructVar{ + Value: &catalog.Secret{Name: "s"}, + Refs: map[string]string{"value": "${resources.catalogs.c.name}"}, + }) + + require.True(t, b.resolveReferences(context.Background(), "resources.secrets.s", entry, "cannot create", false)) + + sv, ok := b.StateCache.Load("resources.secrets.s") + require.True(t, ok) + assert.Equal(t, "resolved-name", sv.Value.(*catalog.Secret).Value) + assert.JSONEq(t, string(redactedJSON), string(entry.NewState.Value)) +} From b1927a2cd0f276a91d8a2a2a8cf5c33e093a241a Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Sat, 28 Nov 2026 09:29:22 +0000 Subject: [PATCH 10/17] Use t.Context in the apply reference test Co-authored-by: Isaac --- bundle/direct/redact_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bundle/direct/redact_test.go b/bundle/direct/redact_test.go index 3a3aa3faaae..ad9aef6824f 100644 --- a/bundle/direct/redact_test.go +++ b/bundle/direct/redact_test.go @@ -1,7 +1,6 @@ package direct import ( - "context" "encoding/json" "testing" @@ -281,7 +280,7 @@ func TestResolveReferencesAfterApplyKeepsRedactedEntry(t *testing.T) { Refs: map[string]string{"value": "${resources.catalogs.c.name}"}, }) - require.True(t, b.resolveReferences(context.Background(), "resources.secrets.s", entry, "cannot create", false)) + require.True(t, b.resolveReferences(t.Context(), "resources.secrets.s", entry, "cannot create", false)) sv, ok := b.StateCache.Load("resources.secrets.s") require.True(t, ok) From 3637e1129d6b49bb3018a19ac7bc7564b0382456 Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Sat, 28 Nov 2026 19:36:06 +0000 Subject: [PATCH 11/17] Bump the saved plan version to 3 for redacted secrets A plan from this CLI carries redacted secret values that only a CLI restoring them from the config can apply. Version 3 makes released CLIs refuse these plans, instead of applying the redaction marker as the secret. Version 2 plans stay readable: restore replaces their sensitive fields from the config. Co-authored-by: Isaac --- .nextchanges/bundles/7713.md | 2 +- .../readplan/plan-version-2/databricks.yml | 7 ++++ .../readplan/plan-version-2/out.test.toml | 2 ++ .../deploy/readplan/plan-version-2/output.txt | 35 +++++++++++++++++++ .../deploy/readplan/plan-version-2/script | 6 ++++ .../deploy/readplan/plan-version-2/test.toml | 2 ++ .../readplan/plan-version-mismatch/output.txt | 2 +- acceptance/test.toml | 11 +++++- bundle/deployplan/plan.go | 10 ++++-- 9 files changed, 72 insertions(+), 5 deletions(-) create mode 100644 acceptance/bundle/deploy/readplan/plan-version-2/databricks.yml create mode 100644 acceptance/bundle/deploy/readplan/plan-version-2/out.test.toml create mode 100644 acceptance/bundle/deploy/readplan/plan-version-2/output.txt create mode 100644 acceptance/bundle/deploy/readplan/plan-version-2/script create mode 100644 acceptance/bundle/deploy/readplan/plan-version-2/test.toml diff --git a/.nextchanges/bundles/7713.md b/.nextchanges/bundles/7713.md index 9523789148b..e941ac34630 100644 --- a/.nextchanges/bundles/7713.md +++ b/.nextchanges/bundles/7713.md @@ -1 +1 @@ -* `bundle plan` no longer shows or saves sensitive variable values, and `bundle deploy --plan` requires them to be supplied again at deploy time (for example with `--var` or `BUNDLE_VAR_`). ([#7713](https://github.com/databricks/cli/pull/7713)) +* `bundle plan` no longer shows or saves sensitive variable values, and `bundle deploy --plan` requires them to be supplied again at deploy time (for example with `--var` or `BUNDLE_VAR_`). Saved plans now use plan version 3, so older CLI versions refuse them, because they cannot restore the redacted values. ([#7713](https://github.com/databricks/cli/pull/7713)) diff --git a/acceptance/bundle/deploy/readplan/plan-version-2/databricks.yml b/acceptance/bundle/deploy/readplan/plan-version-2/databricks.yml new file mode 100644 index 00000000000..b93d6b5b021 --- /dev/null +++ b/acceptance/bundle/deploy/readplan/plan-version-2/databricks.yml @@ -0,0 +1,7 @@ +bundle: + name: test-bundle + +resources: + jobs: + job: + name: test-job diff --git a/acceptance/bundle/deploy/readplan/plan-version-2/out.test.toml b/acceptance/bundle/deploy/readplan/plan-version-2/out.test.toml new file mode 100644 index 00000000000..a927a5fbc06 --- /dev/null +++ b/acceptance/bundle/deploy/readplan/plan-version-2/out.test.toml @@ -0,0 +1,2 @@ +Cloud = false +EnvMatrix.DMS = ["", "true"] diff --git a/acceptance/bundle/deploy/readplan/plan-version-2/output.txt b/acceptance/bundle/deploy/readplan/plan-version-2/output.txt new file mode 100644 index 00000000000..1b06f045475 --- /dev/null +++ b/acceptance/bundle/deploy/readplan/plan-version-2/output.txt @@ -0,0 +1,35 @@ + +>>> [CLI] bundle plan -o json + +>>> [CLI] bundle deploy --plan tmp.plan_v2.json +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/files... +Created jobs.job +Files: 2 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --get //jobs +{ + "method": "POST", + "path": "/api/2.2/jobs/create", + "body": { + "deployment": { + "kind": "BUNDLE", + "metadata_file_path": "/Workspace/Users/[USERNAME]/.bundle/test-bundle/default/state/metadata.json" + }, + "edit_mode": "UI_LOCKED", + "format": "MULTI_TASK", + "max_concurrent_runs": 1, + "name": "test-job", + "queue": { + "enabled": true + } + } +} + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.job + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/test-bundle/default + +Destroy: 1 deleted diff --git a/acceptance/bundle/deploy/readplan/plan-version-2/script b/acceptance/bundle/deploy/readplan/plan-version-2/script new file mode 100644 index 00000000000..eb8d44051c3 --- /dev/null +++ b/acceptance/bundle/deploy/readplan/plan-version-2/script @@ -0,0 +1,6 @@ +# A plan saved by an older CLI has plan version 2. It still loads, and the deploy applies it. +trace $CLI bundle plan -o json | jq '.plan_version = 2' > tmp.plan_v2.json +trace $CLI bundle deploy --plan tmp.plan_v2.json +trace print_requests.py --get //jobs | nostamp | contains.py "POST" + +trace $CLI bundle destroy --auto-approve diff --git a/acceptance/bundle/deploy/readplan/plan-version-2/test.toml b/acceptance/bundle/deploy/readplan/plan-version-2/test.toml new file mode 100644 index 00000000000..e0ad86991a3 --- /dev/null +++ b/acceptance/bundle/deploy/readplan/plan-version-2/test.toml @@ -0,0 +1,2 @@ +RecordRequests = true +Ignore = ["tmp.plan_*.json"] diff --git a/acceptance/bundle/deploy/readplan/plan-version-mismatch/output.txt b/acceptance/bundle/deploy/readplan/plan-version-mismatch/output.txt index 387aac2335c..3ec4497a23e 100644 --- a/acceptance/bundle/deploy/readplan/plan-version-mismatch/output.txt +++ b/acceptance/bundle/deploy/readplan/plan-version-mismatch/output.txt @@ -1,4 +1,4 @@ -Error: plan version mismatch: plan has version 999 (generated with CLI "0.0.0"), but current version is 2 +Error: plan version mismatch: plan has version 999 (generated with CLI "0.0.0"), but current version is 3 Exit code: 1 diff --git a/acceptance/test.toml b/acceptance/test.toml index 390812795a6..f183bfb66b9 100644 --- a/acceptance/test.toml +++ b/acceptance/test.toml @@ -76,15 +76,24 @@ Order = 9 Old = "deco-uc-prod-isolated-aws-us-east-1|metastore_azure_eastus2" New = "[METASTORE_NAME]" -# Normalize plan_version so bumping it doesn't churn every recorded plan. +# Normalize plan_version so bumping it doesn't churn every recorded plan. Version 2 is normalized too, +# since a plan saved by an older CLI is still readable. [[Repls]] Old = '"plan_version": 2,' New = '"plan_version": [PLAN_VERSION],' +[[Repls]] +Old = '"plan_version": 3,' +New = '"plan_version": [PLAN_VERSION],' + [[Repls]] Old = 'json\.plan_version = 2;' New = 'json.plan_version = [PLAN_VERSION];' +[[Repls]] +Old = 'json\.plan_version = 3;' +New = 'json.plan_version = [PLAN_VERSION];' + # The lineage hash (libs/shortid) is not masked: fixture lineages hash to stable values, and # tests with a freshly minted lineage register its hash with read_lineage.py. diff --git a/bundle/deployplan/plan.go b/bundle/deployplan/plan.go index 6fcaa333e08..f3c2c15c516 100644 --- a/bundle/deployplan/plan.go +++ b/bundle/deployplan/plan.go @@ -18,7 +18,13 @@ import ( "github.com/databricks/cli/libs/structs/structvar" ) -const currentPlanVersion = 2 +// currentPlanVersion is the version of plans this CLI writes. Version 3 carries redacted secrets, which +// only a CLI that restores them from the config can apply, so older CLIs refuse it. +const currentPlanVersion = 3 + +// oldestReadablePlanVersion is the oldest plan version still loaded. Its plans may hold plaintext +// secrets, which apply replaces with the values from the config. +const oldestReadablePlanVersion = 2 type Plan struct { PlanVersion int `json:"plan_version,omitempty"` @@ -111,7 +117,7 @@ func LoadPlanFromFile(path string) (*Plan, error) { } // Validate plan version - if plan.PlanVersion != currentPlanVersion { + if plan.PlanVersion < oldestReadablePlanVersion || plan.PlanVersion > currentPlanVersion { return nil, fmt.Errorf("plan version mismatch: plan has version %d (generated with CLI %q), but current version is %d", plan.PlanVersion, plan.CLIVersion, currentPlanVersion) } From 062e1445a1e6897dce4c5dd731af35ca76be0bea Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Sun, 29 Nov 2026 10:25:35 +0000 Subject: [PATCH 12/17] Restore saved plan references as planning resolves them A sensitive field whose reference changed between bundle plan and deploy --plan got the plan's reference back, so apply overwrote the literal from the config. A reference to a resource the plan does not depend on was applied without ordering, and failed mid-apply. The restore now builds the value with buildPlannedState, which is the build makePlan uses. It keeps the references the config has, and drops the plan's when the config has none. A reference to a resource the plan does not depend on is an error that asks for bundle plan again. References that planning resolves before deploy are resolved the same way; the rest are left for apply. The plan no longer carries the references of sensitive fields, so a template such as a secret followed by a reference no longer shows in the saved plan. Co-authored-by: Isaac --- .../readplan/plan-version-2/databricks.yml | 11 ++ .../deploy/readplan/plan-version-2/output.txt | 18 +- .../deploy/readplan/plan-version-2/script | 6 +- .../deploy/readplan/plan-version-2/test.toml | 1 + .../sensitive/plan-restore/output.txt | 78 +++++++++ .../variables/sensitive/plan-restore/script | 83 +++++++++ bundle/direct/bundle_plan.go | 110 +++++++----- bundle/direct/redact.go | 158 +++++++++++++----- bundle/direct/redact_test.go | 53 +++++- 9 files changed, 430 insertions(+), 88 deletions(-) diff --git a/acceptance/bundle/deploy/readplan/plan-version-2/databricks.yml b/acceptance/bundle/deploy/readplan/plan-version-2/databricks.yml index b93d6b5b021..35405bf99d9 100644 --- a/acceptance/bundle/deploy/readplan/plan-version-2/databricks.yml +++ b/acceptance/bundle/deploy/readplan/plan-version-2/databricks.yml @@ -1,7 +1,18 @@ bundle: name: test-bundle +variables: + api_secret: + description: Sensitive value supplied with BUNDLE_VAR_api_secret. + sensitive: true + resources: jobs: job: name: test-job + secrets: + secret: + name: test-secret + catalog_name: main + schema_name: default + value: ${var.api_secret} diff --git a/acceptance/bundle/deploy/readplan/plan-version-2/output.txt b/acceptance/bundle/deploy/readplan/plan-version-2/output.txt index 1b06f045475..21cad6f082b 100644 --- a/acceptance/bundle/deploy/readplan/plan-version-2/output.txt +++ b/acceptance/bundle/deploy/readplan/plan-version-2/output.txt @@ -4,8 +4,21 @@ >>> [CLI] bundle deploy --plan tmp.plan_v2.json Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/files... Created jobs.job +Created secrets.secret Files: 2 uploaded, 0 deleted -Resources: 1 created, 0 changed, 0 deleted, 0 unchanged +Resources: 2 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --keep //unity-catalog/secrets +{ + "method": "POST", + "path": "/api/2.1/unity-catalog/secrets", + "body": { + "catalog_name": "main", + "name": "test-secret", + "schema_name": "default", + "value": "dummy-config" + } +} >>> print_requests.py --get //jobs { @@ -29,7 +42,8 @@ Resources: 1 created, 0 changed, 0 deleted, 0 unchanged >>> [CLI] bundle destroy --auto-approve The following resources will be deleted: delete resources.jobs.job + delete resources.secrets.secret All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/test-bundle/default -Destroy: 1 deleted +Destroy: 2 deleted diff --git a/acceptance/bundle/deploy/readplan/plan-version-2/script b/acceptance/bundle/deploy/readplan/plan-version-2/script index eb8d44051c3..6057793b175 100644 --- a/acceptance/bundle/deploy/readplan/plan-version-2/script +++ b/acceptance/bundle/deploy/readplan/plan-version-2/script @@ -1,6 +1,8 @@ -# A plan saved by an older CLI has plan version 2. It still loads, and the deploy applies it. -trace $CLI bundle plan -o json | jq '.plan_version = 2' > tmp.plan_v2.json +# A plan saved by an older CLI has plan version 2. It still loads, and the deploy applies it. The secret's +# value is stored as plaintext in the old plan, which must not win over the value in the config. +trace $CLI bundle plan -o json | jq '.plan_version = 2 | .plan["resources.secrets.secret"].new_state.value.value = "stale-plaintext"' > tmp.plan_v2.json trace $CLI bundle deploy --plan tmp.plan_v2.json +trace print_requests.py --keep //unity-catalog/secrets trace print_requests.py --get //jobs | nostamp | contains.py "POST" trace $CLI bundle destroy --auto-approve diff --git a/acceptance/bundle/deploy/readplan/plan-version-2/test.toml b/acceptance/bundle/deploy/readplan/plan-version-2/test.toml index e0ad86991a3..89bd91b52e6 100644 --- a/acceptance/bundle/deploy/readplan/plan-version-2/test.toml +++ b/acceptance/bundle/deploy/readplan/plan-version-2/test.toml @@ -1,2 +1,3 @@ RecordRequests = true Ignore = ["tmp.plan_*.json"] +Env.BUNDLE_VAR_api_secret = "dummy-config" diff --git a/acceptance/bundle/variables/sensitive/plan-restore/output.txt b/acceptance/bundle/variables/sensitive/plan-restore/output.txt index c0350a07e47..bafab7f46ae 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/output.txt +++ b/acceptance/bundle/variables/sensitive/plan-restore/output.txt @@ -59,3 +59,81 @@ Resources: 3 created, 0 changed, 0 deleted, 0 unchanged === create requests of the plain deploy and the saved plan match {"name":"escaped_secret","value":"escaped-${x}"} {"name":"ref_secret","value":"dummy-catalog-name"} + +=== a reference that becomes a literal after planning: the literal is sent + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.catalogs.source_catalog + delete resources.secrets.escaped_secret + delete resources.secrets.ref_secret + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 3 deleted + +>>> jq -S .plan["resources.secrets.ref_secret"].new_state .databricks/plan-ref.json +{ + "value": { + "catalog_name": "main", + "name": "ref_secret", + "schema_name": "default", + "value": "[redacted]" + } +} + +>>> [CLI] bundle deploy --plan .databricks/plan-ref.json +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created catalogs.source_catalog +Created secrets.escaped_secret +Created secrets.ref_secret +Files: 1 uploaded, 0 deleted +Resources: 3 created, 0 changed, 0 deleted, 0 unchanged + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.catalogs.source_catalog + delete resources.secrets.escaped_secret + delete resources.secrets.ref_secret + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 3 deleted + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created catalogs.source_catalog +Created secrets.escaped_secret +Created secrets.ref_secret +Files: 1 uploaded, 0 deleted +Resources: 3 created, 0 changed, 0 deleted, 0 unchanged +{"name":"escaped_secret","value":"escaped-${x}"} +{"name":"ref_secret","value":"escaped-${x}"} + +=== a literal that becomes a reference after planning: the saved plan is refused + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.catalogs.source_catalog + delete resources.secrets.escaped_secret + delete resources.secrets.ref_secret + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 3 deleted + +>>> [CLI] bundle deploy --plan .databricks/plan-literal.json +Error: resource resources.secrets.ref_secret: sensitive field value now references resources.catalogs.source_catalog, which the saved plan does not depend on; run 'bundle plan' again + + +=== a sensitive value with an unresolved reference: the plan shows neither the template nor its reference + +>>> env BUNDLE_VAR_api_header=dummy-credential-${resources.catalogs.source_catalog.id} [CLI] bundle plan -o json +{ + "value": { + "catalog_name": "main", + "name": "escaped_secret", + "schema_name": "default", + "value": "[redacted]" + } +} diff --git a/acceptance/bundle/variables/sensitive/plan-restore/script b/acceptance/bundle/variables/sensitive/plan-restore/script index 725200d9cc6..8b95f82d7f6 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/script +++ b/acceptance/bundle/variables/sensitive/plan-restore/script @@ -22,3 +22,86 @@ tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$CREATES" | sort > .databricks/s title "create requests of the plain deploy and the saved plan match" cat .databricks/plain.json diff .databricks/plain.json .databricks/saved.json + +# The config changes between bundle plan and deploy --plan. The plan was made with the reference in +# ref_secret, and the config then has the literal variable value instead. The literal is sent, as a plain +# deploy of the changed config sends it. +cp databricks.yml .databricks/base.yml +cat > .databricks/literal.yml <<'EOF' +bundle: + name: sensitive-variables + +variables: + api_header: + description: Sensitive value supplied with BUNDLE_VAR_api_header, containing an escaped reference. + sensitive: true + +resources: + catalogs: + source_catalog: + name: dummy-catalog-name + secrets: + ref_secret: + name: ref_secret + catalog_name: main + schema_name: default + value: ${var.api_header} + escaped_secret: + name: escaped_secret + catalog_name: main + schema_name: default + value: ${var.api_header} +EOF + +# The id of a catalog that is created in the same deploy is not known at plan time, so the reference stays in +# the plan: it is the case where a changed reference matters. +cat > .databricks/id.yml <<'EOF' +bundle: + name: sensitive-variables + +variables: + api_header: + description: Sensitive value supplied with BUNDLE_VAR_api_header, containing an escaped reference. + sensitive: true + +resources: + catalogs: + source_catalog: + name: dummy-catalog-name + secrets: + ref_secret: + name: ref_secret + catalog_name: main + schema_name: default + value: ${resources.catalogs.source_catalog.id} + escaped_secret: + name: escaped_secret + catalog_name: main + schema_name: default + value: ${var.api_header} +EOF + +title "a reference that becomes a literal after planning: the literal is sent" +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +cp .databricks/id.yml databricks.yml +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan-ref.json +trace jq -S '.plan["resources.secrets.ref_secret"].new_state' .databricks/plan-ref.json +cp .databricks/literal.yml databricks.yml +before=$(wc -l < "$OUT_REQUESTS") +trace $CLI bundle deploy --plan .databricks/plan-ref.json | contains.py "${SECRETS[@]}" +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$CREATES" | sort > .databricks/ref-to-literal-plan.json +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +before=$(wc -l < "$OUT_REQUESTS") +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$CREATES" | sort > .databricks/ref-to-literal-plain.json +diff .databricks/ref-to-literal-plain.json .databricks/ref-to-literal-plan.json +cat .databricks/ref-to-literal-plan.json + +title "a literal that becomes a reference after planning: the saved plan is refused" +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan-literal.json +cp .databricks/base.yml databricks.yml +musterr trace $CLI bundle deploy --plan .databricks/plan-literal.json + +title "a sensitive value with an unresolved reference: the plan shows neither the template nor its reference" +trace env BUNDLE_VAR_api_header='dummy-credential-${resources.catalogs.source_catalog.id}' $CLI bundle plan -o json | contains.py '!dummy-credential' | jq -S '.plan["resources.secrets.escaped_secret"].new_state' diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index 6a9508c0b26..8031c5840a1 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -74,19 +74,13 @@ func ValidatePlanAgainstState(stateDB *dstate.DeploymentState, plan *deployplan. // It runs the same restore as InitForApply, so the check and the apply cannot disagree. The config // holds the values from --var, BUNDLE_VAR_, defaults, targets and the variable-overrides file alike. func CheckSensitivePlanValues(root *config.Root, plan *deployplan.Plan) []error { - _, errs := restoreSavedPlanStates(root, plan, newAdapterForKey) - return errs -} - -// newAdapterForKey returns an adapter for a plan entry without a client, for the checks that run -// before the bundle is initialized for apply. -func newAdapterForKey(resourceKey string) (*dresources.Adapter, error) { - resourceType := config.GetResourceTypeFromKey(resourceKey) - typedNil, ok := dresources.SupportedResources[resourceType] - if !ok { - return nil, fmt.Errorf("unknown resource type %q", resourceType) + adapters, err := dresources.InitAll(nil) + if err != nil { + return []error{err} } - return dresources.NewAdapter(typedNil, resourceType, nil) + b := DeploymentBundle{Adapters: adapters} + _, errs := restoreSavedPlanStates(root, plan, b.getAdapterForKey) + return errs } // restoreSavedPlanStates returns the typed state that apply deploys for each plan entry with a new @@ -110,7 +104,7 @@ func restoreSavedPlanStates(root *config.Root, plan *deployplan.Plan, adapterFor errs = append(errs, fmt.Errorf("loading plan entry %s: %w", resourceKey, err)) continue } - if err := restoreSensitiveFields(adapter, resourceKey, sv, root); err != nil { + if err := restoreSensitiveFields(adapter, resourceKey, entry.DependsOn, sv, root); err != nil { errs = append(errs, err) continue } @@ -137,6 +131,13 @@ func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks. for resourceKey, sv := range states { b.StateCache.Store(resourceKey, sv) } + b.Plan = plan + for _, resourceKey := range slices.Sorted(maps.Keys(states)) { + rules := dresources.GetResourceConfig(config.GetResourceTypeFromKey(resourceKey)).SensitiveFields + if err := b.resolveSensitiveRefs(ctx, rules, states[resourceKey]); err != nil { + return err + } + } // Eagerly parse remote state loaded from JSON: // - RemoteState is decoded as map[string]interface{}; round-trip through the @@ -164,7 +165,6 @@ func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks. } } - b.Plan = plan return nil } @@ -1594,6 +1594,59 @@ func (b *DeploymentBundle) resolveReferences(ctx context.Context, resourceKey st return true } +// buildPlannedState builds the typed state of a resource from its input config, with the references it +// still holds. makePlan and the restore of a saved plan's sensitive fields both call it, so a deploy +// from a saved plan builds the values the same way a plain deploy does. +func buildPlannedState(adapter *dresources.Adapter, resourceKey string, inputConfig any, root *config.Root) (*structvar.StructVar, error) { + inputStructVar, err := adapter.PrepareInputConfig(inputConfig, resourceKey) + if err != nil { + return nil, err + } + + newStateConfig, err := adapter.PrepareState(inputStructVar.Value) + if err != nil { + return nil, err + } + + // Note, we're extracting references in input config but resolving them in newState.Config which is PrepareState(inputConfig) + // This means input and state must be compatible: input can have more fields, but existing fields should not be moved + // This means one cannot refer to fields not present in state (e.g. ${resources.jobs.foo.permissions}) + refs, err := extractReferences(root.Value(), resourceKey, adapter.StateType()) + if err != nil { + return nil, fmt.Errorf("failed to read references from config for %s: %w", resourceKey, err) + } + maps.Copy(refs, inputStructVar.Refs) + + // A sensitive field is checked before unescaping. An escaped "$${...}" is a literal, but an + // unescaped reference without a recorded ref would be sent as it is. The value is left out of + // the message, since it may be a secret. + paths, err := sensitivePaths(adapter.ResourceConfig().SensitiveFields) + if err != nil { + return nil, err + } + for _, path := range paths { + raw, err := structaccess.Get(newStateConfig, path) + if err != nil { + continue + } + if s, _ := raw.(string); dynvar.ContainsVariableReference(s) && refs[path.String()] == "" { + return nil, fmt.Errorf("sensitive field %s of %s holds a reference that is not resolved", path, resourceKey) + } + } + + // Unescape "$${...}" to a literal "${...}" in the typed state, which is what + // gets deployed and saved. + // + // This runs on the typed state rather than the dynamic config so that + // extractReferences above still sees the escaped form and does not mistake + // these placeholders for bundle references. + if err := unescapeRefs(newStateConfig); err != nil { + return nil, err + } + + return &structvar.StructVar{Value: newStateConfig, Refs: refs}, nil +} + func (b *DeploymentBundle) makePlan(ctx context.Context, configRoot *config.Root, db *dstate.Database) (*deployplan.Plan, error) { p := deployplan.NewPlanDirect() @@ -1654,25 +1707,11 @@ func (b *DeploymentBundle) makePlan(ctx context.Context, configRoot *config.Root return nil, fmt.Errorf("%s: %w", prefix, err) } - inputStructVar, err := adapter.PrepareInputConfig(inputConfig, node) - if err != nil { - return nil, fmt.Errorf("%s: %w", prefix, err) - } - - newStateConfig, err := adapter.PrepareState(inputStructVar.Value) + state, err := buildPlannedState(adapter, node, inputConfig, configRoot) if err != nil { return nil, fmt.Errorf("%s: %w", prefix, err) } - - // Unescape "$${...}" to a literal "${...}" in the typed state, which is what - // gets deployed and saved. - // - // This runs on the typed state rather than the dynamic config so that - // extractReferences below still sees the escaped form and does not mistake - // these placeholders for bundle references. - if err := unescapeRefs(newStateConfig); err != nil { - return nil, fmt.Errorf("%s: %w", prefix, err) - } + newStateConfig := state.Value // New nodes only: a node with state must stay in the plan, otherwise emptying it plans nothing. // Apply drops the state entry once the node is empty, so it is skipped from then on. @@ -1686,16 +1725,7 @@ func (b *DeploymentBundle) makePlan(ctx context.Context, configRoot *config.Root } } - // Note, we're extracting references in input config but resolving them in newState.Config which is PrepareState(inputConfig) - // This means input and state must be compatible: input can have more fields, but existing fields should not be moved - // This means one cannot refer to fields not present in state (e.g. ${resources.jobs.foo.permissions}) - - refs, err := extractReferences(configRoot.Value(), node, adapter.StateType()) - if err != nil { - return nil, fmt.Errorf("failed to read references from config for %s: %w", node, err) - } - - maps.Copy(refs, inputStructVar.Refs) + refs := state.Refs var dependsOn []deployplan.DependsOnEntry for _, reference := range refs { diff --git a/bundle/direct/redact.go b/bundle/direct/redact.go index d53b9d3ceef..6d64fba31af 100644 --- a/bundle/direct/redact.go +++ b/bundle/direct/redact.go @@ -1,6 +1,7 @@ package direct import ( + "context" "fmt" "maps" "slices" @@ -8,6 +9,7 @@ import ( "github.com/databricks/cli/bundle/config" "github.com/databricks/cli/bundle/deployplan" "github.com/databricks/cli/bundle/direct/dresources" + "github.com/databricks/cli/libs/dyn" "github.com/databricks/cli/libs/dyn/dynvar" "github.com/databricks/cli/libs/structs/structaccess" "github.com/databricks/cli/libs/structs/structpath" @@ -30,6 +32,16 @@ func sensitivePaths(rules []dresources.FieldRule) ([]*structpath.PathNode, error return paths, nil } +// isSensitivePath reports whether path is a field, or inside a field, that the rules mark as sensitive. +func isSensitivePath(rules []dresources.FieldRule, path *structpath.PathNode) bool { + for _, rule := range rules { + if path.HasPatternPrefix(rule.Field) { + return true + } + } + return false +} + // redactSensitiveFields replaces (or zeros) scalar fields in s (a pointer to a typed struct) // that the adapter marks as sensitive. replacement is what to set the field to; pass // sensitiveRedactedValue for plan output display, or "" for state-file storage. @@ -92,6 +104,26 @@ func redactChanges(adapter *dresources.Adapter, changes deployplan.Changes) erro return nil } +// withoutSensitiveRefs returns a copy of refs without the references of sensitive fields. The map is +// shared with the state cache that a plain deploy applies, so it is not changed. A reference left in a +// sensitive field would show its template in the plan, and apply takes that value from the config. +func withoutSensitiveRefs(rules []dresources.FieldRule, refs map[string]string) (map[string]string, error) { + if refs == nil { + return nil, nil + } + out := maps.Clone(refs) + for key := range refs { + path, err := structpath.ParsePath(key) + if err != nil { + return nil, fmt.Errorf("parsing reference path %q: %w", key, err) + } + if isSensitivePath(rules, path) { + delete(out, key) + } + } + return out, nil +} + // redactPlanEntry redacts new_state, remote_state and changes of a plan entry. It runs once planning // is done: the plan must not be serialized before this, and apply reads the unredacted cache, not // new_state, so nothing after this point re-serializes the values into the entry. @@ -112,6 +144,10 @@ func redactPlanEntry(adapter *dresources.Adapter, entry *deployplan.PlanEntry) e if err != nil { return fmt.Errorf("redacting new_state: %w", err) } + redacted.Refs, err = withoutSensitiveRefs(adapter.ResourceConfig().SensitiveFields, redacted.Refs) + if err != nil { + return fmt.Errorf("redacting new_state: %w", err) + } *entry.NewState = *redacted } @@ -130,11 +166,11 @@ func redactPlanEntry(adapter *dresources.Adapter, entry *deployplan.PlanEntry) e return nil } -// restoreSensitiveFields restores the sensitive fields of a saved plan's state, planned, from the -// config. The values are built the way makePlan builds them, so a deploy from the plan sends what a -// plain deploy sends: a reference stays in the refs and is resolved at apply, and an escaped "$${...}" -// is sent as the literal "${...}". A field the plan holds non-zero must have a config value. -func restoreSensitiveFields(adapter *dresources.Adapter, resourceKey string, planned *structvar.StructVar, root *config.Root) error { +// restoreSensitiveFields restores the sensitive fields of a saved plan's state, planned, from the config. +// The values and their references come from buildPlannedState, as makePlan builds them. A reference +// to a resource the plan does not depend on is an error, since apply would not order the resource +// before this one. The references are resolved before deploy by resolveSensitiveRefs, as planning does. +func restoreSensitiveFields(adapter *dresources.Adapter, resourceKey string, dependsOn []deployplan.DependsOnEntry, planned *structvar.StructVar, root *config.Root) error { rules := dresources.GetResourceConfig(config.GetResourceTypeFromKey(resourceKey)).SensitiveFields if len(rules) == 0 { return nil @@ -158,67 +194,107 @@ func restoreSensitiveFields(adapter *dresources.Adapter, resourceKey string, pla return nil } - inputStructVar, err := adapter.PrepareInputConfig(inputConfig, resourceKey) - if err != nil { - return fmt.Errorf("resource %s: %w", resourceKey, err) - } - built, err := adapter.PrepareState(inputStructVar.Value) + state, err := buildPlannedState(adapter, resourceKey, inputConfig, root) if err != nil { return fmt.Errorf("resource %s: %w", resourceKey, err) } - // The references are the same ones makePlan records for the resource. - refs, err := extractReferences(root.Value(), resourceKey, adapter.StateType()) - if err != nil { - return fmt.Errorf("resource %s: reading references: %w", resourceKey, err) - } - maps.Copy(refs, inputStructVar.Refs) - - // Checked before unescaping: an escaped "$${...}" is a literal, but an unescaped reference - // without a recorded ref would be sent as it is. for _, path := range paths { - raw, err := structaccess.Get(built, path) + plannedValue, err := structaccess.Get(planned.Value, path) if err != nil { continue } - if s, _ := raw.(string); dynvar.ContainsVariableReference(s) && refs[path.String()] == "" { - return fmt.Errorf("resource %s: sensitive field %s holds an unresolved reference %q", resourceKey, path, s) - } - } - - if err := unescapeRefs(built); err != nil { - return fmt.Errorf("resource %s: %w", resourceKey, err) - } - - for _, path := range paths { - v, err := structaccess.Get(built, path) + v, err := structaccess.Get(state.Value, path) if err != nil { continue } value, _ := v.(string) - plannedValue, err := structaccess.Get(planned.Value, path) - if err != nil { - continue - } if value == "" { if !isZeroValue(plannedValue) { return fmt.Errorf("resource %s: the config has no value for sensitive field %s; set the variable it uses with --var or BUNDLE_VAR_", resourceKey, path) } + } else if err := structaccess.Set(planned.Value, path, value); err != nil { + return fmt.Errorf("resource %s: restoring sensitive field %s: %w", resourceKey, path, err) + } + + key := path.String() + ref, ok := state.Refs[key] + if !ok { + delete(planned.Refs, key) continue } - if err := structaccess.Set(planned.Value, path, value); err != nil { - return fmt.Errorf("resource %s: restoring sensitive field %s: %w", resourceKey, path, err) + if target, ok := unplannedReference(dependsOn, ref); ok { + return fmt.Errorf("resource %s: sensitive field %s now references %s, which the saved plan does not depend on; run 'bundle plan' again", resourceKey, path, target) } - if ref, ok := refs[path.String()]; ok { - if planned.Refs == nil { - planned.Refs = make(map[string]string) + if planned.Refs == nil { + planned.Refs = make(map[string]string) + } + planned.Refs[key] = ref + } + return nil +} + +// unplannedReference returns a resource that ref refers to and dependsOn does not list, if there is one. +func unplannedReference(dependsOn []deployplan.DependsOnEntry, ref string) (string, bool) { + r, ok := dynvar.NewRef(dyn.V(ref)) + if !ok { + return "", false + } + for _, target := range r.References() { + p, err := dyn.NewPathFromString(target) + if err != nil { + return target, true + } + node, _ := config.GetNodeAndType(p) + nodeKey := node.String() + if !slices.ContainsFunc(dependsOn, func(d deployplan.DependsOnEntry) bool { return d.Node == nodeKey }) { + return nodeKey, true + } + } + return "", false +} + +// resolveSensitiveRefs resolves the references of sensitive fields that planning resolves before deploy, +// from the local config of their targets (LookupReferencePreDeploy), so the values match a plain deploy. +// A reference that cannot be resolved this way is left in place: apply resolves it after the target is +// deployed, from the remote state, which can differ from the local config for a field the backend +// normalizes. +func (b *DeploymentBundle) resolveSensitiveRefs(ctx context.Context, rules []dresources.FieldRule, sv *structvar.StructVar) error { + resolved := make(map[string]bool) + for _, key := range slices.Sorted(maps.Keys(sv.Refs)) { + path, err := structpath.ParsePath(key) + if err != nil { + return fmt.Errorf("parsing reference path %q: %w", key, err) + } + if !isSensitivePath(rules, path) { + continue + } + r, ok := dynvar.NewRef(dyn.V(sv.Refs[key])) + if !ok { + continue + } + for _, target := range r.References() { + if resolved[target] { + continue + } + targetPath, err := structpath.ParsePath(target) + if err != nil { + return fmt.Errorf("parsing reference %q: %w", target, err) + } + value, err := b.LookupReferencePreDeploy(ctx, targetPath) + if err != nil { + continue + } + if err := sv.ResolveRef("${"+target+"}", value); err != nil { + return fmt.Errorf("resolving %q in %s: %w", target, key, err) } - planned.Refs[path.String()] = ref + resolved[target] = true } } return nil } +// isZeroValue reports whether a field of a saved plan's state holds no value. func isZeroValue(v any) bool { return v == nil || v == "" } diff --git a/bundle/direct/redact_test.go b/bundle/direct/redact_test.go index ad9aef6824f..0c99939840e 100644 --- a/bundle/direct/redact_test.go +++ b/bundle/direct/redact_test.go @@ -92,6 +92,7 @@ func secretRoot(t *testing.T, value string, variables map[string]*variable.Varia const ( msgValueMissing = "resource resources.secrets.s: the config has no value for sensitive field value; set the variable it uses with --var or BUNDLE_VAR_" msgNotInConfig = "resource resources.secrets.gone is not in the config; run 'bundle plan' again" + msgUnplannedRef = "resource resources.secrets.s: sensitive field value now references resources.catalogs.c, which the saved plan does not depend on; run 'bundle plan' again" ) // TestRestoreSensitiveFields checks the value a saved plan's sensitive field is restored to: what a @@ -107,6 +108,8 @@ func TestRestoreSensitiveFields(t *testing.T) { configValue string wantValue string wantRefs map[string]string + plannedRefs map[string]string + dependsOn []deployplan.DependsOnEntry wantErr string }{ { @@ -158,6 +161,23 @@ func TestRestoreSensitiveFields(t *testing.T) { configValue: "${resources.catalogs.c.name}", wantValue: "${resources.catalogs.c.name}", wantRefs: map[string]string{"value": "${resources.catalogs.c.name}"}, + dependsOn: []deployplan.DependsOnEntry{{Node: "resources.catalogs.c", Label: "${resources.catalogs.c.name}"}}, + }, + { + name: "a reference the plan does not depend on is an error", + resourceKey: "resources.secrets.s", + planned: sensitiveRedactedValue, + configValue: "${resources.catalogs.c.name}", + wantErr: msgUnplannedRef, + }, + { + name: "a reference the plan had is dropped when the config has a literal", + resourceKey: "resources.secrets.s", + planned: sensitiveRedactedValue, + plannedRefs: map[string]string{"value": "${resources.catalogs.c.name}"}, + configValue: secretLiteral, + wantValue: secretLiteral, + dependsOn: []deployplan.DependsOnEntry{{Node: "resources.catalogs.c", Label: "${resources.catalogs.c.name}"}}, }, { name: "an escaped reference is sent as the literal it escapes", @@ -171,8 +191,8 @@ func TestRestoreSensitiveFields(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { root := secretRoot(t, tc.configValue, nil) - planned := &structvar.StructVar{Value: &catalog.Secret{Name: "s", Value: tc.planned}} - err := restoreSensitiveFields(adapter, tc.resourceKey, planned, root) + planned := &structvar.StructVar{Value: &catalog.Secret{Name: "s", Value: tc.planned}, Refs: tc.plannedRefs} + err := restoreSensitiveFields(adapter, tc.resourceKey, tc.dependsOn, planned, root) if tc.wantErr != "" { assert.EqualError(t, err, tc.wantErr) return @@ -181,7 +201,11 @@ func TestRestoreSensitiveFields(t *testing.T) { secret := planned.Value.(*catalog.Secret) assert.Equal(t, tc.wantValue, secret.Value) assert.Empty(t, secret.EffectiveValue) - assert.Equal(t, tc.wantRefs, planned.Refs) + if tc.wantRefs == nil { + assert.Empty(t, planned.Refs) + } else { + assert.Equal(t, tc.wantRefs, planned.Refs) + } }) } } @@ -266,6 +290,29 @@ func TestCheckSensitivePlanValuesOneErrorPerResource(t *testing.T) { assert.EqualError(t, errs[2], msgNotInConfig) } +// TestRedactPlanEntryDropsSensitiveRefs checks that a reference left in a sensitive field is not written +// to the plan, since its template would show the secret, and that the state cache's map keeps it. +func TestRedactPlanEntryDropsSensitiveRefs(t *testing.T) { + adapter := secretAdapter(t) + refs := map[string]string{"value": "dummy-credential-${resources.catalogs.c.id}"} + + entry := &deployplan.PlanEntry{ + Action: deployplan.Create, + NewState: &structvar.StructVarJSON{ + Value: []byte(`{"name":"s","value":"dummy-credential-${resources.catalogs.c.id}"}`), + Refs: refs, + }, + } + + require.NoError(t, redactPlanEntry(adapter, entry)) + + out, err := json.Marshal(entry) + require.NoError(t, err) + assert.NotContains(t, string(out), "dummy-credential") + assert.Empty(t, entry.NewState.Refs) + assert.Equal(t, "dummy-credential-${resources.catalogs.c.id}", refs["value"]) +} + // TestResolveReferencesAfterApplyKeepsRedactedEntry checks that apply resolving a reference does not write // the resolved value back into the plan entry, which would put the secret back into memory after redaction. func TestResolveReferencesAfterApplyKeepsRedactedEntry(t *testing.T) { From d7a97da1b36f647db0d4ddd0f66b260e3f83f2d6 Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Mon, 30 Nov 2026 09:22:52 +0000 Subject: [PATCH 13/17] Resolve sensitive references before deploy with the planning rules A reference in a sensitive field to an unchanged resource was left for apply, which reads the remote state. The API lowercases some names, so a plain deploy and deploy --plan sent different values. A reference that did not resolve was skipped, and the failure came after the catalog was created. An unchanged resource now gets a local state built from the config the way planning builds it, and references resolve from it. Only a delayed reference is left for apply; any other lookup error stops the deploy. CheckSensitivePlanValues runs the same resolution before anything is uploaded. A lookup of a remote-only field without remote state is delayed, not an error. Co-authored-by: Isaac --- .../sensitive/plan-restore/output.txt | 60 +++++++++++++ .../variables/sensitive/plan-restore/script | 84 +++++++++++++++++++ bundle/direct/bundle_plan.go | 79 +++++++++++++---- bundle/direct/redact.go | 27 +++--- bundle/direct/redact_test.go | 4 +- cmd/bundle/utils/process.go | 2 +- 6 files changed, 229 insertions(+), 27 deletions(-) diff --git a/acceptance/bundle/variables/sensitive/plan-restore/output.txt b/acceptance/bundle/variables/sensitive/plan-restore/output.txt index bafab7f46ae..c108b3296c5 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/output.txt +++ b/acceptance/bundle/variables/sensitive/plan-restore/output.txt @@ -137,3 +137,63 @@ Error: resource resources.secrets.ref_secret: sensitive field value now referenc "value": "[redacted]" } } + +=== an unchanged schema: a reference to its name sends the name a plain deploy sends + +>>> [CLI] bundle destroy --auto-approve +No active deployment found to destroy! + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created schemas.s +Files: 1 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> [CLI] bundle deploy --plan .databricks/plan-schema.json +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created secrets.sec +Files: 1 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 1 unchanged + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.schemas.s + delete resources.secrets.sec + +This action will result in the deletion of the following UC schemas. Any underlying data may be lost: + delete resources.schemas.s + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 2 deleted + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created schemas.s +Files: 1 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created secrets.sec +Files: 1 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 1 unchanged +{"name":"sec","value":"MySchema"} + +=== a reference that changes to a missing field after planning: refused before any upload or create + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.schemas.s + delete resources.secrets.sec + +This action will result in the deletion of the following UC schemas. Any underlying data may be lost: + delete resources.schemas.s + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 2 deleted + +>>> [CLI] bundle deploy --plan .databricks/plan-bad.json +Error: resource resources.secrets.ref_secret: cannot resolve "${resources.catalogs.source_catalog.nonexistent}" in value: schema mismatch: nonexistent: field "nonexistent" not found in dresources.CatalogState; nonexistent: field "nonexistent" not found in catalog.CatalogInfo + diff --git a/acceptance/bundle/variables/sensitive/plan-restore/script b/acceptance/bundle/variables/sensitive/plan-restore/script index 8b95f82d7f6..86427755784 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/script +++ b/acceptance/bundle/variables/sensitive/plan-restore/script @@ -105,3 +105,87 @@ musterr trace $CLI bundle deploy --plan .databricks/plan-literal.json title "a sensitive value with an unresolved reference: the plan shows neither the template nor its reference" trace env BUNDLE_VAR_api_header='dummy-credential-${resources.catalogs.source_catalog.id}' $CLI bundle plan -o json | contains.py '!dummy-credential' | jq -S '.plan["resources.secrets.escaped_secret"].new_state' + +# The schema is deployed before the plan, so it is unchanged and has no new_state in the saved plan. Its +# name has upper case, which the API lowercases in responses: a reference to it must send the name as written. +cat > .databricks/schema-only.yml <<'EOF' +bundle: + name: sensitive-variables + +resources: + schemas: + s: + name: MySchema + catalog_name: main +EOF +cat > .databricks/schema-ref.yml <<'EOF' +bundle: + name: sensitive-variables + +resources: + schemas: + s: + name: MySchema + catalog_name: main + secrets: + sec: + name: sec + catalog_name: main + schema_name: default + value: ${resources.schemas.s.name} +EOF + +title "an unchanged schema: a reference to its name sends the name a plain deploy sends" +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +cp .databricks/schema-only.yml databricks.yml +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" +cp .databricks/schema-ref.yml databricks.yml +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan-schema.json +before=$(wc -l < "$OUT_REQUESTS") +trace $CLI bundle deploy --plan .databricks/plan-schema.json | contains.py "${SECRETS[@]}" +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$CREATES" | sort > .databricks/schema-plan.json +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +cp .databricks/schema-only.yml databricks.yml +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" +cp .databricks/schema-ref.yml databricks.yml +before=$(wc -l < "$OUT_REQUESTS") +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$CREATES" | sort > .databricks/schema-plain.json +diff .databricks/schema-plain.json .databricks/schema-plan.json +cat .databricks/schema-plan.json + +# The reference changes to a field the resource does not have, after the plan was made. The plan's +# depends_on still lists the catalog, so only the reference check can refuse it: it must fail before any upload or create. +cat > .databricks/bad-ref.yml <<'EOF' +bundle: + name: sensitive-variables + +variables: + api_header: + description: Sensitive value supplied with BUNDLE_VAR_api_header, containing an escaped reference. + sensitive: true + +resources: + catalogs: + source_catalog: + name: dummy-catalog-name + secrets: + ref_secret: + name: ref_secret + catalog_name: main + schema_name: default + value: ${resources.catalogs.source_catalog.nonexistent} + escaped_secret: + name: escaped_secret + catalog_name: main + schema_name: default + value: ${var.api_header} +EOF + +title "a reference that changes to a missing field after planning: refused before any upload or create" +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +cp .databricks/base.yml databricks.yml +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan-bad.json +cp .databricks/bad-ref.yml databricks.yml +musterr trace $CLI bundle deploy --plan .databricks/plan-bad.json +cp .databricks/base.yml databricks.yml diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index 8031c5840a1..18456502c55 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -70,16 +70,40 @@ func ValidatePlanAgainstState(stateDB *dstate.DeploymentState, plan *deployplan. } // CheckSensitivePlanValues returns one error per resource that stops a saved plan from being applied: -// a sensitive field the plan sets whose config value is empty, or a resource the config no longer has. -// It runs the same restore as InitForApply, so the check and the apply cannot disagree. The config -// holds the values from --var, BUNDLE_VAR_, defaults, targets and the variable-overrides file alike. -func CheckSensitivePlanValues(root *config.Root, plan *deployplan.Plan) []error { +// a sensitive field the plan sets whose config value is empty, a resource the config no longer has, +// or a reference in a sensitive field that cannot be resolved. It runs the same restore and reference +// resolution as InitForApply, before anything is uploaded or created. The config holds the values from +// --var, BUNDLE_VAR_, defaults, targets and the variable-overrides file alike. +func CheckSensitivePlanValues(ctx context.Context, root *config.Root, plan *deployplan.Plan) []error { adapters, err := dresources.InitAll(nil) if err != nil { return []error{err} } - b := DeploymentBundle{Adapters: adapters} - _, errs := restoreSavedPlanStates(root, plan, b.getAdapterForKey) + b := &DeploymentBundle{Adapters: adapters, Plan: plan} + states, errs := restoreSavedPlanStates(root, plan, b.getAdapterForKey) + for resourceKey, sv := range states { + b.StateCache.Store(resourceKey, sv) + } + // Without a state database, a reference to a resource id is left for apply, which has one. + lookup := func(ctx context.Context, path *structpath.PathNode) (any, error) { + if _, field := splitResourcePath(path); field.String() == "id" { + return nil, errDelayed + } + return b.LookupReferencePreDeploy(ctx, path) + } + errs = append(errs, b.resolveAllSensitiveRefs(ctx, states, lookup)...) + return errs +} + +// resolveAllSensitiveRefs resolves the sensitive references of every restored state, in key order. +func (b *DeploymentBundle) resolveAllSensitiveRefs(ctx context.Context, states map[string]*structvar.StructVar, lookup referenceLookup) []error { + var errs []error + for _, resourceKey := range slices.Sorted(maps.Keys(states)) { + rules := dresources.GetResourceConfig(config.GetResourceTypeFromKey(resourceKey)).SensitiveFields + if err := resolveSensitiveRefs(ctx, resourceKey, rules, states[resourceKey], lookup); err != nil { + errs = append(errs, err) + } + } return errs } @@ -110,6 +134,34 @@ func restoreSavedPlanStates(root *config.Root, plan *deployplan.Plan, adapterFor } states[resourceKey] = sv } + + // An unchanged resource has no new_state in the plan. A reference to it is resolved from its local + // state, built from the config the way planning builds it, as planning resolves it. + for _, resourceKey := range slices.Sorted(maps.Keys(plan.Plan)) { + entry := plan.Plan[resourceKey] + if entry.Action != deployplan.Skip || entry.NewState != nil { + continue + } + inputConfig, err := root.GetResourceConfig(resourceKey) + if err != nil { + errs = append(errs, fmt.Errorf("resource %s: %w", resourceKey, err)) + continue + } + if inputConfig == nil { + continue + } + adapter, err := adapterFor(resourceKey) + if err != nil { + errs = append(errs, fmt.Errorf("converting plan entry %s: %w", resourceKey, err)) + continue + } + state, err := buildPlannedState(adapter, resourceKey, inputConfig, root) + if err != nil { + errs = append(errs, fmt.Errorf("resource %s: %w", resourceKey, err)) + continue + } + states[resourceKey] = state + } return states, errs } @@ -132,11 +184,8 @@ func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks. b.StateCache.Store(resourceKey, sv) } b.Plan = plan - for _, resourceKey := range slices.Sorted(maps.Keys(states)) { - rules := dresources.GetResourceConfig(config.GetResourceTypeFromKey(resourceKey)).SensitiveFields - if err := b.resolveSensitiveRefs(ctx, rules, states[resourceKey]); err != nil { - return err - } + if errs := b.resolveAllSensitiveRefs(ctx, states, b.LookupReferencePreDeploy); len(errs) > 0 { + return errors.Join(errs...) } // Eagerly parse remote state loaded from JSON: @@ -1436,7 +1485,8 @@ func (b *DeploymentBundle) LookupReferencePreDeploy(ctx context.Context, path *s return nil, errDelayed } - if targetEntry.NewState == nil { + // An unchanged resource has no new_state in a saved plan; its state comes from the cache instead. + if targetEntry.NewState == nil && targetAction != deployplan.Skip { return nil, fmt.Errorf("internal error: %s: action is %q missing new_state", targetResourceKey, targetEntry.Action) } @@ -1495,7 +1545,8 @@ func (b *DeploymentBundle) LookupReferencePreDeploy(ctx context.Context, path *s if ok { return structaccess.Get(remoteState, fieldPath) } else { - return nil, fmt.Errorf("internal error: no entry in remote state cache for %q (remote-only)", targetResourceKey) + // A saved plan is applied without the remote state of its targets; apply reads it. + return nil, fmt.Errorf("%w: no remote state for %q (remote-only)", errDelayed, targetResourceKey) } } return nil, errDelayed @@ -1514,7 +1565,7 @@ func (b *DeploymentBundle) LookupReferencePreDeploy(ctx context.Context, path *s if ok { return structaccess.Get(remoteState, fieldPath) } else { - return nil, fmt.Errorf("internal error: no entry in remote state cache for %q", targetResourceKey) + return nil, fmt.Errorf("%w: no remote state for %q", errDelayed, targetResourceKey) } } diff --git a/bundle/direct/redact.go b/bundle/direct/redact.go index 6d64fba31af..53e67a07a74 100644 --- a/bundle/direct/redact.go +++ b/bundle/direct/redact.go @@ -2,6 +2,7 @@ package direct import ( "context" + "errors" "fmt" "maps" "slices" @@ -254,17 +255,20 @@ func unplannedReference(dependsOn []deployplan.DependsOnEntry, ref string) (stri return "", false } +// referenceLookup returns the value a reference resolves to before deploy, or errDelayed when the value +// is only known after the target is deployed. +type referenceLookup func(context.Context, *structpath.PathNode) (any, error) + // resolveSensitiveRefs resolves the references of sensitive fields that planning resolves before deploy, -// from the local config of their targets (LookupReferencePreDeploy), so the values match a plain deploy. -// A reference that cannot be resolved this way is left in place: apply resolves it after the target is -// deployed, from the remote state, which can differ from the local config for a field the backend -// normalizes. -func (b *DeploymentBundle) resolveSensitiveRefs(ctx context.Context, rules []dresources.FieldRule, sv *structvar.StructVar) error { +// so the values match a plain deploy. A reference that is delayed stays in place for apply, which +// resolves it after the target is deployed. Any other lookup error stops the deploy: the value would +// otherwise be sent from a reference that does not resolve. +func resolveSensitiveRefs(ctx context.Context, resourceKey string, rules []dresources.FieldRule, sv *structvar.StructVar, lookup referenceLookup) error { resolved := make(map[string]bool) for _, key := range slices.Sorted(maps.Keys(sv.Refs)) { path, err := structpath.ParsePath(key) if err != nil { - return fmt.Errorf("parsing reference path %q: %w", key, err) + return fmt.Errorf("resource %s: parsing reference path %q: %w", resourceKey, key, err) } if !isSensitivePath(rules, path) { continue @@ -279,14 +283,17 @@ func (b *DeploymentBundle) resolveSensitiveRefs(ctx context.Context, rules []dre } targetPath, err := structpath.ParsePath(target) if err != nil { - return fmt.Errorf("parsing reference %q: %w", target, err) + return fmt.Errorf("resource %s: parsing reference %q: %w", resourceKey, target, err) } - value, err := b.LookupReferencePreDeploy(ctx, targetPath) - if err != nil { + value, err := lookup(ctx, targetPath) + if errors.Is(err, errDelayed) { continue } + if err != nil { + return fmt.Errorf("resource %s: cannot resolve %q in %s: %w", resourceKey, "${"+target+"}", key, err) + } if err := sv.ResolveRef("${"+target+"}", value); err != nil { - return fmt.Errorf("resolving %q in %s: %w", target, key, err) + return fmt.Errorf("resource %s: cannot resolve %q in %s: %w", resourceKey, "${"+target+"}", key, err) } resolved[target] = true } diff --git a/bundle/direct/redact_test.go b/bundle/direct/redact_test.go index 0c99939840e..4430a0d9fee 100644 --- a/bundle/direct/redact_test.go +++ b/bundle/direct/redact_test.go @@ -257,7 +257,7 @@ func TestCheckSensitivePlanValues(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - errs := CheckSensitivePlanValues(tc.root, tc.plan) + errs := CheckSensitivePlanValues(t.Context(), tc.root, tc.plan) if tc.wantErr == "" { assert.Empty(t, errs) return @@ -283,7 +283,7 @@ func TestCheckSensitivePlanValuesOneErrorPerResource(t *testing.T) { "resources.secrets.gone": {NewState: &structvar.StructVarJSON{Value: []byte(`{"name":"gone","value":"[redacted]"}`)}}, }} - errs := CheckSensitivePlanValues(root, plan) + errs := CheckSensitivePlanValues(t.Context(), root, plan) require.Len(t, errs, 3) assert.EqualError(t, errs[0], "resource resources.secrets.a: the config has no value for sensitive field value; set the variable it uses with --var or BUNDLE_VAR_") assert.EqualError(t, errs[1], "resource resources.secrets.b: the config has no value for sensitive field value; set the variable it uses with --var or BUNDLE_VAR_") diff --git a/cmd/bundle/utils/process.go b/cmd/bundle/utils/process.go index 5d476b90537..a9a4f0537eb 100644 --- a/cmd/bundle/utils/process.go +++ b/cmd/bundle/utils/process.go @@ -492,7 +492,7 @@ func ProcessBundleRet(cmd *cobra.Command, opts ProcessOptions) (b *bundle.Bundle return b, stateDesc, root.ErrAlreadyPrinted } - if errs := direct.CheckSensitivePlanValues(&b.Config, plan); len(errs) > 0 { + if errs := direct.CheckSensitivePlanValues(ctx, &b.Config, plan); len(errs) > 0 { for _, err := range errs { logdiag.LogError(ctx, err) } From 47e837f9e526c005eb9cc83dea339e048b5797ba Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Tue, 1 Dec 2026 10:45:30 +0000 Subject: [PATCH 14/17] Pin saved plan references that deploy --plan resolves differently plan-restore now covers three cases a saved plan must match a plain deploy on: a comment that refers to a secret value which becomes a literal after planning, a chained reference to an unchanged schema name, and a map key that is missing after planning, which must fail before any upload or create. A unit test checks that the check does not change the plan entry's references. Co-authored-by: Isaac --- .../sensitive/plan-restore/output.txt | 116 +++++++++++- .../variables/sensitive/plan-restore/script | 169 ++++++++++++++++++ .../sensitive/plan-restore/test.toml | 1 + bundle/direct/redact_test.go | 23 +++ 4 files changed, 308 insertions(+), 1 deletion(-) diff --git a/acceptance/bundle/variables/sensitive/plan-restore/output.txt b/acceptance/bundle/variables/sensitive/plan-restore/output.txt index c108b3296c5..bfd0079c586 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/output.txt +++ b/acceptance/bundle/variables/sensitive/plan-restore/output.txt @@ -195,5 +195,119 @@ All files and directories at the following location will be deleted: /Workspace/ Destroy: 2 deleted >>> [CLI] bundle deploy --plan .databricks/plan-bad.json -Error: resource resources.secrets.ref_secret: cannot resolve "${resources.catalogs.source_catalog.nonexistent}" in value: schema mismatch: nonexistent: field "nonexistent" not found in dresources.CatalogState; nonexistent: field "nonexistent" not found in catalog.CatalogInfo +Error: resource resources.secrets.ref_secret: cannot resolve "${resources.catalogs.source_catalog.nonexistent}": schema mismatch: nonexistent: field "nonexistent" not found in dresources.CatalogState; nonexistent: field "nonexistent" not found in catalog.CatalogInfo + + +=== a reference in a sensitive field becomes a literal after planning: the comment of a dependent secret matches a plain deploy + +>>> [CLI] bundle destroy --auto-approve +No active deployment found to destroy! + +>>> [CLI] bundle deploy --plan .databricks/plan-comment.json +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created catalogs.source_catalog +Created secrets.sec_a +Created secrets.sec_b +Files: 1 uploaded, 0 deleted +Resources: 3 created, 0 changed, 0 deleted, 0 unchanged + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.catalogs.source_catalog + delete resources.secrets.sec_a + delete resources.secrets.sec_b + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 3 deleted + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created catalogs.source_catalog +Created secrets.sec_a +Created secrets.sec_b +Files: 1 uploaded, 0 deleted +Resources: 3 created, 0 changed, 0 deleted, 0 unchanged +comment and value: same as a plain deploy +false + +=== a chained reference to an unchanged schema: a saved plan sends the name a plain deploy sends + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.catalogs.source_catalog + delete resources.secrets.sec_a + delete resources.secrets.sec_b + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 3 deleted + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created schemas.s +Created schemas.s2 +Files: 1 uploaded, 0 deleted +Resources: 2 created, 0 changed, 0 deleted, 0 unchanged + +>>> [CLI] bundle deploy --plan .databricks/plan-chain.json +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created secrets.sec_c +Files: 1 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 2 unchanged + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.schemas.s + delete resources.schemas.s2 + delete resources.secrets.sec_c + +This action will result in the deletion of the following UC schemas. Any underlying data may be lost: + delete resources.schemas.s + delete resources.schemas.s2 + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 3 deleted + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created schemas.s +Created schemas.s2 +Created secrets.sec_c +Files: 1 uploaded, 0 deleted +Resources: 3 created, 0 changed, 0 deleted, 0 unchanged +{"name":"sec_c","value":"MySchemaTwo"} + +=== a map key that is missing after planning: deploy --plan fails before any upload or create, as bundle plan does + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.schemas.s + delete resources.schemas.s2 + delete resources.secrets.sec_c + +This action will result in the deletion of the following UC schemas. Any underlying data may be lost: + delete resources.schemas.s + delete resources.schemas.s2 + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 3 deleted + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created schemas.s +Created secrets.sec_other +Files: 1 uploaded, 0 deleted +Resources: 2 created, 0 changed, 0 deleted, 0 unchanged + +>>> [CLI] bundle plan +Error: cannot plan resources.secrets.sec_d: cannot resolve "${resources.schemas.s.properties.missing}": properties.missing: key "missing" not found in map + +Error: planning failed + + +>>> [CLI] bundle deploy --plan .databricks/plan-props.json +Error: resource resources.secrets.sec_d: cannot resolve "${resources.schemas.s.properties.missing}": properties.missing: key "missing" not found in map diff --git a/acceptance/bundle/variables/sensitive/plan-restore/script b/acceptance/bundle/variables/sensitive/plan-restore/script index 86427755784..4d1af96e035 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/script +++ b/acceptance/bundle/variables/sensitive/plan-restore/script @@ -189,3 +189,172 @@ $CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan-bad.js cp .databricks/bad-ref.yml databricks.yml musterr trace $CLI bundle deploy --plan .databricks/plan-bad.json cp .databricks/base.yml databricks.yml + +# A secret that depends on another secret's value through its comment as well: the reference in the +# comment is kept in the saved plan until the reference of the value is resolved. The value is a sensitive +# variable without escapes, so the literal the variable resolves to is not parsed as a reference. +cat > .databricks/comment-plan.yml <<'EOF2' +bundle: + name: sensitive-variables + +variables: + comment_value: + description: Sensitive value that a secret value and comment are built from. + sensitive: true + +resources: + catalogs: + source_catalog: + name: dummy-catalog-name + secrets: + sec_a: + name: sec_a + catalog_name: main + schema_name: default + value: ${resources.catalogs.source_catalog.id} + sec_b: + name: sec_b + catalog_name: main + schema_name: default + value: ${resources.secrets.sec_a.value} + comment: c-${resources.secrets.sec_a.value} +EOF2 +sed 's/value: ${resources.catalogs.source_catalog.id}/value: ${var.comment_value}/' .databricks/comment-plan.yml > .databricks/comment-literal.yml +COMMENTS='select(.method == "POST" and .path == "/api/2.1/unity-catalog/secrets") | {name: .body.name, comment: .body.comment, value: .body.value}' + +title "a reference in a sensitive field becomes a literal after planning: the comment of a dependent secret matches a plain deploy" +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +cp .databricks/comment-plan.yml databricks.yml +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" '!comment-secret-value' > .databricks/plan-comment.json +cp .databricks/comment-literal.yml databricks.yml +before=$(wc -l < "$OUT_REQUESTS") +trace $CLI bundle deploy --plan .databricks/plan-comment.json | contains.py "${SECRETS[@]}" '!comment-secret-value' +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$COMMENTS" | sort > .databricks/comment-saved.json +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" '!comment-secret-value' +before=$(wc -l < "$OUT_REQUESTS") +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" '!comment-secret-value' +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$COMMENTS" | sort > .databricks/comment-plain.json +# The values are not printed: they are compared, and no reference is left in the comment. +if cmp -s .databricks/comment-plain.json .databricks/comment-saved.json; then echo "comment and value: same as a plain deploy"; else echo "comment and value: different from a plain deploy"; fi +jq -s -c 'map(select(.name == "sec_b") | .comment | contains("${")) | any' .databricks/comment-saved.json + +# The schema s2 takes its name from s. Its name is planned as an unchanged resource: a reference to s2.name +# must send the name a plain deploy sends, MySchemaTwo, not the name the API returns in lower case. +cat > .databricks/chain-schemas.yml <<'EOF2' +bundle: + name: sensitive-variables + +resources: + schemas: + s: + name: MySchema + catalog_name: main + s2: + name: ${resources.schemas.s.name}Two + catalog_name: main +EOF2 +cat > .databricks/chain-ref.yml <<'EOF2' +bundle: + name: sensitive-variables + +resources: + schemas: + s: + name: MySchema + catalog_name: main + s2: + name: ${resources.schemas.s.name}Two + catalog_name: main + secrets: + sec_c: + name: sec_c + catalog_name: main + schema_name: default + value: ${resources.schemas.s2.name} +EOF2 +SCHEMA_SECRETS='select(.method == "POST" and .path == "/api/2.1/unity-catalog/secrets") | {name: .body.name, value: .body.value}' + +title "a chained reference to an unchanged schema: a saved plan sends the name a plain deploy sends" +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +cp .databricks/chain-schemas.yml databricks.yml +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" +cp .databricks/chain-ref.yml databricks.yml +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan-chain.json +before=$(wc -l < "$OUT_REQUESTS") +trace $CLI bundle deploy --plan .databricks/plan-chain.json | contains.py "${SECRETS[@]}" +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$SCHEMA_SECRETS" | sort > .databricks/chain-saved.json +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +before=$(wc -l < "$OUT_REQUESTS") +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c "$SCHEMA_SECRETS" | sort > .databricks/chain-plain.json +diff .databricks/chain-plain.json .databricks/chain-saved.json +cat .databricks/chain-saved.json + +# A map key that is in the deployed schema when planned and missing when deploy --plan runs. A plain +# bundle plan fails on it, so the saved plan must fail before anything is uploaded or created. +cat > .databricks/props-schema.yml <<'EOF2' +bundle: + name: sensitive-variables + +variables: + api_header: + description: Sensitive value supplied with BUNDLE_VAR_api_header, containing an escaped reference. + sensitive: true + +resources: + schemas: + s: + name: MySchema + catalog_name: main + properties: + k: v + secrets: + sec_other: + name: sec_other + catalog_name: main + schema_name: default + value: ${var.api_header} +EOF2 +cat > .databricks/props-k.yml <<'EOF2' +bundle: + name: sensitive-variables + +variables: + api_header: + description: Sensitive value supplied with BUNDLE_VAR_api_header, containing an escaped reference. + sensitive: true + +resources: + schemas: + s: + name: MySchema + catalog_name: main + properties: + k: v + secrets: + sec_other: + name: sec_other + catalog_name: main + schema_name: default + value: ${var.api_header} + sec_d: + name: sec_d + catalog_name: main + schema_name: default + value: ${resources.schemas.s.properties.k} +EOF2 +sed 's/properties.k}/properties.missing}/' .databricks/props-k.yml > .databricks/props-missing.yml + +title "a map key that is missing after planning: deploy --plan fails before any upload or create, as bundle plan does" +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +cp .databricks/props-schema.yml databricks.yml +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" +cp .databricks/props-k.yml databricks.yml +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan-props.json +cp .databricks/props-missing.yml databricks.yml +before=$(wc -l < "$OUT_REQUESTS") +musterr trace $CLI bundle plan +musterr trace $CLI bundle deploy --plan .databricks/plan-props.json +# Any request that changes state would be listed here. +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c 'select(.method != "GET" and .path != "/telemetry-ext") | {method, path}' +cp .databricks/base.yml databricks.yml diff --git a/acceptance/bundle/variables/sensitive/plan-restore/test.toml b/acceptance/bundle/variables/sensitive/plan-restore/test.toml index 3f5a71b07fa..b6c052af639 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/test.toml +++ b/acceptance/bundle/variables/sensitive/plan-restore/test.toml @@ -2,3 +2,4 @@ RecordRequests = true Env.BUNDLE_VAR_api_header = 'escaped-$${x}' Cloud = false EnvMatrix.DMS = ["", "true"] +Env.BUNDLE_VAR_comment_value = 'comment-secret-value' diff --git a/bundle/direct/redact_test.go b/bundle/direct/redact_test.go index 4430a0d9fee..dc77d0169b5 100644 --- a/bundle/direct/redact_test.go +++ b/bundle/direct/redact_test.go @@ -2,6 +2,7 @@ package direct import ( "encoding/json" + "maps" "testing" "github.com/databricks/cli/bundle/config" @@ -334,3 +335,25 @@ func TestResolveReferencesAfterApplyKeepsRedactedEntry(t *testing.T) { assert.Equal(t, "resolved-name", sv.Value.(*catalog.Secret).Value) assert.JSONEq(t, string(redactedJSON), string(entry.NewState.Value)) } + +// TestCheckSensitivePlanValuesKeepsPlanRefs checks that the check resolves a saved plan's references on +// copies, so the plan entry still holds the reference after the check and apply can restore it. +func TestCheckSensitivePlanValuesKeepsPlanRefs(t *testing.T) { + root := syncedRoot(t, &config.Root{Resources: config.Resources{ + Catalogs: map[string]*resources.Catalog{"c": {CreateCatalog: catalog.CreateCatalog{Name: "c"}}}, + Secrets: map[string]*resources.Secret{"s": {Secret: catalog.Secret{Name: "s", Value: "${resources.catalogs.c.name}"}}}, + }}) + wantRefs := map[string]string{ + "value": "${resources.catalogs.c.name}", + "comment": "c-${resources.catalogs.c.name}", + } + plan := deployplan.NewPlanDirect() + plan.Plan["resources.catalogs.c"] = &deployplan.PlanEntry{Action: deployplan.Skip} + plan.Plan["resources.secrets.s"] = &deployplan.PlanEntry{NewState: &structvar.StructVarJSON{ + Value: []byte(`{"name":"s","value":"[redacted]","comment":"c-${resources.catalogs.c.name}"}`), + Refs: maps.Clone(wantRefs), + }, DependsOn: []deployplan.DependsOnEntry{{Node: "resources.catalogs.c", Label: "${resources.catalogs.c.name}"}}} + + require.Empty(t, CheckSensitivePlanValues(t.Context(), root, plan)) + assert.Equal(t, wantRefs, plan.Plan["resources.secrets.s"].NewState.Refs) +} From e41a5115cfe6aa5ca0a9c05e8c2ada6da864ee85 Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Tue, 1 Dec 2026 10:45:44 +0000 Subject: [PATCH 15/17] Resolve saved plan references the way planning does A saved plan restored its sensitive references with only the sensitive fields resolved, while planning resolves every reference of every node in graph order. A reference to an unchanged resource was resolved from a remote state the apply did not have, so a chained name was sent in lower case, and a missing map key passed the check and failed after uploads and creates. The plan's remote_state now fills the remote state cache before the references are resolved, and the restored states are resolved in graph order with the same lookup planning uses. The reference resolution is shared with planning. The check resolves copies of the references, so the plan entry keeps the references it was saved with and apply can restore them. Co-authored-by: Isaac --- bundle/direct/bundle_plan.go | 185 +++++++++++++++++++++-------------- bundle/direct/redact.go | 45 +-------- 2 files changed, 114 insertions(+), 116 deletions(-) diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index 18456502c55..efc9ad83518 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -10,6 +10,7 @@ import ( "reflect" "slices" "strings" + "sync" "github.com/databricks/cli/bundle/config" "github.com/databricks/cli/bundle/config/resources" @@ -84,6 +85,8 @@ func CheckSensitivePlanValues(ctx context.Context, root *config.Root, plan *depl for resourceKey, sv := range states { b.StateCache.Store(resourceKey, sv) } + _, remoteErrs := b.planRemoteStates(plan) + errs = append(errs, remoteErrs...) // Without a state database, a reference to a resource id is left for apply, which has one. lookup := func(ctx context.Context, path *structpath.PathNode) (any, error) { if _, field := splitResourcePath(path); field.String() == "id" { @@ -91,19 +94,71 @@ func CheckSensitivePlanValues(ctx context.Context, root *config.Root, plan *depl } return b.LookupReferencePreDeploy(ctx, path) } - errs = append(errs, b.resolveAllSensitiveRefs(ctx, states, lookup)...) - return errs + return append(errs, b.resolvePlanRefs(ctx, plan, lookup)...) } -// resolveAllSensitiveRefs resolves the sensitive references of every restored state, in key order. -func (b *DeploymentBundle) resolveAllSensitiveRefs(ctx context.Context, states map[string]*structvar.StructVar, lookup referenceLookup) []error { +// planRemoteStates returns the remote state each plan entry carries, typed as its adapter reads it, and +// caches the ones planning caches: every entry but a delete. The plan keeps the JSON form it was read in. +func (b *DeploymentBundle) planRemoteStates(plan *deployplan.Plan) (map[string]any, []error) { + typedStates := make(map[string]any) var errs []error - for _, resourceKey := range slices.Sorted(maps.Keys(states)) { - rules := dresources.GetResourceConfig(config.GetResourceTypeFromKey(resourceKey)).SensitiveFields - if err := resolveSensitiveRefs(ctx, resourceKey, rules, states[resourceKey], lookup); err != nil { - errs = append(errs, err) + for _, resourceKey := range slices.Sorted(maps.Keys(plan.Plan)) { + entry := plan.Plan[resourceKey] + if entry.RemoteState == nil { + continue + } + adapter, err := b.getAdapterForKey(resourceKey) + if err != nil { + errs = append(errs, fmt.Errorf("converting plan entry %s: %w", resourceKey, err)) + continue + } + data, err := json.Marshal(entry.RemoteState) + if err != nil { + errs = append(errs, fmt.Errorf("re-serializing remote state for %s: %w", resourceKey, err)) + continue + } + // RemoteType() returns a pointer type (e.g. *AppRemote); Elem() gives + // the struct type so reflect.New produces a single pointer, not double. + typed := reflect.New(adapter.RemoteType().Elem()).Interface() + if err := json.Unmarshal(data, typed); err != nil { + errs = append(errs, fmt.Errorf("loading remote state for %s: %w", resourceKey, err)) + continue + } + typedStates[resourceKey] = typed + if entry.Action != deployplan.Delete { + b.RemoteStateCache.Store(resourceKey, typed) } } + return typedStates, errs +} + +// resolvePlanRefs resolves the references of the restored states in graph order, as CalculatePlan does +// before deploy, so a reference to a resource that has references of its own sees the resolved value. +// It returns one error per resource whose references do not resolve. +func (b *DeploymentBundle) resolvePlanRefs(ctx context.Context, plan *deployplan.Plan, lookup referenceLookup) []error { + g, err := makeGraph(plan) + if err != nil { + return []error{err} + } + var mu sync.Mutex + var errs []error + g.Run(defaultParallelism, func(resourceKey string, failedDependency *string) bool { + if failedDependency != nil { + // The dependency's error is already in errs. + return false + } + sv, ok := b.StateCache.Load(resourceKey) + if !ok { + return true + } + if _, err := resolveStateRefs(ctx, sv, lookup); err != nil { + mu.Lock() + errs = append(errs, fmt.Errorf("resource %s: %w", resourceKey, err)) + mu.Unlock() + return false + } + return true + }) return errs } @@ -128,6 +183,8 @@ func restoreSavedPlanStates(root *config.Root, plan *deployplan.Plan, adapterFor errs = append(errs, fmt.Errorf("loading plan entry %s: %w", resourceKey, err)) continue } + // The references are the plan entry's own map. Resolving them must not change the plan. + sv.Refs = maps.Clone(sv.Refs) if err := restoreSensitiveFields(adapter, resourceKey, entry.DependsOn, sv, root); err != nil { errs = append(errs, err) continue @@ -184,36 +241,20 @@ func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks. b.StateCache.Store(resourceKey, sv) } b.Plan = plan - if errs := b.resolveAllSensitiveRefs(ctx, states, b.LookupReferencePreDeploy); len(errs) > 0 { + + // Planning resolves an unchanged resource from the remote state it read, so the remote states the + // plan carries are loaded before the references are resolved. + remoteStates, errs := b.planRemoteStates(plan) + if len(errs) > 0 { return errors.Join(errs...) } - - // Eagerly parse remote state loaded from JSON: - // - RemoteState is decoded as map[string]interface{}; round-trip through the - // adapter's StateType to recover the correct typed struct so that type - // assertions in resource adapters (e.g. entry.RemoteState.(*GrantsState)) - // work identically whether the plan came from a file or from memory. - for resourceKey, entry := range plan.Plan { - if entry.RemoteState != nil { - adapter, err := b.getAdapterForKey(resourceKey) - if err != nil { - return fmt.Errorf("converting plan entry %s: %w", resourceKey, err) - } - - data, err := json.Marshal(entry.RemoteState) - if err != nil { - return fmt.Errorf("re-serializing remote state for %s: %w", resourceKey, err) - } - // RemoteType() returns a pointer type (e.g. *AppRemote); Elem() gives - // the struct type so reflect.New produces a single pointer, not double. - typed := reflect.New(adapter.RemoteType().Elem()).Interface() - if err := json.Unmarshal(data, typed); err != nil { - return fmt.Errorf("loading remote state for %s: %w", resourceKey, err) - } - entry.RemoteState = typed - } + for resourceKey, remoteState := range remoteStates { + plan.Plan[resourceKey].RemoteState = remoteState } + if errs := b.resolvePlanRefs(ctx, plan, b.LookupReferencePreDeploy); len(errs) > 0 { + return errors.Join(errs...) + } return nil } @@ -1545,8 +1586,7 @@ func (b *DeploymentBundle) LookupReferencePreDeploy(ctx context.Context, path *s if ok { return structaccess.Get(remoteState, fieldPath) } else { - // A saved plan is applied without the remote state of its targets; apply reads it. - return nil, fmt.Errorf("%w: no remote state for %q (remote-only)", errDelayed, targetResourceKey) + return nil, fmt.Errorf("internal error: no entry in remote state cache for %q (remote-only)", targetResourceKey) } } return nil, errDelayed @@ -1565,7 +1605,7 @@ func (b *DeploymentBundle) LookupReferencePreDeploy(ctx context.Context, path *s if ok { return structaccess.Get(remoteState, fieldPath) } else { - return nil, fmt.Errorf("%w: no remote state for %q", errDelayed, targetResourceKey) + return nil, fmt.Errorf("internal error: no entry in remote state cache for %q", targetResourceKey) } } @@ -1580,12 +1620,36 @@ func (b *DeploymentBundle) resolveReferences(ctx context.Context, resourceKey st return false } + lookup := b.LookupReferencePostDeploy + if isPreDeploy { + lookup = b.LookupReferencePreDeploy + } + resolved, err := resolveStateRefs(ctx, sv, lookup) + if err != nil { + logdiag.LogError(ctx, fmt.Errorf("%s: %w", errorPrefix, err)) + return false + } + + // Sync resolved values back to StructVarJSON for serialization. Only planning serializes: after + // apply the plan entries stay redacted, so the plaintext of the cache is not written back into them. + if resolved && isPreDeploy { + if err := sv.SyncToJSON(entry.NewState); err != nil { + logdiag.LogError(ctx, fmt.Errorf("%s: cannot save state: %w", errorPrefix, err)) + return false + } + } + + return true +} + +// resolveStateRefs resolves the references of sv that lookup resolves, and reports whether it resolved +// any. A delayed reference stays in place for apply; any other lookup error is returned. +func resolveStateRefs(ctx context.Context, sv *structvar.StructVar, lookup referenceLookup) (bool, error) { var resolved bool for fieldPathStr, refString := range sv.Refs { refs, ok := dynvar.NewRef(dyn.V(refString)) if !ok { - logdiag.LogError(ctx, fmt.Errorf("%s: cannot parse %q", errorPrefix, refString)) - return false + return resolved, fmt.Errorf("cannot parse %q", refString) } // References() returns one entry per occurrence, but ResolveRef substitutes @@ -1602,47 +1666,24 @@ func (b *DeploymentBundle) resolveReferences(ctx context.Context, resourceKey st ref := "${" + pathString + "}" targetPath, err := structpath.ParsePath(pathString) if err != nil { - logdiag.LogError(ctx, fmt.Errorf("%s: cannot parse reference %q: %w", errorPrefix, ref, err)) - return false + return resolved, fmt.Errorf("cannot parse reference %q: %w", ref, err) } - var value any - if isPreDeploy { - value, err = b.LookupReferencePreDeploy(ctx, targetPath) - if err != nil { - if errors.Is(err, errDelayed) { - continue - } - logdiag.LogError(ctx, fmt.Errorf("%s: cannot resolve %q: %w", errorPrefix, ref, err)) - return false - } - } else { - value, err = b.LookupReferencePostDeploy(ctx, targetPath) - if err != nil { - logdiag.LogError(ctx, fmt.Errorf("%s: cannot resolve %q: %w", errorPrefix, ref, err)) - return false - } + value, err := lookup(ctx, targetPath) + if errors.Is(err, errDelayed) { + continue } - - err = sv.ResolveRef(ref, value) if err != nil { - logdiag.LogError(ctx, fmt.Errorf("%s: cannot update %s with value of %q: %w", errorPrefix, fieldPathStr, ref, err)) - return false + return resolved, fmt.Errorf("cannot resolve %q: %w", ref, err) } - resolved = true - } - } - // Sync resolved values back to StructVarJSON for serialization. Only planning serializes: after - // apply the plan entries stay redacted, so the plaintext of the cache is not written back into them. - if resolved && isPreDeploy { - if err := sv.SyncToJSON(entry.NewState); err != nil { - logdiag.LogError(ctx, fmt.Errorf("%s: cannot save state: %w", errorPrefix, err)) - return false + if err := sv.ResolveRef(ref, value); err != nil { + return resolved, fmt.Errorf("cannot update %s with value of %q: %w", fieldPathStr, ref, err) + } + resolved = true } } - - return true + return resolved, nil } // buildPlannedState builds the typed state of a resource from its input config, with the references it diff --git a/bundle/direct/redact.go b/bundle/direct/redact.go index 53e67a07a74..8306ef75d54 100644 --- a/bundle/direct/redact.go +++ b/bundle/direct/redact.go @@ -2,7 +2,6 @@ package direct import ( "context" - "errors" "fmt" "maps" "slices" @@ -170,7 +169,7 @@ func redactPlanEntry(adapter *dresources.Adapter, entry *deployplan.PlanEntry) e // restoreSensitiveFields restores the sensitive fields of a saved plan's state, planned, from the config. // The values and their references come from buildPlannedState, as makePlan builds them. A reference // to a resource the plan does not depend on is an error, since apply would not order the resource -// before this one. The references are resolved before deploy by resolveSensitiveRefs, as planning does. +// before this one. The references are resolved before deploy by resolvePlanRefs, as planning does. func restoreSensitiveFields(adapter *dresources.Adapter, resourceKey string, dependsOn []deployplan.DependsOnEntry, planned *structvar.StructVar, root *config.Root) error { rules := dresources.GetResourceConfig(config.GetResourceTypeFromKey(resourceKey)).SensitiveFields if len(rules) == 0 { @@ -259,48 +258,6 @@ func unplannedReference(dependsOn []deployplan.DependsOnEntry, ref string) (stri // is only known after the target is deployed. type referenceLookup func(context.Context, *structpath.PathNode) (any, error) -// resolveSensitiveRefs resolves the references of sensitive fields that planning resolves before deploy, -// so the values match a plain deploy. A reference that is delayed stays in place for apply, which -// resolves it after the target is deployed. Any other lookup error stops the deploy: the value would -// otherwise be sent from a reference that does not resolve. -func resolveSensitiveRefs(ctx context.Context, resourceKey string, rules []dresources.FieldRule, sv *structvar.StructVar, lookup referenceLookup) error { - resolved := make(map[string]bool) - for _, key := range slices.Sorted(maps.Keys(sv.Refs)) { - path, err := structpath.ParsePath(key) - if err != nil { - return fmt.Errorf("resource %s: parsing reference path %q: %w", resourceKey, key, err) - } - if !isSensitivePath(rules, path) { - continue - } - r, ok := dynvar.NewRef(dyn.V(sv.Refs[key])) - if !ok { - continue - } - for _, target := range r.References() { - if resolved[target] { - continue - } - targetPath, err := structpath.ParsePath(target) - if err != nil { - return fmt.Errorf("resource %s: parsing reference %q: %w", resourceKey, target, err) - } - value, err := lookup(ctx, targetPath) - if errors.Is(err, errDelayed) { - continue - } - if err != nil { - return fmt.Errorf("resource %s: cannot resolve %q in %s: %w", resourceKey, "${"+target+"}", key, err) - } - if err := sv.ResolveRef("${"+target+"}", value); err != nil { - return fmt.Errorf("resource %s: cannot resolve %q in %s: %w", resourceKey, "${"+target+"}", key, err) - } - resolved[target] = true - } - } - return nil -} - // isZeroValue reports whether a field of a saved plan's state holds no value. func isZeroValue(v any) bool { return v == nil || v == "" From 6fbc914370722f45cce61bd9a880c779699c30fa Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Tue, 1 Dec 2026 10:57:40 +0000 Subject: [PATCH 16/17] Leave a saved plan reference to a resource without restored state to apply The restore builds state only for resources the config holds. An internal snapshot that deploy adds to the config after the plan is loaded has none, so a reference to its path failed the restore, which resolves every reference now. Apply reads such a reference from the remote state after the target is deployed, as it did before the restore resolved all references. The immutable-folder acceptance tests pin this case. Co-authored-by: Isaac --- bundle/direct/bundle_plan.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index efc9ad83518..b82b5438d5e 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -92,11 +92,22 @@ func CheckSensitivePlanValues(ctx context.Context, root *config.Root, plan *depl if _, field := splitResourcePath(path); field.String() == "id" { return nil, errDelayed } - return b.LookupReferencePreDeploy(ctx, path) + return b.restoreLookup(ctx, path) } return append(errs, b.resolvePlanRefs(ctx, plan, lookup)...) } +// restoreLookup resolves a reference from the state the restore built. A resource the restore has no +// state for is not in the config, as the internal snapshot is not before deploy adds it: its reference +// is left for apply, which reads the resource from its remote state. +func (b *DeploymentBundle) restoreLookup(ctx context.Context, path *structpath.PathNode) (any, error) { + targetResourceKey, _ := splitResourcePath(path) + if _, ok := b.StateCache.Load(targetResourceKey); !ok { + return nil, errDelayed + } + return b.LookupReferencePreDeploy(ctx, path) +} + // planRemoteStates returns the remote state each plan entry carries, typed as its adapter reads it, and // caches the ones planning caches: every entry but a delete. The plan keeps the JSON form it was read in. func (b *DeploymentBundle) planRemoteStates(plan *deployplan.Plan) (map[string]any, []error) { @@ -252,7 +263,7 @@ func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks. plan.Plan[resourceKey].RemoteState = remoteState } - if errs := b.resolvePlanRefs(ctx, plan, b.LookupReferencePreDeploy); len(errs) > 0 { + if errs := b.resolvePlanRefs(ctx, plan, b.restoreLookup); len(errs) > 0 { return errors.Join(errs...) } return nil From 483fd3301e82edb6e99257588e8a86db79ea19b6 Mon Sep 17 00:00:00 2001 From: "andrew.nester" Date: Tue, 1 Dec 2026 11:16:08 +0000 Subject: [PATCH 17/17] Refuse a saved plan reference to a resource that is no longer in the config A reference to an internal resource that the restore has no state for, such as the immutable snapshot, is left for apply, which reads it from the remote state. Any other resource that the restore has no state for is no longer in the config. Its reference used to be left for apply too, so deploy --plan uploaded the bundle files where a bundle plan with the same config fails. Such a reference now fails the check before anything is uploaded, and asks for bundle plan again. plan-restore pins the case with a secret that references a schema removed from the config after planning: deploy --plan must make no state-changing request. Co-authored-by: Isaac --- .../sensitive/plan-restore/output.txt | 31 +++++++++++++ .../variables/sensitive/plan-restore/script | 44 +++++++++++++++++++ bundle/direct/bundle_plan.go | 12 +++-- 3 files changed, 83 insertions(+), 4 deletions(-) diff --git a/acceptance/bundle/variables/sensitive/plan-restore/output.txt b/acceptance/bundle/variables/sensitive/plan-restore/output.txt index bfd0079c586..f15a7c9e844 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/output.txt +++ b/acceptance/bundle/variables/sensitive/plan-restore/output.txt @@ -311,3 +311,34 @@ Error: planning failed >>> [CLI] bundle deploy --plan .databricks/plan-props.json Error: resource resources.secrets.sec_d: cannot resolve "${resources.schemas.s.properties.missing}": properties.missing: key "missing" not found in map + +=== a schema that an unchanged secret references is removed after planning: refused before any upload or create + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.schemas.s + delete resources.secrets.sec_other + +This action will result in the deletion of the following UC schemas. Any underlying data may be lost: + delete resources.schemas.s + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default + +Destroy: 2 deleted + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/sensitive-variables/default/files... +Created schemas.s +Created secrets.sec_e +Files: 1 uploaded, 0 deleted +Resources: 2 created, 0 changed, 0 deleted, 0 unchanged + +>>> [CLI] bundle plan +Error: cannot plan resources.secrets.sec_e: cannot resolve "${resources.schemas.s.name}": internal error: resources.schemas.s: action is "delete" missing new_state + +Error: planning failed + + +>>> [CLI] bundle deploy --plan .databricks/plan-ref-schema.json +Error: resource resources.secrets.sec_e: cannot resolve "${resources.schemas.s.name}": resources.schemas.s is not in the config; run 'bundle plan' again + diff --git a/acceptance/bundle/variables/sensitive/plan-restore/script b/acceptance/bundle/variables/sensitive/plan-restore/script index 4d1af96e035..826f1acbbf4 100644 --- a/acceptance/bundle/variables/sensitive/plan-restore/script +++ b/acceptance/bundle/variables/sensitive/plan-restore/script @@ -358,3 +358,47 @@ musterr trace $CLI bundle deploy --plan .databricks/plan-props.json # Any request that changes state would be listed here. tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c 'select(.method != "GET" and .path != "/telemetry-ext") | {method, path}' cp .databricks/base.yml databricks.yml + +# The schema an unchanged secret references is removed from the config after bundle plan. The saved plan +# still has the schema as unchanged, so deploy --plan has no state to resolve the reference from: it must be +# refused before any upload or create, and bundle plan refuses the same config. +cat > .databricks/ref-schema.yml <<'EOF2' +bundle: + name: sensitive-variables + +resources: + schemas: + s: + name: MySchema + catalog_name: main + secrets: + sec_e: + name: sec_e + catalog_name: main + schema_name: default + value: ${resources.schemas.s.name} +EOF2 +cat > .databricks/ref-schema-removed.yml <<'EOF2' +bundle: + name: sensitive-variables + +resources: + secrets: + sec_e: + name: sec_e + catalog_name: main + schema_name: default + value: ${resources.schemas.s.name} +EOF2 + +title "a schema that an unchanged secret references is removed after planning: refused before any upload or create" +trace $CLI bundle destroy --auto-approve | contains.py "${SECRETS[@]}" +cp .databricks/ref-schema.yml databricks.yml +trace $CLI bundle deploy | contains.py "${SECRETS[@]}" +$CLI bundle plan -o json | contains.py "${SECRETS[@]}" > .databricks/plan-ref-schema.json +cp .databricks/ref-schema-removed.yml databricks.yml +before=$(wc -l < "$OUT_REQUESTS") +musterr trace $CLI bundle plan +musterr trace $CLI bundle deploy --plan .databricks/plan-ref-schema.json +tail -n +$((before+1)) "$OUT_REQUESTS" | jq -c 'select(.method != "GET" and .path != "/telemetry-ext") | {method, path}' +cp .databricks/base.yml databricks.yml diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index b82b5438d5e..322cdc50c4a 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -97,13 +97,17 @@ func CheckSensitivePlanValues(ctx context.Context, root *config.Root, plan *depl return append(errs, b.resolvePlanRefs(ctx, plan, lookup)...) } -// restoreLookup resolves a reference from the state the restore built. A resource the restore has no -// state for is not in the config, as the internal snapshot is not before deploy adds it: its reference -// is left for apply, which reads the resource from its remote state. +// restoreLookup resolves a reference from the state the restore built. An internal resource, such as the +// immutable snapshot that deploy adds to the config, has no restored state before deploy: its reference is +// left for apply, which reads the resource from its remote state. Any other resource the restore has no +// state for is no longer in the config, so its reference cannot be resolved as planning resolved it. func (b *DeploymentBundle) restoreLookup(ctx context.Context, path *structpath.PathNode) (any, error) { targetResourceKey, _ := splitResourcePath(path) if _, ok := b.StateCache.Load(targetResourceKey); !ok { - return nil, errDelayed + if strings.HasPrefix(config.GetResourceTypeFromKey(targetResourceKey), "internal_") { + return nil, errDelayed + } + return nil, fmt.Errorf("%s is not in the config; run 'bundle plan' again", targetResourceKey) } return b.LookupReferencePreDeploy(ctx, path) }