Skip to content

Commit 9950b72

Browse files
Fix CLI token source --profile fallback with version detection
Replace the broken error-based --profile detection with version-based CLI detection at init time. The --profile flag is a global Cobra flag that old CLIs (< v0.207.1) silently accept instead of reporting "unknown flag: --profile", making the previous --host fallback dead code. The SDK now runs `databricks version` at init time, parses the semver, and uses it to decide between --profile and --host. If version detection fails, the SDK falls back to --host (most conservative command). This also simplifies CliTokenSource to hold a single cmd with no runtime fallback logic, and enables future version-gated flags (e.g. --force-refresh) without additional subprocess calls. See: databricks/cli#855
1 parent baa3b63 commit 9950b72

3 files changed

Lines changed: 368 additions & 195 deletions

File tree

NEXT_CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@
77
### Security
88

99
### Bug Fixes
10+
* Fixed Databricks CLI `--profile` fallback by detecting the CLI version at init time. The previous error-based detection was broken because `--profile` is a global Cobra flag silently accepted by old CLIs.
1011

1112
### Documentation
1213

1314
### Breaking Changes
1415

1516
### Internal Changes
17+
* Detect Databricks CLI version at init time via `databricks version`, enabling version-gated flag support (e.g. `--force-refresh`) without additional subprocess calls.
1618

1719
### API Changes

databricks/sdk/credentials_provider.py

Lines changed: 160 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
import abc
22
import base64
3+
import dataclasses
34
import functools
45
import io
56
import json
67
import logging
78
import os
89
import pathlib
910
import platform
11+
import re
1012
import subprocess
1113
import sys
1214
import threading
@@ -662,23 +664,61 @@ def refreshed_headers() -> Dict[str, str]:
662664
return OAuthCredentialsProvider(refreshed_headers, token)
663665

664666

667+
@dataclasses.dataclass(order=True)
668+
class CliVersion:
669+
"""Semver version triple of the Databricks CLI.
670+
671+
Three sentinel states in the (major, minor, patch) tuple:
672+
* `(-1, -1, -1)` — the default, meaning version detection failed. It
673+
compares less than every real release so every feature gate fails.
674+
* `(0, 0, 0)` — the CLI's default dev build, emitted when the binary
675+
was built without version metadata. See `is_default_dev_build`.
676+
* anything else — a real CLI version.
677+
678+
Prerelease tags (e.g. "-rc.1", "-dev+commit") are deliberately ignored:
679+
for our purposes the base triple is sufficient, and feature gates are
680+
release-based so a prerelease of a version with a flag is assumed to
681+
have the flag too.
682+
"""
683+
684+
major: int = -1
685+
minor: int = -1
686+
patch: int = -1
687+
688+
@property
689+
def is_default_dev_build(self) -> bool:
690+
"""True when the CLI reports (0, 0, 0), i.e. its default dev build.
691+
692+
Narrowly matches the CLI's "no version injected" marker: its version
693+
metadata stays at the zero defaults. A version the user explicitly
694+
set (e.g. v1.0.0-dev) is intentional and is not flagged here.
695+
"""
696+
return self == _DEFAULT_DEV_BUILD
697+
698+
def __str__(self) -> str:
699+
if self == CliVersion():
700+
return "unknown"
701+
return f"v{self.major}.{self.minor}.{self.patch}"
702+
703+
704+
# The Databricks CLI emits (Major, Minor, Patch) = (0, 0, 0) when the binary
705+
# was built without version metadata — the build-time variables stay at
706+
# their "0" string defaults.
707+
_DEFAULT_DEV_BUILD = CliVersion(0, 0, 0)
708+
709+
665710
class CliTokenSource(oauth.Refreshable):
711+
666712
def __init__(
667713
self,
668714
cmd: List[str],
669715
token_type_field: str,
670716
access_token_field: str,
671717
expiry_field: str,
672718
disable_async: bool = True,
673-
fallback_cmd: Optional[List[str]] = None,
674719
):
675720
super().__init__(disable_async=disable_async)
676721
self._cmd = cmd
677-
# fallback_cmd is tried when the primary command fails with "unknown flag: --profile",
678-
# indicating the CLI is too old to support --profile. Can be removed once support
679-
# for CLI versions predating --profile is dropped.
680-
# See: https://github.com/databricks/databricks-sdk-go/pull/1497
681-
self._fallback_cmd = fallback_cmd
682722
self._token_type_field = token_type_field
683723
self._access_token_field = access_token_field
684724
self._expiry_field = expiry_field
@@ -713,16 +753,7 @@ def _exec_cli_command(self, cmd: List[str]) -> oauth.Token:
713753
raise IOError(f"cannot get access token: {message}") from e
714754

