Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added globus auth scope show command #1077

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions changelog.d/20250130_222824_derek_scope_show.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

### Enhancements

* Added a new command to display auth scope information: `globus auth scope show`.

*The "globus auth" command tree is hidden until more commands are added.*
1 change: 1 addition & 0 deletions src/globus_cli/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
@main_group(
lazy_subcommands={
"api": ("api", "api_command"),
"auth": ("auth", "auth_command"),
"bookmark": ("bookmark", "bookmark_command"),
"cli-profile-list": ("cli_profile_list", "cli_profile_list"),
"collection": ("collection", "collection_command"),
Expand Down
13 changes: 13 additions & 0 deletions src/globus_cli/commands/auth/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from globus_cli.parsing import group


@group(
"auth",
lazy_subcommands={
"scope": (".scope", "scope_command"),
},
# TODO - Make the auth command public once we have >= 5 subcommands
hidden=True,
)
def auth_command() -> None:
"""Interact with the Globus Auth service."""
11 changes: 11 additions & 0 deletions src/globus_cli/commands/auth/scope/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from globus_cli.parsing import group


@group(
"scope",
lazy_subcommands={
"show": (".show", "show_command"),
},
)
def scope_command() -> None:
"""Interact with a scope in the Globus Auth service."""
83 changes: 83 additions & 0 deletions src/globus_cli/commands/auth/scope/_common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from __future__ import annotations

import globus_sdk

from globus_cli.termio import Field, formatters

SCOPE_SUMMARY_FIELDS = [
Field("Scope ID", "scope"),
Field("Optional", "optional", formatter=formatters.Bool),
Field(
"Requires Refresh Token", "requires_refresh_token", formatter=formatters.Bool
),
]

DECORATED_SCOPE_SUMMARY_FIELDS = [
# Scope summaries don't actually contain a "scope_string" field
# But it's very useful to understanding a dependent scope, so we decorate it in.
Field("Scope String", "scope_string"),
] + SCOPE_SUMMARY_FIELDS

_BASE_SCOPE_FIELDS = [
Field("Scope String", "scope_string"),
Field("Scope ID", "id"),
Field("Name", "name"),
Field("Description", "description", wrap_enabled=True),
Field("Client ID", "client"),
Field("Allows Refresh Tokens", "allows_refresh_token", formatter=formatters.Bool),
Field("Required Domains", "required_domains", formatter=formatters.Array),
Field("Advertised", "advertised", formatter=formatters.Bool),
]

DECORATED_SCOPE_FIELDS = _BASE_SCOPE_FIELDS + [
Field(
"Dependent Scopes",
"dependent_scopes",
formatter=formatters.ArrayMultilineFormatter(
formatters.RecordFormatter(DECORATED_SCOPE_SUMMARY_FIELDS)
),
),
]


class BatchScopeStringResolver:
"""
A resolver for accessing multiple scope strings without making multiple requests.

The list of scopes ids, provided at initialization, are queried in a batch request
and cached for future access once the first scope string is resolved.

:param auth_client: The AuthClient to use for scope string resolution.
:param scope_ids: A list of scope IDs to resolve.
:param default: A default string to return in case a scope id couldn't be found.
"""

def __init__(
self,
auth_client: globus_sdk.AuthClient,
scope_ids: list[str],
default: str | None = "UNKNOWN",
) -> None:
self._auth_client = auth_client
self._scope_ids = scope_ids
self._scope_strings: dict[str, str] | None = None
self._default = default

def resolve(self, scope_id: str) -> str:
if scope_id not in self._scope_ids:
raise ValueError(f"Scope ID {scope_id} was not registered for resolution.")
elif scope_id not in self.scope_strings:
if self._default is not None:
return self._default
raise ValueError(f"Scope string for {scope_id} could not be retrieved.")
return self.scope_strings[scope_id]

@property
def scope_strings(self) -> dict[str, str]:
"""A mapping of scope ID to their scope strings."""
if self._scope_strings is None:
resp = self._auth_client.get_scopes(ids=self._scope_ids)
self._scope_strings = {
scope["id"]: scope["scope_string"] for scope in resp.get("scopes", [])
}
return self._scope_strings
78 changes: 78 additions & 0 deletions src/globus_cli/commands/auth/scope/show.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
from __future__ import annotations

import functools
import typing as t

import click
import globus_sdk

from globus_cli.login_manager import LoginManager
from globus_cli.parsing import command
from globus_cli.termio import display
from globus_cli.utils import LazyDict, is_uuid

from ._common import DECORATED_SCOPE_FIELDS, BatchScopeStringResolver


@command("show")
@click.argument("SCOPE_ID_OR_STRING", type=str)
@LoginManager.requires_login("auth")
def show_command(login_manager: LoginManager, *, scope_id_or_string: str) -> None:
"""Show a scope by ID or string."""
auth_client = login_manager.get_auth_client()

if is_uuid(scope_id_or_string):
show_scope_by_id(auth_client, scope_id_or_string)
else:
show_scope_by_string(auth_client, scope_id_or_string)


def show_scope_by_id(auth_client: globus_sdk.AuthClient, scope_id: str) -> None:
scope_resp = auth_client.get_scope(scope_id)

decorate_scope_response(auth_client, scope_resp["scope"])

display(
scope_resp,
text_mode=display.RECORD,
fields=DECORATED_SCOPE_FIELDS,
response_key="scope",
)


def show_scope_by_string(auth_client: globus_sdk.AuthClient, scope_string: str) -> None:
scope_resp = auth_client.get_scopes(scope_strings=[scope_string])

decorate_scope_response(auth_client, scope_resp["scopes"][0])

display(
scope_resp,
text_mode=display.RECORD,
fields=DECORATED_SCOPE_FIELDS,
response_key=lambda resp: resp["scopes"][0],
)


def decorate_scope_response(
auth_client: globus_sdk.AuthClient,
scope: dict[str, t.Any],
) -> None:
"""
Decorates the dependent scopes of a get-scope response.

Every dependent scope dict has a "scope_string" lazy-loader added to it that will
resolve the scope string by querying globus auth (with batching and caching).
"""
dependent_scopes = scope.get("dependent_scopes")
if not dependent_scopes:
return

# Create a batch resolver so that we resolve all dependent scope strings at once.
dependent_scope_ids = [dependent["scope"] for dependent in dependent_scopes]
resolver = BatchScopeStringResolver(auth_client, dependent_scope_ids)

# Replace the dependent scopes with LazyDicts.
scope["dependent_scopes"] = [LazyDict(dependent) for dependent in dependent_scopes]
for dependent in scope["dependent_scopes"]:
load_scope_string = functools.partial(resolver.resolve, dependent["scope"])
dependent.register_loader("scope_string", load_scope_string)
3 changes: 2 additions & 1 deletion src/globus_cli/login_manager/scopes.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,15 @@ class _ServiceRequirement(t.TypedDict):
class _CLIScopeRequirements(t.Dict[ServiceNameLiteral, _ServiceRequirement]):
def __init__(self) -> None:
self["auth"] = {
"min_contract_version": 0,
"min_contract_version": 1,
"resource_server": AuthScopes.resource_server,
"nice_server_name": "Globus Auth",
"scopes": [
AuthScopes.openid,
AuthScopes.profile,
AuthScopes.email,
AuthScopes.view_identity_set,
AuthScopes.manage_projects,
],
}
self["transfer"] = {
Expand Down
12 changes: 2 additions & 10 deletions src/globus_cli/services/auth.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
from __future__ import annotations

import typing as t
import uuid

import globus_sdk
import globus_sdk.scopes


def _is_uuid(s: str) -> bool:
try:
uuid.UUID(s)
return True
except ValueError:
return False
from globus_cli.utils import is_uuid


class GetIdentitiesKwargs(t.TypedDict, total=False):
Expand Down Expand Up @@ -72,7 +64,7 @@ def maybe_lookup_identity_id(
def maybe_lookup_identity_id(
self, identity_name: str, provision: bool = False
) -> str | None:
if _is_uuid(identity_name):
if is_uuid(identity_name):
return identity_name
else:
return self._lookup_identity_field(
Expand Down
4 changes: 3 additions & 1 deletion src/globus_cli/termio/_display.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import globus_sdk

from .context import outformat_is_json, outformat_is_text, outformat_is_unix
from .field import Field
from .printers import (
CustomPrinter,
JsonPrinter,
Expand All @@ -19,6 +18,9 @@
)
from .server_timing import maybe_show_server_timing

if t.TYPE_CHECKING:
from .field import Field


class TextMode(enum.Enum):
silent = enum.auto()
Expand Down
4 changes: 4 additions & 0 deletions src/globus_cli/termio/formatters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
from .base import FieldFormatter, FormattingFailedWarning
from .compound import (
ArrayFormatter,
ArrayMultilineFormatter,
ParentheticalDescriptionFormatter,
RecordFormatter,
SortedJsonFormatter,
)
from .primitive import (
Expand Down Expand Up @@ -30,6 +32,8 @@
"FuzzyBoolFormatter",
"StaticStringFormatter",
"ArrayFormatter",
"ArrayMultilineFormatter",
"RecordFormatter",
"SortedJsonFormatter",
"ParentheticalDescriptionFormatter",
"Str",
Expand Down
Loading
Loading