diff --git a/.nextchanges/bundles/7713.md b/.nextchanges/bundles/7713.md new file mode 100644 index 00000000000..e941ac34630 --- /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 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..35405bf99d9 --- /dev/null +++ b/acceptance/bundle/deploy/readplan/plan-version-2/databricks.yml @@ -0,0 +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/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..21cad6f082b --- /dev/null +++ b/acceptance/bundle/deploy/readplan/plan-version-2/output.txt @@ -0,0 +1,49 @@ + +>>> [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 +Created secrets.secret +Files: 2 uploaded, 0 deleted +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 +{ + "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 + delete resources.secrets.secret + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/test-bundle/default + +Destroy: 2 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..6057793b175 --- /dev/null +++ b/acceptance/bundle/deploy/readplan/plan-version-2/script @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 00000000000..89bd91b52e6 --- /dev/null +++ b/acceptance/bundle/deploy/readplan/plan-version-2/test.toml @@ -0,0 +1,3 @@ +RecordRequests = true +Ignore = ["tmp.plan_*.json"] +Env.BUNDLE_VAR_api_secret = "dummy-config" 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/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": { 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-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..f15a7c9e844 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-restore/output.txt @@ -0,0 +1,344 @@ + +=== 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: 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"} + +=== 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]" + } +} + +=== 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}": 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 + + +=== 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 new file mode 100644 index 00000000000..826f1acbbf4 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-restore/script @@ -0,0 +1,404 @@ +# 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 > .databricks/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 > .databricks/saved.json + +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' + +# 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 + +# 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 + +# 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/acceptance/bundle/variables/sensitive/plan-restore/test.toml b/acceptance/bundle/variables/sensitive/plan-restore/test.toml new file mode 100644 index 00000000000..b6c052af639 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan-restore/test.toml @@ -0,0 +1,5 @@ +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/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..f190193ef33 --- /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 without the sensitive variable + +>>> env -u BUNDLE_VAR_api_header [CLI] bundle deploy --plan .databricks/plan.json +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; set the variable it uses with --var or BUNDLE_VAR_ + +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..a26543c56e1 --- /dev/null +++ b/acceptance/bundle/variables/sensitive/plan/script @@ -0,0 +1,45 @@ +# 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 + +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 + +# 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" diff --git a/acceptance/test.toml b/acceptance/test.toml index 94c80ce4066..ab34e11dd93 100644 --- a/acceptance/test.toml +++ b/acceptance/test.toml @@ -87,15 +87,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/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 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) } diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index 9a3b20cebb3..322cdc50c4a 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" @@ -69,58 +70,206 @@ func ValidatePlanAgainstState(stateDB *dstate.DeploymentState, plan *deployplan. return nil } -// InitForApply initializes the DeploymentBundle for applying a pre-computed plan. -// 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 { - b.StateDB.AssertOpenedForWrite() - - err := b.init(client) +// 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, 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 err + return []error{err} + } + b := &DeploymentBundle{Adapters: adapters, Plan: plan} + states, errs := restoreSavedPlanStates(root, plan, b.getAdapterForKey) + 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" { + return nil, errDelayed + } + return b.restoreLookup(ctx, path) + } + return append(errs, b.resolvePlanRefs(ctx, plan, lookup)...) +} - // Eagerly parse plan entries loaded from JSON: - // - NewState.Value contains raw JSON bytes; parse into typed structs and cache. - // - 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 +// 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 { + 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) +} +// 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(plan.Plan)) { + entry := plan.Plan[resourceKey] + if entry.RemoteState == nil { + continue + } adapter, err := b.getAdapterForKey(resourceKey) if err != nil { - return fmt.Errorf("converting plan entry %s: %w", resourceKey, err) + 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 +} - if hasNewState { - sv, err := entry.NewState.ToStructVar(adapter.StateType()) - if err != nil { - return fmt.Errorf("loading plan entry %s: %w", resourceKey, err) - } - b.StateCache.Store(resourceKey, sv) +// 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 +} - if hasRemoteState { - 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 +// 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 || len(entry.NewState.Value) == 0 { + continue + } + adapter, err := adapterFor(resourceKey) + if err != nil { + errs = append(errs, fmt.Errorf("converting plan entry %s: %w", resourceKey, err)) + continue + } + sv, err := entry.NewState.ToStructVar(adapter.StateType()) + if err != nil { + 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 + } + 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 +} +// 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, root *config.Root) error { + b.StateDB.AssertOpenedForWrite() + + err := b.init(client) + if err != nil { + return err + } + + 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) + } b.Plan = plan + + // 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...) + } + for resourceKey, remoteState := range remoteStates { + plan.Plan[resourceKey].RemoteState = remoteState + } + + if errs := b.resolvePlanRefs(ctx, plan, b.restoreLookup); len(errs) > 0 { + return errors.Join(errs...) + } return nil } @@ -513,7 +662,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) } } } @@ -1392,7 +1541,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) } @@ -1485,12 +1635,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 @@ -1507,46 +1681,77 @@ 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) + } + + 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 resolved, nil +} - // Sync resolved values back to StructVarJSON for serialization - if resolved { - if err := sv.SyncToJSON(entry.NewState); err != nil { - logdiag.LogError(ctx, fmt.Errorf("%s: cannot save state: %w", errorPrefix, err)) - return false +// 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) } } - return true + // 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) { @@ -1609,25 +1814,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. @@ -1641,16 +1832,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 { @@ -1704,8 +1886,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()) @@ -1714,20 +1895,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..8306ef75d54 100644 --- a/bundle/direct/redact.go +++ b/bundle/direct/redact.go @@ -1,17 +1,47 @@ package direct import ( + "context" "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" + "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]" +// sensitivePaths parses the sensitive field rules of a resource type. +func sensitivePaths(rules []dresources.FieldRule) ([]*structpath.PathNode, error) { + var paths []*structpath.PathNode + 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) + } + paths = append(paths, path) + } + 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. @@ -20,13 +50,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.ResourceConfig().SensitiveFields) + if err != nil { + return err + } + for _, path := range paths { fv, err := structaccess.Get(s, path) if err != nil { continue @@ -76,13 +104,53 @@ 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. +// 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. 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) + } + redacted.Refs, err = withoutSensitiveRefs(adapter.ResourceConfig().SensitiveFields, redacted.Refs) + 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 +165,100 @@ 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 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 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 { + 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 + } + 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 + } + + state, err := buildPlannedState(adapter, resourceKey, inputConfig, root) + if err != nil { + return fmt.Errorf("resource %s: %w", resourceKey, err) + } + + for _, path := range paths { + plannedValue, err := structaccess.Get(planned.Value, path) + if err != nil { + continue + } + v, err := structaccess.Get(state.Value, path) + if err != nil { + continue + } + value, _ := v.(string) + 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 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 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 +} + +// 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) + +// 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 new file mode 100644 index 00000000000..dc77d0169b5 --- /dev/null +++ b/bundle/direct/redact_test.go @@ -0,0 +1,359 @@ +package direct + +import ( + "encoding/json" + "maps" + "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/structs/structvar" + "github.com/databricks/databricks-sdk-go/service/catalog" + "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; 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 +// 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 + planned string + configValue string + wantValue string + wantRefs map[string]string + plannedRefs map[string]string + dependsOn []deployplan.DependsOnEntry + wantErr string + }{ + { + name: "redaction marker is replaced by the config value", + resourceKey: "resources.secrets.s", + 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", + planned: "stale-plaintext", + configValue: secretLiteral, + wantValue: secretLiteral, + }, + { + name: "zero in the plan but set in the config is restored", + resourceKey: "resources.secrets.s", + planned: "", + configValue: secretLiteral, + wantValue: secretLiteral, + }, + { + name: "zero in both is skipped", + resourceKey: "resources.secrets.s", + planned: "", + configValue: "", + wantValue: "", + }, + { + name: "non-zero in the plan with an empty config value is an error", + resourceKey: "resources.secrets.s", + planned: sensitiveRedactedValue, + configValue: "", + wantErr: msgValueMissing, + }, + { + name: "non-zero in the plan with the resource missing from config is an error", + resourceKey: "resources.secrets.gone", + 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}"}, + 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", + 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) + 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 + } + require.NoError(t, err) + secret := planned.Value.(*catalog.Secret) + assert.Equal(t, tc.wantValue, secret.Value) + assert.Empty(t, secret.EffectiveValue) + if tc.wantRefs == nil { + assert.Empty(t, planned.Refs) + } else { + assert.Equal(t, tc.wantRefs, planned.Refs) + } + }) + } +} + +func TestCheckSensitivePlanValues(t *testing.T) { + sensitive := true + 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]"}`)}}, + }} + 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 + wantErr string + }{ + { + name: "plan without sensitive resources needs nothing", + root: secretRoot(t, "", variables), + plan: jobsPlan, + }, + { + name: "sensitive value set in the config passes", + root: secretRoot(t, secretLiteral, variables), + plan: secretPlan, + }, + { + name: "zero in the plan and set in the config passes", + root: secretRoot(t, secretLiteral, variables), + plan: zeroPlan, + }, + { + name: "empty config value is reported", + root: secretRoot(t, "", variables), + plan: secretPlan, + wantErr: msgValueMissing, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + errs := CheckSensitivePlanValues(t.Context(), tc.root, tc.plan) + if tc.wantErr == "" { + assert.Empty(t, errs) + return + } + require.Len(t, errs, 1) + assert.EqualError(t, errs[0], tc.wantErr) + }) + } +} + +// 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"}}, + "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(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_") + 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) { + 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(t.Context(), "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)) +} + +// 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) +} diff --git a/bundle/phases/deploy.go b/bundle/phases/deploy.go index a8e523b49ca..a04c486dd52 100644 --- a/bundle/phases/deploy.go +++ b/bundle/phases/deploy.go @@ -292,7 +292,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 c3eab53c80f..a9a4f0537eb 100644 --- a/cmd/bundle/utils/process.go +++ b/cmd/bundle/utils/process.go @@ -491,6 +491,13 @@ func ProcessBundleRet(cmd *cobra.Command, opts ProcessOptions) (b *bundle.Bundle logdiag.LogError(ctx, err) return b, stateDesc, root.ErrAlreadyPrinted } + + if errs := direct.CheckSensitivePlanValues(ctx, &b.Config, plan); len(errs) > 0 { + for _, err := range errs { + logdiag.LogError(ctx, err) + } + return b, stateDesc, root.ErrAlreadyPrinted + } } // Reject an unknown --select before PreDeployChecks and the predeploy script