Skip to content

Commit 9e897a6

Browse files
bugfix - better behavior of legacy client CLI when a static API key is set (#12)
* more logging and some doc updates * doc updates * support static API key clients for some commands in the legacy client command * formatting
1 parent 1066489 commit 9e897a6

File tree

3 files changed

+57
-15
lines changed

3 files changed

+57
-15
lines changed

src/planet_auth/auth.py

+6
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@
2121
from planet_auth.credential import Credential
2222
from planet_auth.request_authenticator import CredentialRequestAuthenticator
2323
from planet_auth.storage_utils import ObjectStorageProvider
24+
from planet_auth.logging.auth_logger import getAuthLogger
2425

26+
auth_logger = getAuthLogger()
2527

2628
# class AuthClientContextException(AuthException):
2729
# def __init__(self, **kwargs):
@@ -53,6 +55,10 @@ def __init__(
5355
Create a new auth container object with the specified auth components.
5456
Users should use one of the more friendly static initializer methods.
5557
"""
58+
auth_logger.debug(
59+
msg=f"Initializing Auth Context. Profile: {profile_name} ; Type: {type(auth_client).__name__} ; Token file: {token_file_path}"
60+
)
61+
5662
self._auth_client = auth_client
5763
self._request_authenticator = request_authenticator
5864
self._token_file_path = token_file_path

src/planet_auth_utils/commands/cli/planet_legacy_auth_cmd.py

+38-7
Original file line numberDiff line numberDiff line change
@@ -20,20 +20,35 @@
2020
FileBackedPlanetLegacyApiKey,
2121
PlanetLegacyAuthClient,
2222
PlanetLegacyAuthClientConfig,
23+
StaticApiKeyAuthClient,
24+
StaticApiKeyAuthClientConfig,
2325
)
2426

2527
from .options import opt_password, opt_sops, opt_username, opt_yes_no
2628
from .util import recast_exceptions_to_click, post_login_cmd_helper
2729

2830

29-
def _check_client_type(ctx):
31+
def _check_client_type_pllegacy(ctx):
3032
if not isinstance(ctx.obj["AUTH"].auth_client(), PlanetLegacyAuthClient):
3133
raise click.ClickException(
3234
f'"legacy" auth commands can only be used with "{PlanetLegacyAuthClientConfig.meta()["client_type"]}" type auth profiles.'
3335
f' The current profile "{ctx.obj["AUTH"].profile_name()}" is of type "{ctx.obj["AUTH"].auth_client()._auth_client_config.meta()["client_type"]}".'
3436
)
3537

3638

39+
def _check_client_type_pllegacy_or_apikey(ctx):
40+
if not (
41+
isinstance(ctx.obj["AUTH"].auth_client(), PlanetLegacyAuthClient)
42+
or isinstance(ctx.obj["AUTH"].auth_client(), StaticApiKeyAuthClient)
43+
):
44+
raise click.ClickException(
45+
"This command can only be used with "
46+
f'"{PlanetLegacyAuthClientConfig.meta()["client_type"]}" or "{StaticApiKeyAuthClientConfig.meta()["client_type"]}" '
47+
"type auth profiles. "
48+
f'The current profile "{ctx.obj["AUTH"].profile_name()}" is of type "{ctx.obj["AUTH"].auth_client()._auth_client_config.meta()["client_type"]}".'
49+
)
50+
51+
3752
@click.group("legacy", invoke_without_command=True)
3853
@click.pass_context
3954
def cmd_pllegacy(ctx):
@@ -44,7 +59,7 @@ def cmd_pllegacy(ctx):
4459
click.echo(ctx.get_help())
4560
sys.exit(0)
4661

47-
_check_client_type(ctx)
62+
_check_client_type_pllegacy(ctx)
4863

4964

5065
@cmd_pllegacy.command("login")
@@ -57,7 +72,7 @@ def cmd_pllegacy_login(ctx, username, password, sops, yes):
5772
"""
5873
Perform an initial login using Planet's legacy authentication interfaces.
5974
"""
60-
_check_client_type(ctx)
75+
_check_client_type_pllegacy(ctx)
6176
current_auth_context = ctx.obj["AUTH"]
6277
current_auth_context.login(
6378
allow_tty_prompt=True,
@@ -75,10 +90,26 @@ def cmd_pllegacy_print_api_key(ctx):
7590
"""
7691
Show the API Key used by the currently selected authentication profile.
7792
"""
78-
_check_client_type(ctx)
93+
# We also support StaticApiKeyAuthClient in some cases where the user
94+
# directly provides an API key. Such clients can use the legacy API
95+
# key, but lack the ability to obtain one. This helps in our transition
96+
# away from the legacy auth protocol.
97+
_check_client_type_pllegacy_or_apikey(ctx)
98+
99+
# Since API keys are static, we support them in the client config
100+
# and not just in the token file.
101+
if isinstance(ctx.obj["AUTH"].auth_client(), PlanetLegacyAuthClient):
102+
api_key = ctx.obj["AUTH"].auth_client().config().legacy_api_key()
103+
if api_key:
104+
print(api_key)
105+
return
106+
if isinstance(ctx.obj["AUTH"].auth_client(), StaticApiKeyAuthClient):
107+
api_key = ctx.obj["AUTH"].auth_client().config().api_key()
108+
if api_key:
109+
print(api_key)
110+
return
111+
79112
saved_token = FileBackedPlanetLegacyApiKey(api_key_file=ctx.obj["AUTH"].token_file_path())
80-
# Not using object print for API keys printing. We don't want object quoting and escaping.
81-
# print_obj(saved_token.legacy_api_key())
82113
print(saved_token.legacy_api_key())
83114

84115

@@ -89,6 +120,6 @@ def cmd_pllegacy_print_access_token(ctx):
89120
"""
90121
Show the legacy JWT currently held by the selected authentication profile.
91122
"""
92-
_check_client_type(ctx)
123+
_check_client_type_pllegacy(ctx)
93124
saved_token = FileBackedPlanetLegacyApiKey(api_key_file=ctx.obj["AUTH"].token_file_path())
94125
print(saved_token.legacy_jwt())

src/planet_auth_utils/plauth_factory.py

+13-8
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ def _init_context_from_profile(
110110
profile_name=normalized_selected_profile, overide_path=token_file_opt, save_token_file=save_token_file # type: ignore
111111
)
112112

113+
auth_logger.debug(msg=f"Initializing Auth from profile {normalized_selected_profile}")
113114
return Auth.initialize_from_config(
114115
client_config=auth_client_config,
115116
token_file=token_file_path,
@@ -143,6 +144,7 @@ def _init_context_from_oauth_svc_account(
143144
profile_name=adhoc_profile_name, overide_path=token_file_opt, save_token_file=save_token_file
144145
)
145146

147+
auth_logger.debug(msg=f"Initializing Auth for service account {m2m_realm_name}:{client_id}")
146148
plauth_context = Auth.initialize_from_config_dict(
147149
client_config=constructed_client_config_dict,
148150
token_file=token_file_path,
@@ -169,6 +171,7 @@ def _init_context_from_client_config(
169171
profile_name=profile_name, overide_path=None, save_token_file=save_token_file
170172
)
171173

174+
auth_logger.debug(msg="Initializing Auth from provided configuration")
172175
plauth_context = Auth.initialize_from_config_dict(
173176
client_config=client_config,
174177
initial_token_data=initial_token_data,
@@ -216,6 +219,7 @@ def _init_context_from_api_key(api_key: str) -> Auth:
216219
"bearer_token_prefix": PlanetLegacyRequestAuthenticator.TOKEN_PREFIX,
217220
}
218221
adhoc_profile_name = "_PL_API_KEY"
222+
auth_logger.debug(msg="Initializing Auth from API key")
219223
plauth_context = Auth.initialize_from_config_dict(
220224
client_config=constructed_client_config_dict,
221225
token_file=None,
@@ -249,18 +253,19 @@ def initialize_auth_client_context(
249253
Between built-in profiles to interactively login users, customer or third party
250254
registered OAuth clients and corresponding custom profiles that may be saved on disk,
251255
OAuth service account profiles, and static API keys, there are a number of
252-
ways to configure how an application build with this library should authenticate
253-
requests made to the service. Add to this, configration may come from explict
254-
parameters set by the user, environment variables, or configuration files, and the
255-
number of possibilities rises.
256+
ways to configure how an application built with this library should authenticate
257+
requests made to the service. Add to this configration may come from explict
258+
parameters set by the user, environment variables, configuration files, or values
259+
hard-coded by the application developer, and the number of possibilities rises.
256260
257261
This helper function is provided to help build applications with a consistent
258262
user experience when sharing auth context with the CLI. This function
259-
does not at this time support using custom storage providers.
263+
does not support using custom storage providers at this time.
260264
261-
Arguments to this function are taken to be explicitly set by the user, and are
262-
given the highest priority. Internally, the priority used for the source of
263-
any particular configuration values is, from highest to lowest priority, as follows:
265+
Arguments to this function are taken to be explicitly set by the user or
266+
application developer, and are given the highest priority. Internally, the
267+
priority used for the source of any particular configuration values is, from
268+
highest to lowest priority, as follows:
264269
- Arguments to this function.
265270
- Environment variables.
266271
- Values from configuration file.

0 commit comments

Comments
 (0)