11import abc
22import base64
3+ import dataclasses
34import functools
45import io
56import json
@@ -662,23 +663,57 @@ def refreshed_headers() -> Dict[str, str]:
662663 return OAuthCredentialsProvider (refreshed_headers , token )
663664
664665
666+ @dataclasses .dataclass (order = True )
667+ class CliVersion :
668+ """Semver version triple of the Databricks CLI.
669+
670+ Three sentinel states in the (major, minor, patch) tuple:
671+ * `(-1, -1, -1)` — the default, meaning version detection failed. It
672+ compares less than every real release so every feature gate fails.
673+ * `(0, 0, 0)` — the CLI's default dev build, emitted when the binary
674+ was built without version metadata. See `is_default_dev_build`.
675+ * anything else — a real CLI version.
676+
677+ Prerelease tags (e.g. "-rc.1", "-dev+commit") are deliberately ignored:
678+ for our purposes the base triple is sufficient, and feature gates are
679+ release-based so a prerelease of a version with a flag is assumed to
680+ have the flag too.
681+ """
682+
683+ major : int = - 1
684+ minor : int = - 1
685+ patch : int = - 1
686+
687+ @property
688+ def is_default_dev_build (self ) -> bool :
689+ """True when the CLI reports (0, 0, 0), i.e. its default dev build.
690+
691+ Narrowly matches the CLI's "no version injected" marker: its version
692+ metadata stays at the zero defaults. A version the user explicitly
693+ set (e.g. v1.0.0-dev) is intentional and is not flagged here.
694+ """
695+ return (self .major , self .minor , self .patch ) == (0 , 0 , 0 )
696+
697+ def __str__ (self ) -> str :
698+ if self == CliVersion ():
699+ return "unknown"
700+ if self .is_default_dev_build :
701+ return "v0.0.0-dev"
702+ return f"v{ self .major } .{ self .minor } .{ self .patch } "
703+
704+
665705class CliTokenSource (oauth .Refreshable ):
706+
666707 def __init__ (
667708 self ,
668709 cmd : List [str ],
669710 token_type_field : str ,
670711 access_token_field : str ,
671712 expiry_field : str ,
672713 disable_async : bool = True ,
673- fallback_cmd : Optional [List [str ]] = None ,
674714 ):
675715 super ().__init__ (disable_async = disable_async )
676716 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
682717 self ._token_type_field = token_type_field
683718 self ._access_token_field = access_token_field
684719 self ._expiry_field = expiry_field
@@ -713,16 +748,7 @@ def _exec_cli_command(self, cmd: List[str]) -> oauth.Token:
713748 raise IOError (f"cannot get access token: { message } " ) from e
714749
715750 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
751+ return self ._exec_cli_command (self ._cmd )
726752
727753
728754def _run_subprocess (
@@ -889,6 +915,37 @@ def inner() -> Dict[str, str]:
889915 return inner
890916
891917
918+ @functools .lru_cache (maxsize = 8 )
919+ def _get_cli_version (cli_path : str ) -> "CliVersion" :
920+ """Run `databricks version --output json` and return the parsed CliVersion.
921+
922+ Cached by `cli_path` for the Python process lifetime: the installed binary's
923+ version is immutable during the process, and the credential chain may
924+ instantiate DatabricksCliTokenSource many times (per WorkspaceClient, per
925+ request in some patterns). Without the cache, every construction would
926+ re-fork `databricks version`.
927+
928+ The 5-second timeout prevents a hung CLI (first-run disk scan, antivirus,
929+ stdin wait) from wedging SDK init indefinitely; TimeoutExpired is caught
930+ by the generic handler and falls through to CliVersion().
931+
932+ Returns CliVersion() on any failure.
933+ """
934+ try :
935+ out = _run_subprocess (
936+ [cli_path , "version" , "--output" , "json" ],
937+ capture_output = True ,
938+ check = True ,
939+ timeout = 5 ,
940+ )
941+ return DatabricksCliTokenSource ._parse_cli_version (out .stdout .decode ())
942+ except Exception as e :
943+ logger .warning (
944+ f"Failed to detect Databricks CLI version: { e } . Falling back to conservative flag set."
945+ )
946+ return CliVersion ()
947+
948+
892949class DatabricksCliTokenSource (CliTokenSource ):
893950 """Obtain the token granted by `databricks auth login` CLI command"""
894951
@@ -911,16 +968,7 @@ def __init__(self, cfg: "Config"):
911968 elif cli_path .count ("/" ) == 0 :
912969 cli_path = self .__class__ ._find_executable (cli_path )
913970
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 )
971+ cmd = self .__class__ ._resolve_cli_command (cli_path , cfg )
924972
925973 # get_scopes() defaults to ["all-apis"] when nothing is configured, which would
926974 # cause false-positive mismatches against every token that wasn't issued with
@@ -930,12 +978,11 @@ def __init__(self, cfg: "Config"):
930978 self ._host = cfg .host
931979
932980 super ().__init__ (
933- cmd = [ cli_path , * args ] ,
981+ cmd = cmd ,
934982 token_type_field = "token_type" ,
935983 access_token_field = "access_token" ,
936984 expiry_field = "expiry" ,
937985 disable_async = cfg .disable_async_token_refresh ,
938- fallback_cmd = fallback_cmd ,
939986 )
940987
941988 def refresh (self ) -> oauth .Token :
@@ -993,15 +1040,114 @@ def _validate_token_scopes(self, token: oauth.Token):
9931040 f"Scopes default to all-apis."
9941041 )
9951042
1043+ # --profile support added in CLI v0.207.1: https://github.com/databricks/cli/pull/855
1044+ _CLI_VERSION_FOR_PROFILE = CliVersion (0 , 207 , 1 )
1045+
1046+ @staticmethod
1047+ def _parse_cli_version (output : str ) -> CliVersion :
1048+ """Parse the JSON output of `databricks version --output json`.
1049+
1050+ Takes Major/Minor/Patch from the JSON's pre-parsed numeric fields. The
1051+ `Prerelease` JSON field and the `Version` string are intentionally
1052+ ignored: for our feature-gate purposes the base triple is sufficient,
1053+ and the (0, 0, 0) case already identifies the default dev build (a
1054+ CLI built without version metadata leaves these fields at their zero
1055+ defaults).
1056+
1057+ Returns CliVersion() (unknown, (-1, -1, -1)) on failure so that an
1058+ unparseable version disables every feature gate.
1059+ """
1060+ try :
1061+ data = json .loads (output )
1062+ return CliVersion (
1063+ int (data ["Major" ]),
1064+ int (data ["Minor" ]),
1065+ int (data ["Patch" ]),
1066+ )
1067+ except (json .JSONDecodeError , KeyError , TypeError , ValueError ) as e :
1068+ logger .debug (f"Failed to parse Databricks CLI version from output: { output !r} ({ e } )" )
1069+ return CliVersion ()
1070+
1071+ @staticmethod
1072+ def _resolve_cli_command (cli_path : str , cfg : "Config" ) -> List [str ]:
1073+ """Detect CLI version and build the auth-token command.
1074+
1075+ Raises IOError with a precise message when no usable command can be
1076+ built (missing profile/host, or --profile-unsupported CLI with no host
1077+ fallback configured). IOError matches the exception type already
1078+ handled by the `databricks_cli()` credential-chain strategy, so
1079+ graceful-skip behaviour is preserved.
1080+ """
1081+ version = _get_cli_version (cli_path )
1082+ if version .is_default_dev_build :
1083+ # A default-marker dev build has no injected version, so every
1084+ # feature gate fails via at_least. Surface an informational hint so
1085+ # users know why their feature flags aren't taking effect.
1086+ logger .info (
1087+ f"Databricks CLI { version } is a development build; feature detection will use "
1088+ "conservative fallbacks. Rebuild the CLI with an explicit version to enable "
1089+ "capability-based flag selection."
1090+ )
1091+ try :
1092+ return DatabricksCliTokenSource ._build_cli_command (cli_path , cfg , version )
1093+ except IOError as e :
1094+ raise IOError (f"cannot configure CLI token source: { e } " ) from e
1095+
1096+ @staticmethod
1097+ def _build_cli_command (cli_path : str , cfg : "Config" , version : CliVersion ) -> List [str ]:
1098+ """Build the `auth token` command.
1099+
1100+ Falls back to --host when --profile is either not configured or not
1101+ supported by the installed CLI. Raises IOError describing which
1102+ piece of configuration is missing when no command can be built.
1103+ """
1104+ if not cfg .profile :
1105+ try :
1106+ return DatabricksCliTokenSource ._build_host_command (cli_path , cfg )
1107+ except IOError as e :
1108+ raise IOError (f"neither profile nor host is configured: { e } " ) from e
1109+
1110+ # Flag --profile is a global flag and is recognized for all
1111+ # commands even the ones that do not support it. Only use --profile
1112+ # in CLI versions that are known to support it in `auth token`.
1113+ if version < DatabricksCliTokenSource ._CLI_VERSION_FOR_PROFILE :
1114+ # For the unknown (detection failed) and dev-build (no version
1115+ # metadata) cases we can't actually prove the CLI lacks --profile;
1116+ # we just failed to confirm it. Log accordingly.
1117+ if version == CliVersion () or version .is_default_dev_build :
1118+ logger .warning (
1119+ f"Could not confirm --profile support for Databricks CLI { version } "
1120+ f"(requires >= { DatabricksCliTokenSource ._CLI_VERSION_FOR_PROFILE } ). "
1121+ "Falling back to --host."
1122+ )
1123+ else :
1124+ logger .warning (
1125+ f"Databricks CLI { version } does not support --profile "
1126+ f"(requires >= { DatabricksCliTokenSource ._CLI_VERSION_FOR_PROFILE } ). "
1127+ "Falling back to --host."
1128+ )
1129+ try :
1130+ return DatabricksCliTokenSource ._build_host_command (cli_path , cfg )
1131+ except IOError as e :
1132+ raise IOError (
1133+ f"Databricks CLI { version } does not support --profile "
1134+ f"(requires >= { DatabricksCliTokenSource ._CLI_VERSION_FOR_PROFILE } ) "
1135+ f"and no host fallback is configured: { e } "
1136+ ) from e
1137+
1138+ return [cli_path , "auth" , "token" , "--profile" , cfg .profile ]
1139+
9961140 @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.
1141+ def _build_host_command (cli_path : str , cfg : "Config" ) -> List [str ]:
1142+ """Build the --host based auth token command. Raises when cfg.host is unset."""
1143+ if not cfg .host :
1144+ raise IOError ("host is not set" )
1145+ cmd = [cli_path , "auth" , "token" , "--host" , cfg .host ]
1146+ # Older Databricks CLIs need --account-id for account-scoped calls;
1147+ # unified hosts don't use this path.
10021148 if cfg .client_type == ClientType .ACCOUNT :
1003- args += ["--account-id" , cfg .account_id ]
1004- return args
1149+ cmd += ["--account-id" , cfg .account_id ]
1150+ return cmd
10051151
10061152 @staticmethod
10071153 def _find_executable (name ) -> str :
0 commit comments