vincbeck commented on code in PR #75938:
URL: https://github.com/apache/airflow/pull/75938#discussion_r4591218714


##########
airflow-ctl/src/airflowctl/api/operations.py:
##########
@@ -369,6 +370,43 @@ def login_with_username_and_password(self, login: 
LoginBody) -> LoginResponse |
             self.client.post("/token/cli", 
json=login.model_dump(mode="json")).content
         )
 
+    def get_cli_login_metadata(self, api_url: str) -> CliLoginMetadataResponse:
+        """Return the login methods the API server offers, or none for servers 
without CLI login discovery."""
+        try:
+            response = self.client.get(
+                f"{api_url.rstrip('/')}/api/v2/auth/cli/metadata",
+                extensions={"airflowctl_suppress_error_log": True},
+            )
+        except httpx.HTTPStatusError as e:
+            if e.response.status_code != 404:
+                raise
+            return CliLoginMetadataResponse(
+                grant_types_supported=[],
+                code_challenge_methods_supported=[],
+                authorization_endpoint=None,
+                device_authorization_endpoint=None,
+                token_endpoint=None,
+            )
+        return CliLoginMetadataResponse.model_validate_json(response.content)
+
+    def login_with_authorization_code(
+        self, token_url: str, code: str, code_verifier: str, redirect_uri: str
+    ) -> LoginResponse:
+        """Redeem an authorization code from the browser login for a CLI 
token."""
+        request = self.client.build_request(
+            "POST",
+            token_url,
+            json={
+                "grant_type": "authorization_code",
+                "code": code,
+                "code_verifier": code_verifier,
+                "redirect_uri": redirect_uri,
+            },
+        )
+        # send() skips the retries of Client.request(): a code is single use, 
and identity providers can
+        # treat a replayed code as an attack and revoke the session.
+        return 
LoginResponse.model_validate_json(self.client.send(request).content)

Review Comment:
   Is `send()` needed? `_should_retry_api_request` never retries a POST once it 
reached the server, so `self.client.post(token_url, json=...)` gives the same 
guarantee and still retries a connect error.



##########
airflow-ctl/src/airflowctl/ctl/commands/auth_command.py:
##########
@@ -53,6 +83,31 @@ def login(args, api_client=NEW_API_CLIENT) -> None:
     password = args.password
     token = args.api_token or os.environ.get("AIRFLOW_CLI_TOKEN")
 
+    if args.sso:
+        if args.api_token or username or password:
+            rich.print("[red]--sso is not compatible with --api-token, 
--username or --password.")
+            sys.exit(1)
+        try:
+            api_token = _get_token_with_browser(args, api_client, api_url)
+        except Exception as e:
+            rich.print(f"[red]Login failed: {escape(str(e))}")
+            sys.exit(1)
+        Credentials(
+            api_url=api_url,
+            api_token=api_token,
+            api_environment=args.env,
+            client_kind=ClientKind.AUTH,
+        ).save(args.skip_keyring)

Review Comment:
   About the keyring error after the browser login: no need to probe the 
keyring, can we catch `AirflowCtlKeyringException` here and fall back to what 
`--skip-keyring` does (print the token and the `AIRFLOW_CLI_TOKEN` note)? That 
way the user doesn't have to log in twice.



##########
airflow-ctl/src/airflowctl/ctl/cli_config.py:
##########
@@ -345,6 +345,30 @@ def _load_help_texts_yaml() -> dict[str, dict[str, str]]:
     dest="password",
     help="The password to use for authentication",
 )
+ARG_AUTH_SSO = Arg(
+    flags=("--sso",),
+    dest="sso",
+    default=False,
+    action="store_true",
+    help="Log in through the browser with the identity provider of the API 
server, if it offers it",
+)
+ARG_AUTH_NO_BROWSER = Arg(
+    flags=("--no-browser",),
+    dest="no_browser",
+    default=False,
+    action="store_true",
+    help=(
+        "With --sso, print the login URL instead of opening a browser. The 
browser must still reach "
+        "this machine on 127.0.0.1, for example through 'ssh -L' when logged 
in remotely"
+    ),
+)
+ARG_AUTH_TIMEOUT = Arg(
+    flags=("--timeout",),
+    type=float,

Review Comment:
   nit: `--timeout 0` or a negative value fails right after the browser opens, 
and `--timeout inf` fails with an `OverflowError`. Maybe reject values that are 
not positive and finite in the parser?



##########
airflow-ctl/src/airflowctl/ctl/cli_config.py:
##########
@@ -1291,6 +1319,9 @@ def merge_commands(
             ARG_AUTH_URL,
             ARG_AUTH_USERNAME,
             ARG_AUTH_PASSWORD,
+            ARG_AUTH_SSO,

Review Comment:
   nit: the `auth token` description above still says it authenticates with 
username and password. Should we mention `--sso` there, like you did for `auth 
login`?



##########
airflow-ctl/src/airflowctl/ctl/commands/auth_command.py:
##########
@@ -53,6 +83,31 @@ def login(args, api_client=NEW_API_CLIENT) -> None:
     password = args.password
     token = args.api_token or os.environ.get("AIRFLOW_CLI_TOKEN")
 
+    if args.sso:
+        if args.api_token or username or password:
+            rich.print("[red]--sso is not compatible with --api-token, 
--username or --password.")
+            sys.exit(1)
+        try:
+            api_token = _get_token_with_browser(args, api_client, api_url)
+        except Exception as e:
+            rich.print(f"[red]Login failed: {escape(str(e))}")

Review Comment:
   With `--skip-keyring`, stdout carries the token, but this error (and the 
`--sso is not compatible` one above) also goes to stdout. With `export 
AIRFLOW_CLI_TOKEN=$(airflowctl auth login --sso --skip-keyring ...)`, a failed 
login sets the variable to "Login failed: ..." and the user sees nothing in the 
terminal. Can these go to stderr like in `get_token`?



##########
airflow-ctl/src/airflowctl/ctl/commands/auth_command.py:
##########
@@ -53,6 +83,31 @@ def login(args, api_client=NEW_API_CLIENT) -> None:
     password = args.password
     token = args.api_token or os.environ.get("AIRFLOW_CLI_TOKEN")
 
+    if args.sso:
+        if args.api_token or username or password:
+            rich.print("[red]--sso is not compatible with --api-token, 
--username or --password.")
+            sys.exit(1)
+        try:
+            api_token = _get_token_with_browser(args, api_client, api_url)
+        except Exception as e:
+            rich.print(f"[red]Login failed: {escape(str(e))}")
+            sys.exit(1)
+        Credentials(
+            api_url=api_url,
+            api_token=api_token,
+            api_environment=args.env,
+            client_kind=ClientKind.AUTH,
+        ).save(args.skip_keyring)
+        if args.skip_keyring:
+            # Nothing stores the token, so this is the only way to use the 
login that just happened.
+            print(api_token)

Review Comment:
   Agree, the CodeQL alert is a false positive. Printing the token is the point 
of `--skip-keyring` here, so it can be dismissed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to