11import abc
22import base64
3+ import dataclasses
34import functools
45import io
56import json
@@ -662,23 +663,61 @@ 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 == _DEFAULT_DEV_BUILD
696+
697+ def __str__ (self ) -> str :
698+ if self == CliVersion ():
699+ return "unknown"
700+ return f"v{ self .major } .{ self .minor } .{ self .patch } "
701+
702+
703+ # The Databricks CLI emits (Major, Minor, Patch) = (0, 0, 0) when the binary
704+ # was built without version metadata — the build-time variables stay at
705+ # their "0" string defaults.
706+ _DEFAULT_DEV_BUILD = CliVersion (0 , 0 , 0 )
707+
708+
665709class CliTokenSource (oauth .Refreshable ):
710+
666711 def __init__ (
667712 self ,
668713 cmd : List [str ],
669714 token_type_field : str ,
670715 access_token_field : str ,
671716 expiry_field : str ,
672717 disable_async : bool = True ,
673- fallback_cmd : Optional [List [str ]] = None ,
674718 ):
675719 super ().__init__ (disable_async = disable_async )
676720 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
682721 self ._token_type_field = token_type_field
683722 self ._access_token_field = access_token_field
684723 self ._expiry_field = expiry_field
@@ -713,16 +752,7 @@ def _exec_cli_command(self, cmd: List[str]) -> oauth.Token:
713752 raise IOError (f"cannot get access token: { message } " ) from e
714753
715754 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
755+ return self ._exec_cli_command (self ._cmd )
726756
727757
728758def _run_subprocess (
@@ -911,16 +941,7 @@ def __init__(self, cfg: "Config"):
911941 elif cli_path .count ("/" ) == 0 :
912942 cli_path = self .__class__ ._find_executable (cli_path )
913943
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 )
944+ cmd = self .__class__ ._resolve_cli_command (cli_path , cfg )
924945
925946 # get_scopes() defaults to ["all-apis"] when nothing is configured, which would
926947 # cause false-positive mismatches against every token that wasn't issued with
@@ -930,12 +951,11 @@ def __init__(self, cfg: "Config"):
930951 self ._host = cfg .host
931952
932953 super ().__init__ (
933- cmd = [ cli_path , * args ] ,
954+ cmd = cmd ,
934955 token_type_field = "token_type" ,
935956 access_token_field = "access_token" ,
936957 expiry_field = "expiry" ,
937958 disable_async = cfg .disable_async_token_refresh ,
938- fallback_cmd = fallback_cmd ,
939959 )
940960
941961 def refresh (self ) -> oauth .Token :
@@ -993,15 +1013,119 @@ def _validate_token_scopes(self, token: oauth.Token):
9931013 f"Scopes default to all-apis."
9941014 )
9951015
1016+ # --profile support added in CLI v0.207.1: https://github.com/databricks/cli/pull/855
1017+ _CLI_VERSION_FOR_PROFILE = CliVersion (0 , 207 , 1 )
1018+
1019+ @staticmethod
1020+ def _parse_cli_version (output : str ) -> CliVersion :
1021+ """Parse the JSON output of `databricks version --output json`.
1022+
1023+ Takes Major/Minor/Patch from the JSON's pre-parsed numeric fields. The
1024+ `Prerelease` JSON field and the `Version` string are intentionally
1025+ ignored: for our feature-gate purposes the base triple is sufficient,
1026+ and the (0, 0, 0) case already identifies the default dev build (a
1027+ CLI built without version metadata leaves these fields at their zero
1028+ defaults).
1029+
1030+ Returns CliVersion() (unknown, (-1, -1, -1)) on failure so that an
1031+ unparseable version disables every feature gate.
1032+ """
1033+ try :
1034+ data = json .loads (output )
1035+ return CliVersion (
1036+ int (data ["Major" ]),
1037+ int (data ["Minor" ]),
1038+ int (data ["Patch" ]),
1039+ )
1040+ except (json .JSONDecodeError , KeyError , TypeError , ValueError ) as e :
1041+ logger .debug (f"Failed to parse Databricks CLI version from output: { output !r} ({ e } )" )
1042+ return CliVersion ()
1043+
1044+ @staticmethod
1045+ def _get_cli_version (cli_path : str ) -> CliVersion :
1046+ """Run `databricks version --output json` and return the parsed CliVersion.
1047+
1048+ Returns CliVersion() on failure.
1049+ """
1050+ try :
1051+ out = _run_subprocess (
1052+ [cli_path , "version" , "--output" , "json" ],
1053+ capture_output = True ,
1054+ check = True ,
1055+ )
1056+ return DatabricksCliTokenSource ._parse_cli_version (out .stdout .decode ())
1057+ except Exception as e :
1058+ logger .warning (f"Failed to detect Databricks CLI version: { e } . " "Falling back to conservative flag set." )
1059+ return CliVersion ()
1060+
1061+ @staticmethod
1062+ def _resolve_cli_command (cli_path : str , cfg : "Config" ) -> List [str ]:
1063+ """Detect CLI version and build the auth-token command.
1064+
1065+ Raises ValueError with a precise message when no usable command can be
1066+ built (missing profile/host, or --profile-unsupported CLI with no host
1067+ fallback configured).
1068+ """
1069+ version = DatabricksCliTokenSource ._get_cli_version (cli_path )
1070+ if version .is_default_dev_build :
1071+ # A default-marker dev build has no injected version, so every
1072+ # feature gate fails via at_least. Surface an informational hint so
1073+ # users know why their feature flags aren't taking effect.
1074+ logger .info (
1075+ f"Databricks CLI { version } is a development build; feature detection will use "
1076+ "conservative fallbacks. Rebuild the CLI with an explicit version to enable "
1077+ "capability-based flag selection."
1078+ )
1079+ try :
1080+ return DatabricksCliTokenSource ._build_cli_command (cli_path , cfg , version )
1081+ except ValueError as e :
1082+ raise ValueError (f"cannot configure CLI token source: { e } " ) from e
1083+
1084+ @staticmethod
1085+ def _build_cli_command (cli_path : str , cfg : "Config" , version : CliVersion ) -> List [str ]:
1086+ """Build the `auth token` command.
1087+
1088+ Falls back to --host when --profile is either not configured or not
1089+ supported by the installed CLI. Raises ValueError describing which
1090+ piece of configuration is missing when no command can be built.
1091+ """
1092+ if not cfg .profile :
1093+ try :
1094+ return DatabricksCliTokenSource ._build_host_command (cli_path , cfg )
1095+ except ValueError as e :
1096+ raise ValueError (f"neither profile nor host is configured: { e } " ) from e
1097+
1098+ # Flag --profile is a global CLI flag and is recognized for all
1099+ # commands even the ones that do not support it. Only use --profile
1100+ # in CLI versions that are known to support it in `auth token`.
1101+ if version < DatabricksCliTokenSource ._CLI_VERSION_FOR_PROFILE :
1102+ logger .warning (
1103+ f"Databricks CLI { version } does not support --profile "
1104+ f"(requires >= { DatabricksCliTokenSource ._CLI_VERSION_FOR_PROFILE } ). "
1105+ "Falling back to --host."
1106+ )
1107+ try :
1108+ return DatabricksCliTokenSource ._build_host_command (cli_path , cfg )
1109+ except ValueError as e :
1110+ raise ValueError (
1111+ f"Databricks CLI { version } does not support --profile "
1112+ f"(requires >= { DatabricksCliTokenSource ._CLI_VERSION_FOR_PROFILE } ) "
1113+ f"and no host fallback is configured: { e } "
1114+ ) from e
1115+
1116+ return [cli_path , "auth" , "token" , "--profile" , cfg .profile ]
1117+
9961118 @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.
1119+ def _build_host_command (cli_path : str , cfg : "Config" ) -> List [str ]:
1120+ """Build the --host based auth token command. Raises when cfg.host is unset."""
1121+ if not cfg .host :
1122+ raise ValueError ("host is not set" )
1123+ cmd = [cli_path , "auth" , "token" , "--host" , cfg .host ]
1124+ # Older Databricks CLIs need --account-id for account-scoped calls;
1125+ # unified hosts don't use this path.
10021126 if cfg .client_type == ClientType .ACCOUNT :
1003- args += ["--account-id" , cfg .account_id ]
1004- return args
1127+ cmd += ["--account-id" , cfg .account_id ]
1128+ return cmd
10051129
10061130 @staticmethod
10071131 def _find_executable (name ) -> str :
0 commit comments