715755
def refresh(self) -> oauth.Token:
716-
try:
717-
return self._exec_cli_command(self._cmd)
718-
except IOError as e:
719-
if self._fallback_cmd is not None and "unknown flag: --profile" in str(e):
720-
logger.warning(
721-
"Databricks CLI does not support --profile flag. Falling back to --host. "
722-
"Please upgrade your CLI to the latest version."
723-
)
724-
return self._exec_cli_command(self._fallback_cmd)
725-
raise
756+
return self._exec_cli_command(self._cmd)
726757

727758

728759
def _run_subprocess(
@@ -911,16 +942,7 @@ def __init__(self, cfg: "Config"):
911942
elif cli_path.count("/") == 0:
912943
cli_path = self.__class__._find_executable(cli_path)
913944

914-
fallback_cmd = None
915-
if cfg.profile:
916-
# When profile is set, use --profile as the primary command.
917-
# The profile contains the full config (host, account_id, etc.).
918-
args = ["auth", "token", "--profile", cfg.profile]
919-
# Build a --host fallback for older CLIs that don't support --profile.
920-
if cfg.host:
921-
fallback_cmd = [cli_path, *self.__class__._build_host_args(cfg)]
922-
else:
923-
args = self.__class__._build_host_args(cfg)
945+
cmd = self.__class__._resolve_cli_command(cli_path, cfg)
924946

925947
# get_scopes() defaults to ["all-apis"] when nothing is configured, which would
926948
# cause false-positive mismatches against every token that wasn't issued with
@@ -930,12 +952,11 @@ def __init__(self, cfg: "Config"):
930952
self._host = cfg.host
931953

932954
super().__init__(
933-
cmd=[cli_path, *args],
955+
cmd=cmd,
934956
token_type_field="token_type",
935957
access_token_field="access_token",
936958
expiry_field="expiry",
937959
disable_async=cfg.disable_async_token_refresh,
938-
fallback_cmd=fallback_cmd,
939960
)
940961

941962
def refresh(self) -> oauth.Token:
@@ -993,15 +1014,119 @@ def _validate_token_scopes(self, token: oauth.Token):
9931014
f"Scopes default to all-apis."
9941015
)
9951016

1017+
# --profile support added in CLI v0.207.1: https://github.com/databricks/cli/pull/855
1018+
_CLI_VERSION_FOR_PROFILE = CliVersion(0, 207, 1)
1019+
1020+
@staticmethod
1021+
def _parse_cli_version(output: str) -> CliVersion:
1022+
"""Parse the JSON output of `databricks version --output json`.
1023+
1024+
Takes Major/Minor/Patch from the JSON's pre-parsed numeric fields. The
1025+
`Prerelease` JSON field and the `Version` string are intentionally
1026+
ignored: for our feature-gate purposes the base triple is sufficient,
1027+
and the (0, 0, 0) case already identifies the default dev build (a
1028+
CLI built without version metadata leaves these fields at their zero
1029+
defaults).
1030+
1031+
Returns CliVersion() (unknown, (-1, -1, -1)) on failure so that an
1032+
unparseable version disables every feature gate.
1033+
"""
1034+
try:
1035+
data = json.loads(output)
1036+
return CliVersion(
1037+
int(data["Major"]),
1038+
int(data["Minor"]),
1039+
int(data["Patch"]),
1040+
)
1041+
except (json.JSONDecodeError, KeyError, TypeError, ValueError) as e:
1042+
logger.debug(f"Failed to parse Databricks CLI version from output: {output!r} ({e})")
1043+
return CliVersion()
1044+
1045+
@staticmethod
1046+
def _get_cli_version(cli_path: str) -> CliVersion:
1047+
"""Run `databricks version --output json` and return the parsed CliVersion.
1048+
1049+
Returns CliVersion() on failure.
1050+
"""
1051+
try:
1052+
out = _run_subprocess(
1053+
[cli_path, "version", "--output", "json"],
1054+
capture_output=True,
1055+
check=True,
1056+
)
1057+
return DatabricksCliTokenSource._parse_cli_version(out.stdout.decode())
1058+
except Exception as e:
1059+
logger.warning(f"Failed to detect Databricks CLI version: {e}. " "Falling back to conservative flag set.")
1060+
return CliVersion()
1061+
1062+
@staticmethod
1063+
def _resolve_cli_command(cli_path: str, cfg: "Config") -> List[str]:
1064+
"""Detect CLI version and build the auth-token command.
1065+
1066+
Raises ValueError with a precise message when no usable command can be
1067+
built (missing profile/host, or --profile-unsupported CLI with no host
1068+
fallback configured).
1069+
"""
1070+
version = DatabricksCliTokenSource._get_cli_version(cli_path)
1071+
if version.is_default_dev_build:
1072+
# A default-marker dev build has no injected version, so every
1073+
# feature gate fails via at_least. Surface an informational hint so
1074+
# users know why their feature flags aren't taking effect.
1075+
logger.info(
1076+
f"Databricks CLI {version} is a development build; feature detection will use "
1077+
"conservative fallbacks. Rebuild the CLI with an explicit version to enable "
1078+
"capability-based flag selection."
1079+
)
1080+
try:
1081+
return DatabricksCliTokenSource._build_cli_command(cli_path, cfg, version)
1082+
except ValueError as e:
1083+
raise ValueError(f"cannot configure CLI token source: {e}") from e
1084+
1085+
@staticmethod
1086+
def _build_cli_command(cli_path: str, cfg: "Config", version: CliVersion) -> List[str]:
1087+
"""Build the `auth token` command.
1088+
1089+
Falls back to --host when --profile is either not configured or not
1090+
supported by the installed CLI. Raises ValueError describing which
1091+
piece of configuration is missing when no command can be built.
1092+
"""
1093+
if not cfg.profile:
1094+
try:
1095+
return DatabricksCliTokenSource._build_host_command(cli_path, cfg)
1096+
except ValueError as e:
1097+
raise ValueError(f"neither profile nor host is configured: {e}") from e
1098+
1099+
# Flag --profile is a global CLI flag and is recognized for all
1100+
# commands even the ones that do not support it. Only use --profile
1101+
# in CLI versions that are known to support it in `auth token`.
1102+
if version < DatabricksCliTokenSource._CLI_VERSION_FOR_PROFILE:
1103+
logger.warning(
1104+
f"Databricks CLI {version} does not support --profile "
1105+
f"(requires >= {DatabricksCliTokenSource._CLI_VERSION_FOR_PROFILE}). "
1106+
"Falling back to --host."
1107+
)
1108+
try:
1109+
return DatabricksCliTokenSource._build_host_command(cli_path, cfg)
1110+
except ValueError as e:
1111+
raise ValueError(
1112+
f"Databricks CLI {version} does not support --profile "
1113+
f"(requires >= {DatabricksCliTokenSource._CLI_VERSION_FOR_PROFILE}) "
1114+
f"and no host fallback is configured: {e}"
1115+
) from e
1116+
1117+
return [cli_path, "auth", "token", "--profile", cfg.profile]
1118+
9961119
@staticmethod
997-
def _build_host_args(cfg: "Config") -> List[str]:
998-
"""Build CLI arguments using --host (legacy path)."""
999-
args = ["auth", "token", "--host", cfg.host]
1000-
# This is here to support older versions of the Databricks CLI, so we need to keep the client type check.
1001-
# This won't work for unified hosts, but it is not supposed to.
1120+
def _build_host_command(cli_path: str, cfg: "Config") -> List[str]:
1121+
"""Build the --host based auth token command. Raises when cfg.host is unset."""
1122+
if not cfg.host:
1123+
raise ValueError("host is not set")
1124+
cmd = [cli_path, "auth", "token", "--host", cfg.host]
1125+
# Older Databricks CLIs need --account-id for account-scoped calls;
1126+
# unified hosts don't use this path.
10021127
if cfg.client_type == ClientType.ACCOUNT:
1003-
args += ["--account-id", cfg.account_id]
1004-
return args
1128+
cmd += ["--account-id", cfg.account_id]
1129+
return cmd
10051130

10061131
@staticmethod
10071132
def _find_executable(name) -> str:

0 commit comments

Comments
 (0)