This is an automated email from the ASF dual-hosted git repository.
vincbeck pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 1e30d3d5a0d Add browser login to airflowctl (#75938)
1e30d3d5a0d is described below
commit 1e30d3d5a0dcbb06a7076d56c1aaec9026859742
Author: Baptiste Gouhoury <[email protected]>
AuthorDate: Tue Nov 17 23:42:15 2026 +0100
Add browser login to airflowctl (#75938)
Users who sign in to Airflow through SSO or with a second factor have no
password to give airflowctl, so they could only log in by copying a
token from somewhere else. Auth managers can now advertise a browser
login through the CLI login discovery route, and airflowctl can use it
without knowing which auth manager serves it.
Servers without discovery, or whose auth manager does not offer browser
login, fail with a clear message instead of a silent wait for a browser
redirect that never comes.
---
airflow-ctl/docs/images/command_hashes.txt | 2 +-
airflow-ctl/docs/images/output_auth_login.svg | 140 +++++----
airflow-ctl/docs/start.rst | 14 +-
airflow-ctl/src/airflowctl/api/client.py | 16 +-
airflow-ctl/src/airflowctl/api/operations.py | 35 +++
airflow-ctl/src/airflowctl/ctl/cli_config.py | 48 +++-
.../src/airflowctl/ctl/commands/auth_command.py | 93 +++++-
.../src/airflowctl/ctl/utils/browser_login.py | 195 +++++++++++++
airflow-ctl/src/airflowctl/exceptions.py | 4 +
airflow-ctl/tests/airflow_ctl/api/test_client.py | 37 ++-
.../tests/airflow_ctl/api/test_operations.py | 120 +++++++-
.../airflow_ctl/ctl/commands/test_auth_command.py | 319 +++++++++++++++++++++
.../tests/airflow_ctl/ctl/test_cli_config.py | 9 +
.../airflow_ctl/ctl/utils/test_browser_login.py | 281 ++++++++++++++++++
docs/spelling_wordlist.txt | 1 +
15 files changed, 1250 insertions(+), 64 deletions(-)
diff --git a/airflow-ctl/docs/images/command_hashes.txt
b/airflow-ctl/docs/images/command_hashes.txt
index 3e57380b614..2028b92a2c1 100644
--- a/airflow-ctl/docs/images/command_hashes.txt
+++ b/airflow-ctl/docs/images/command_hashes.txt
@@ -14,4 +14,4 @@ tasks:79059c3c8de9114e73895d4b8e86ed00
variables:f8fc76d3d398b2780f4e97f7cd816646
version:31f4efdf8de0dbaaa4fac71ff7efecc3
plugins:4864fd8f356704bd2b3cd1aec3567e35
-auth login:963355e38ab1c133f2cf9495d00d99f6
+auth login:b71937602ce3b928547dc7b7ab3ed955
diff --git a/airflow-ctl/docs/images/output_auth_login.svg
b/airflow-ctl/docs/images/output_auth_login.svg
index f722fb20eb3..6a55f626d89 100644
--- a/airflow-ctl/docs/images/output_auth_login.svg
+++ b/airflow-ctl/docs/images/output_auth_login.svg
@@ -1,4 +1,4 @@
-<svg class="rich-terminal" viewBox="0 0 933 538.0"
xmlns="http://www.w3.org/2000/svg">
+<svg class="rich-terminal" viewBox="0 0 933 757.5999999999999"
xmlns="http://www.w3.org/2000/svg">
<!-- Generated with Rich https://www.textualize.io -->
<style>
@@ -19,119 +19,155 @@
font-weight: 700;
}
- .terminal-2746294408-matrix {
+ .terminal-364581079-matrix {
font-family: Fira Code, monospace;
font-size: 20px;
line-height: 24.4px;
font-variant-east-asian: full-width;
}
- .terminal-2746294408-title {
+ .terminal-364581079-title {
font-size: 18px;
font-weight: bold;
font-family: arial;
}
- .terminal-2746294408-r1 { fill: #ff8700 }
-.terminal-2746294408-r2 { fill: #c5c8c6 }
-.terminal-2746294408-r3 { fill: #808080 }
-.terminal-2746294408-r4 { fill: #68a0b3 }
-.terminal-2746294408-r5 { fill: #00af87 }
+ .terminal-364581079-r1 { fill: #ff8700 }
+.terminal-364581079-r2 { fill: #c5c8c6 }
+.terminal-364581079-r3 { fill: #808080 }
+.terminal-364581079-r4 { fill: #68a0b3 }
+.terminal-364581079-r5 { fill: #00af87 }
</style>
<defs>
- <clipPath id="terminal-2746294408-clip-terminal">
- <rect x="0" y="0" width="914.0" height="487.0" />
+ <clipPath id="terminal-364581079-clip-terminal">
+ <rect x="0" y="0" width="914.0" height="706.5999999999999" />
</clipPath>
- <clipPath id="terminal-2746294408-line-0">
+ <clipPath id="terminal-364581079-line-0">
<rect x="0" y="1.5" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-1">
+<clipPath id="terminal-364581079-line-1">
<rect x="0" y="25.9" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-2">
+<clipPath id="terminal-364581079-line-2">
<rect x="0" y="50.3" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-3">
+<clipPath id="terminal-364581079-line-3">
<rect x="0" y="74.7" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-4">
+<clipPath id="terminal-364581079-line-4">
<rect x="0" y="99.1" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-5">
+<clipPath id="terminal-364581079-line-5">
<rect x="0" y="123.5" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-6">
+<clipPath id="terminal-364581079-line-6">
<rect x="0" y="147.9" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-7">
+<clipPath id="terminal-364581079-line-7">
<rect x="0" y="172.3" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-8">
+<clipPath id="terminal-364581079-line-8">
<rect x="0" y="196.7" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-9">
+<clipPath id="terminal-364581079-line-9">
<rect x="0" y="221.1" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-10">
+<clipPath id="terminal-364581079-line-10">
<rect x="0" y="245.5" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-11">
+<clipPath id="terminal-364581079-line-11">
<rect x="0" y="269.9" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-12">
+<clipPath id="terminal-364581079-line-12">
<rect x="0" y="294.3" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-13">
+<clipPath id="terminal-364581079-line-13">
<rect x="0" y="318.7" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-14">
+<clipPath id="terminal-364581079-line-14">
<rect x="0" y="343.1" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-15">
+<clipPath id="terminal-364581079-line-15">
<rect x="0" y="367.5" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-16">
+<clipPath id="terminal-364581079-line-16">
<rect x="0" y="391.9" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-17">
+<clipPath id="terminal-364581079-line-17">
<rect x="0" y="416.3" width="915" height="24.65"/>
</clipPath>
-<clipPath id="terminal-2746294408-line-18">
+<clipPath id="terminal-364581079-line-18">
<rect x="0" y="440.7" width="915" height="24.65"/>
</clipPath>
+<clipPath id="terminal-364581079-line-19">
+ <rect x="0" y="465.1" width="915" height="24.65"/>
+ </clipPath>
+<clipPath id="terminal-364581079-line-20">
+ <rect x="0" y="489.5" width="915" height="24.65"/>
+ </clipPath>
+<clipPath id="terminal-364581079-line-21">
+ <rect x="0" y="513.9" width="915" height="24.65"/>
+ </clipPath>
+<clipPath id="terminal-364581079-line-22">
+ <rect x="0" y="538.3" width="915" height="24.65"/>
+ </clipPath>
+<clipPath id="terminal-364581079-line-23">
+ <rect x="0" y="562.7" width="915" height="24.65"/>
+ </clipPath>
+<clipPath id="terminal-364581079-line-24">
+ <rect x="0" y="587.1" width="915" height="24.65"/>
+ </clipPath>
+<clipPath id="terminal-364581079-line-25">
+ <rect x="0" y="611.5" width="915" height="24.65"/>
+ </clipPath>
+<clipPath id="terminal-364581079-line-26">
+ <rect x="0" y="635.9" width="915" height="24.65"/>
+ </clipPath>
+<clipPath id="terminal-364581079-line-27">
+ <rect x="0" y="660.3" width="915" height="24.65"/>
+ </clipPath>
</defs>
- <rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1"
x="1" y="1" width="931" height="536" rx="8"/>
+ <rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1"
x="1" y="1" width="931" height="755.6" rx="8"/>
<g transform="translate(26,22)">
<circle cx="0" cy="0" r="7" fill="#ff5f57"/>
<circle cx="22" cy="0" r="7" fill="#febc2e"/>
<circle cx="44" cy="0" r="7" fill="#28c840"/>
</g>
- <g transform="translate(9, 41)"
clip-path="url(#terminal-2746294408-clip-terminal)">
+ <g transform="translate(9, 41)"
clip-path="url(#terminal-364581079-clip-terminal)">
- <g class="terminal-2746294408-matrix">
- <text class="terminal-2746294408-r1" x="0" y="20" textLength="73.2"
clip-path="url(#terminal-2746294408-line-0)">Usage:</text><text
class="terminal-2746294408-r3" x="85.4" y="20" textLength="256.2"
clip-path="url(#terminal-2746294408-line-0)">airflowctl auth login</text><text
class="terminal-2746294408-r2" x="341.6" y="20" textLength="24.4"
clip-path="url(#terminal-2746294408-line-0)"> [</text><text
class="terminal-2746294408-r4" x="366" y="20" textLength="24.4" clip-p [...]
-</text><text class="terminal-2746294408-r2" x="0" y="44.4" textLength="366"
clip-path="url(#terminal-2746294408-line-1)">                             [</text><text
class="terminal-2746294408-r4" x="366" y="44.4" textLength="109.8"
clip-path="url(#terminal-2746294408-line-1)">--api-url</text><text
class="terminal-2746294408-r5" x="488" y="44.4" t [...]
-</text><text class="terminal-2746294408-r2" x="0" y="68.8" textLength="366"
clip-path="url(#terminal-2746294408-line-2)">                             [</text><text
class="terminal-2746294408-r4" x="366" y="68.8" textLength="122"
clip-path="url(#terminal-2746294408-line-2)">--password</text><text
class="terminal-2746294408-r5" x="500.2" y="68.8" [...]
-</text><text class="terminal-2746294408-r2" x="0" y="93.2" textLength="366"
clip-path="url(#terminal-2746294408-line-3)">                             [</text><text
class="terminal-2746294408-r4" x="366" y="93.2" textLength="122"
clip-path="url(#terminal-2746294408-line-3)">--username</text><text
class="terminal-2746294408-r5" x="500.2" y="93.2" [...]
-</text><text class="terminal-2746294408-r2" x="915" y="117.6"
textLength="12.2" clip-path="url(#terminal-2746294408-line-4)">
-</text><text class="terminal-2746294408-r2" x="0" y="142" textLength="915"
clip-path="url(#terminal-2746294408-line-5)">Log in to the Airflow API server and store the credentials for the selected</text><text
class="terminal-2746294408-r2" x="915" y="142" textLength="12.2"
clip-path="url(#terminal-2746294408-line-5)">
-</text><text class="terminal-2746294408-r2" x="0" y="166.4" textLength="219.6"
clip-path="url(#terminal-2746294408-line-6)">environment. Pass </text><text
class="terminal-2746294408-r4" x="219.6" y="166.4" textLength="134.2"
clip-path="url(#terminal-2746294408-line-6)">--api-token</text><text
class="terminal-2746294408-r2" x="353.8" y="166.4" textLength="390.4"
clip-path="url(#terminal-2746294408-line-6)"> (or set AIRFLOW_CLI_TOKEN), or </text><text
cla [...]
-</text><text class="terminal-2746294408-r4" x="0" y="190.8" textLength="122"
clip-path="url(#terminal-2746294408-line-7)">--password</text><text
class="terminal-2746294408-r2" x="122" y="190.8" textLength="695.4"
clip-path="url(#terminal-2746294408-line-7)">; missing credentials are prompted for when running in a </text><text
class="terminal-2746294408-r2" x="915" y="190.8" textLength="12.2"
clip-path="url(#terminal-2746294408-line-7)">
-</text><text class="terminal-2746294408-r2" x="0" y="215.2" textLength="109.8"
clip-path="url(#terminal-2746294408-line-8)">terminal.</text><text
class="terminal-2746294408-r2" x="915" y="215.2" textLength="12.2"
clip-path="url(#terminal-2746294408-line-8)">
-</text><text class="terminal-2746294408-r2" x="915" y="239.6"
textLength="12.2" clip-path="url(#terminal-2746294408-line-9)">
-</text><text class="terminal-2746294408-r1" x="0" y="264" textLength="97.6"
clip-path="url(#terminal-2746294408-line-10)">Options:</text><text
class="terminal-2746294408-r2" x="915" y="264" textLength="12.2"
clip-path="url(#terminal-2746294408-line-10)">
-</text><text class="terminal-2746294408-r4" x="24.4" y="288.4"
textLength="24.4" clip-path="url(#terminal-2746294408-line-11)">-h</text><text
class="terminal-2746294408-r2" x="48.8" y="288.4" textLength="24.4"
clip-path="url(#terminal-2746294408-line-11)">, </text><text
class="terminal-2746294408-r4" x="73.2" y="288.4" textLength="73.2"
clip-path="url(#terminal-2746294408-line-11)">--help</text><text
class="terminal-2746294408-r2" x="292.8" y="288.4" textLength="378.2"
clip-path="ur [...]
-</text><text class="terminal-2746294408-r4" x="24.4" y="312.8"
textLength="134.2"
clip-path="url(#terminal-2746294408-line-12)">--api-token</text><text
class="terminal-2746294408-r5" x="170.8" y="312.8" textLength="109.8"
clip-path="url(#terminal-2746294408-line-12)">API_TOKEN</text><text
class="terminal-2746294408-r2" x="915" y="312.8" textLength="12.2"
clip-path="url(#terminal-2746294408-line-12)">
-</text><text class="terminal-2746294408-r2" x="292.8" y="337.2"
textLength="427"
clip-path="url(#terminal-2746294408-line-13)">The token to use for authentication</text><text
class="terminal-2746294408-r2" x="915" y="337.2" textLength="12.2"
clip-path="url(#terminal-2746294408-line-13)">
-</text><text class="terminal-2746294408-r4" x="24.4" y="361.6"
textLength="109.8"
clip-path="url(#terminal-2746294408-line-14)">--api-url</text><text
class="terminal-2746294408-r5" x="146.4" y="361.6" textLength="85.4"
clip-path="url(#terminal-2746294408-line-14)">API_URL</text><text
class="terminal-2746294408-r2" x="292.8" y="361.6" textLength="402.6"
clip-path="url(#terminal-2746294408-line-14)">The URL of the Airflow API server</text><text
class="terminal [...]
-</text><text class="terminal-2746294408-r4" x="24.4" y="386" textLength="24.4"
clip-path="url(#terminal-2746294408-line-15)">-e</text><text
class="terminal-2746294408-r2" x="48.8" y="386" textLength="24.4"
clip-path="url(#terminal-2746294408-line-15)">, </text><text
class="terminal-2746294408-r4" x="73.2" y="386" textLength="61"
clip-path="url(#terminal-2746294408-line-15)">--env</text><text
class="terminal-2746294408-r5" x="146.4" y="386" textLength="36.6"
clip-path="url(#terminal- [...]
-</text><text class="terminal-2746294408-r4" x="24.4" y="410.4"
textLength="122"
clip-path="url(#terminal-2746294408-line-16)">--password</text><text
class="terminal-2746294408-r5" x="158.6" y="410.4" textLength="97.6"
clip-path="url(#terminal-2746294408-line-16)">PASSWORD</text><text
class="terminal-2746294408-r2" x="292.8" y="410.4" textLength="463.6"
clip-path="url(#terminal-2746294408-line-16)">The password to use for authentication</text><text
class="terminal [...]
-</text><text class="terminal-2746294408-r4" x="24.4" y="434.8"
textLength="170.8"
clip-path="url(#terminal-2746294408-line-17)">--skip-keyring</text><text
class="terminal-2746294408-r2" x="292.8" y="434.8" textLength="427"
clip-path="url(#terminal-2746294408-line-17)">Skip storing credentials in keyring</text><text
class="terminal-2746294408-r2" x="915" y="434.8" textLength="12.2"
clip-path="url(#terminal-2746294408-line-17)">
-</text><text class="terminal-2746294408-r4" x="24.4" y="459.2"
textLength="122"
clip-path="url(#terminal-2746294408-line-18)">--username</text><text
class="terminal-2746294408-r5" x="158.6" y="459.2" textLength="97.6"
clip-path="url(#terminal-2746294408-line-18)">USERNAME</text><text
class="terminal-2746294408-r2" x="292.8" y="459.2" textLength="463.6"
clip-path="url(#terminal-2746294408-line-18)">The username to use for authentication</text><text
class="terminal [...]
-</text><text class="terminal-2746294408-r2" x="915" y="483.6"
textLength="12.2" clip-path="url(#terminal-2746294408-line-19)">
+ <g class="terminal-364581079-matrix">
+ <text class="terminal-364581079-r1" x="0" y="20" textLength="73.2"
clip-path="url(#terminal-364581079-line-0)">Usage:</text><text
class="terminal-364581079-r3" x="85.4" y="20" textLength="256.2"
clip-path="url(#terminal-364581079-line-0)">airflowctl auth login</text><text
class="terminal-364581079-r2" x="341.6" y="20" textLength="24.4"
clip-path="url(#terminal-364581079-line-0)"> [</text><text
class="terminal-364581079-r4" x="366" y="20" textLength="24.4" clip-path="ur
[...]
+</text><text class="terminal-364581079-r2" x="0" y="44.4" textLength="366"
clip-path="url(#terminal-364581079-line-1)">                             [</text><text
class="terminal-364581079-r4" x="366" y="44.4" textLength="109.8"
clip-path="url(#terminal-364581079-line-1)">--api-url</text><text
class="terminal-364581079-r5" x="488" y="44.4" textLe [...]
+</text><text class="terminal-364581079-r2" x="0" y="68.8" textLength="366"
clip-path="url(#terminal-364581079-line-2)">                             [</text><text
class="terminal-364581079-r4" x="366" y="68.8" textLength="122"
clip-path="url(#terminal-364581079-line-2)">--password</text><text
class="terminal-364581079-r5" x="500.2" y="68.8" textL [...]
+</text><text class="terminal-364581079-r2" x="0" y="93.2" textLength="366"
clip-path="url(#terminal-364581079-line-3)">                             [</text><text
class="terminal-364581079-r4" x="366" y="93.2" textLength="61"
clip-path="url(#terminal-364581079-line-3)">--sso</text><text
class="terminal-364581079-r2" x="427" y="93.2" textLength="3 [...]
+</text><text class="terminal-364581079-r2" x="0" y="117.6" textLength="366"
clip-path="url(#terminal-364581079-line-4)">                             [</text><text
class="terminal-364581079-r4" x="366" y="117.6" textLength="122"
clip-path="url(#terminal-364581079-line-4)">--username</text><text
class="terminal-364581079-r5" x="500.2" y="117.6" te [...]
+</text><text class="terminal-364581079-r2" x="915" y="142" textLength="12.2"
clip-path="url(#terminal-364581079-line-5)">
+</text><text class="terminal-364581079-r2" x="0" y="166.4" textLength="915"
clip-path="url(#terminal-364581079-line-6)">Log in to the Airflow API server and store the credentials for the selected</text><text
class="terminal-364581079-r2" x="915" y="166.4" textLength="12.2"
clip-path="url(#terminal-364581079-line-6)">
+</text><text class="terminal-364581079-r2" x="0" y="190.8" textLength="219.6"
clip-path="url(#terminal-364581079-line-7)">environment. Pass </text><text
class="terminal-364581079-r4" x="219.6" y="190.8" textLength="134.2"
clip-path="url(#terminal-364581079-line-7)">--api-token</text><text
class="terminal-364581079-r2" x="353.8" y="190.8" textLength="390.4"
clip-path="url(#terminal-364581079-line-7)"> (or set AIRFLOW_CLI_TOKEN), or </text><text
class="te [...]
+</text><text class="terminal-364581079-r4" x="0" y="215.2" textLength="122"
clip-path="url(#terminal-364581079-line-8)">--password</text><text
class="terminal-364581079-r2" x="122" y="215.2" textLength="695.4"
clip-path="url(#terminal-364581079-line-8)">; missing credentials are prompted for when running in a </text><text
class="terminal-364581079-r2" x="915" y="215.2" textLength="12.2"
clip-path="url(#terminal-364581079-line-8)">
+</text><text class="terminal-364581079-r2" x="0" y="239.6" textLength="183"
clip-path="url(#terminal-364581079-line-9)">terminal. Pass </text><text
class="terminal-364581079-r4" x="183" y="239.6" textLength="61"
clip-path="url(#terminal-364581079-line-9)">--sso</text><text
class="terminal-364581079-r2" x="244" y="239.6" textLength="622.2"
clip-path="url(#terminal-364581079-line-9)"> to log in through the browser when the API ser
[...]
+</text><text class="terminal-364581079-r2" x="0" y="264" textLength="122"
clip-path="url(#terminal-364581079-line-10)">offers it.</text><text
class="terminal-364581079-r2" x="915" y="264" textLength="12.2"
clip-path="url(#terminal-364581079-line-10)">
+</text><text class="terminal-364581079-r2" x="915" y="288.4" textLength="12.2"
clip-path="url(#terminal-364581079-line-11)">
+</text><text class="terminal-364581079-r1" x="0" y="312.8" textLength="97.6"
clip-path="url(#terminal-364581079-line-12)">Options:</text><text
class="terminal-364581079-r2" x="915" y="312.8" textLength="12.2"
clip-path="url(#terminal-364581079-line-12)">
+</text><text class="terminal-364581079-r4" x="24.4" y="337.2"
textLength="24.4" clip-path="url(#terminal-364581079-line-13)">-h</text><text
class="terminal-364581079-r2" x="48.8" y="337.2" textLength="24.4"
clip-path="url(#terminal-364581079-line-13)">, </text><text
class="terminal-364581079-r4" x="73.2" y="337.2" textLength="73.2"
clip-path="url(#terminal-364581079-line-13)">--help</text><text
class="terminal-364581079-r2" x="292.8" y="337.2" textLength="378.2"
clip-path="url(#term [...]
+</text><text class="terminal-364581079-r4" x="24.4" y="361.6"
textLength="134.2"
clip-path="url(#terminal-364581079-line-14)">--api-token</text><text
class="terminal-364581079-r5" x="170.8" y="361.6" textLength="109.8"
clip-path="url(#terminal-364581079-line-14)">API_TOKEN</text><text
class="terminal-364581079-r2" x="915" y="361.6" textLength="12.2"
clip-path="url(#terminal-364581079-line-14)">
+</text><text class="terminal-364581079-r2" x="292.8" y="386" textLength="427"
clip-path="url(#terminal-364581079-line-15)">The token to use for authentication</text><text
class="terminal-364581079-r2" x="915" y="386" textLength="12.2"
clip-path="url(#terminal-364581079-line-15)">
+</text><text class="terminal-364581079-r4" x="24.4" y="410.4"
textLength="109.8"
clip-path="url(#terminal-364581079-line-16)">--api-url</text><text
class="terminal-364581079-r5" x="146.4" y="410.4" textLength="85.4"
clip-path="url(#terminal-364581079-line-16)">API_URL</text><text
class="terminal-364581079-r2" x="292.8" y="410.4" textLength="402.6"
clip-path="url(#terminal-364581079-line-16)">The URL of the Airflow API server</text><text
class="terminal-36458 [...]
+</text><text class="terminal-364581079-r4" x="24.4" y="434.8"
textLength="24.4" clip-path="url(#terminal-364581079-line-17)">-e</text><text
class="terminal-364581079-r2" x="48.8" y="434.8" textLength="24.4"
clip-path="url(#terminal-364581079-line-17)">, </text><text
class="terminal-364581079-r4" x="73.2" y="434.8" textLength="61"
clip-path="url(#terminal-364581079-line-17)">--env</text><text
class="terminal-364581079-r5" x="146.4" y="434.8" textLength="36.6"
clip-path="url(#terminal [...]
+</text><text class="terminal-364581079-r4" x="24.4" y="459.2"
textLength="146.4"
clip-path="url(#terminal-364581079-line-18)">--no-browser</text><text
class="terminal-364581079-r2" x="292.8" y="459.2" textLength="61"
clip-path="url(#terminal-364581079-line-18)">With </text><text
class="terminal-364581079-r4" x="353.8" y="459.2" textLength="61"
clip-path="url(#terminal-364581079-line-18)">--sso</text><text
class="terminal-364581079-r2" x="414.8" y="459.2" textLength="500.2" clip-path
[...]
+</text><text class="terminal-364581079-r2" x="0" y="483.6" textLength="817.4"
clip-path="url(#terminal-364581079-line-19)">a browser. The browser must run on this machine, because the login </text><text
class="terminal-364581079-r2" x="915" y="483.6" textLength="12.2"
clip-path="url(#terminal-364581079-line-19)">
+</text><text class="terminal-364581079-r2" x="0" y="508" textLength="268.4"
clip-path="url(#terminal-364581079-line-20)">redirects to 127.0.0.1</text><text
class="terminal-364581079-r2" x="915" y="508" textLength="12.2"
clip-path="url(#terminal-364581079-line-20)">
+</text><text class="terminal-364581079-r4" x="24.4" y="532.4" textLength="122"
clip-path="url(#terminal-364581079-line-21)">--password</text><text
class="terminal-364581079-r5" x="158.6" y="532.4" textLength="97.6"
clip-path="url(#terminal-364581079-line-21)">PASSWORD</text><text
class="terminal-364581079-r2" x="292.8" y="532.4" textLength="463.6"
clip-path="url(#terminal-364581079-line-21)">The password to use for authentication</text><text
class="terminal-36458 [...]
+</text><text class="terminal-364581079-r4" x="24.4" y="556.8"
textLength="170.8"
clip-path="url(#terminal-364581079-line-22)">--skip-keyring</text><text
class="terminal-364581079-r2" x="292.8" y="556.8" textLength="427"
clip-path="url(#terminal-364581079-line-22)">Skip storing credentials in keyring</text><text
class="terminal-364581079-r2" x="915" y="556.8" textLength="12.2"
clip-path="url(#terminal-364581079-line-22)">
+</text><text class="terminal-364581079-r4" x="24.4" y="581.2" textLength="61"
clip-path="url(#terminal-364581079-line-23)">--sso</text><text
class="terminal-364581079-r2" x="292.8" y="581.2" textLength="549"
clip-path="url(#terminal-364581079-line-23)">Log in through the browser with the identity </text><text
class="terminal-364581079-r2" x="915" y="581.2" textLength="12.2"
clip-path="url(#terminal-364581079-line-23)">
+</text><text class="terminal-364581079-r2" x="0" y="605.6" textLength="524.6"
clip-path="url(#terminal-364581079-line-24)">provider of the API server, if it offers it</text><text
class="terminal-364581079-r2" x="915" y="605.6" textLength="12.2"
clip-path="url(#terminal-364581079-line-24)">
+</text><text class="terminal-364581079-r4" x="24.4" y="630" textLength="109.8"
clip-path="url(#terminal-364581079-line-25)">--timeout</text><text
class="terminal-364581079-r5" x="146.4" y="630" textLength="85.4"
clip-path="url(#terminal-364581079-line-25)">TIMEOUT</text><text
class="terminal-364581079-r2" x="292.8" y="630" textLength="61"
clip-path="url(#terminal-364581079-line-25)">With </text><text
class="terminal-364581079-r4" x="353.8" y="630" textLength="61"
clip-path="url(#ter [...]
+</text><text class="terminal-364581079-r2" x="0" y="654.4" textLength="317.2"
clip-path="url(#terminal-364581079-line-26)">to complete (default: 300)</text><text
class="terminal-364581079-r2" x="915" y="654.4" textLength="12.2"
clip-path="url(#terminal-364581079-line-26)">
+</text><text class="terminal-364581079-r4" x="24.4" y="678.8" textLength="122"
clip-path="url(#terminal-364581079-line-27)">--username</text><text
class="terminal-364581079-r5" x="158.6" y="678.8" textLength="97.6"
clip-path="url(#terminal-364581079-line-27)">USERNAME</text><text
class="terminal-364581079-r2" x="292.8" y="678.8" textLength="463.6"
clip-path="url(#terminal-364581079-line-27)">The username to use for authentication</text><text
class="terminal-36458 [...]
+</text><text class="terminal-364581079-r2" x="915" y="703.2" textLength="12.2"
clip-path="url(#terminal-364581079-line-28)">
</text>
</g>
</g>
diff --git a/airflow-ctl/docs/start.rst b/airflow-ctl/docs/start.rst
index fc879092c8c..72d24a15d8c 100644
--- a/airflow-ctl/docs/start.rst
+++ b/airflow-ctl/docs/start.rst
@@ -44,7 +44,19 @@ OR
export AIRFLOW_CLI_TOKEN=<token>
airflowctl auth login --api-url <api_url> --env <env_name>
-This command will create a new airflowctl environment with the specified
username and password.
+OR, when the auth manager of the API server offers browser login (for example
to sign in through SSO):
+
+.. code-block:: bash
+
+ airflowctl auth login --sso --api-url <api_url>
+
+This opens the login page of the API server in your browser and waits for the
login to complete.
+The browser redirects back to airflowctl on ``127.0.0.1``, so it must run on
the same machine.
+Pass ``--no-browser`` to only print the login URL, for example to open it in
another browser.
+On a machine without a keyring, also pass ``--skip-keyring``: the token is
printed instead of
+stored, and you can set ``AIRFLOW_CLI_TOKEN`` to it.
+
+Each of these commands creates a new airflowctl environment with the given
credentials.
You can then use the following command to start the airflowctl environment:
.. code-block:: bash
diff --git a/airflow-ctl/src/airflowctl/api/client.py
b/airflow-ctl/src/airflowctl/api/client.py
index aea909e7cb8..629eaba02c6 100644
--- a/airflow-ctl/src/airflowctl/api/client.py
+++ b/airflow-ctl/src/airflowctl/api/client.py
@@ -33,7 +33,7 @@ import httpx
import keyring
import structlog
from httpx import URL
-from keyring.errors import NoKeyringError
+from keyring.errors import KeyringError, NoKeyringError
from tenacity import (
before_sleep_log,
retry,
@@ -239,11 +239,12 @@ class Credentials:
"""Build the keyring/debug token key for a given environment name."""
return f"api_token_{api_environment}"
- def save(self, skip_keyring: bool = False):
+ def save(self, skip_keyring: bool = False) -> bool:
"""
Save the credentials to keyring and URL to disk as a file.
Skip saving the token to keyring if skip_keyring is True.
+ Return whether the token was stored, which debug mode does even with
skip_keyring.
The debug credentials file of an earlier login is removed first, and
the
config file records that the token is not in keyring until
@@ -268,7 +269,7 @@ class Credentials:
json.dump({self.token_key_for_environment(self.api_environment):
self.api_token}, f)
else:
if skip_keyring:
- return
+ return False
# Replace the upstream EncryptedKeyring's unbounded password
# prompt with a bounded one before set_password can trigger it.
# The active backend may be a ChainerBackend that delegates to
@@ -296,6 +297,12 @@ class Credentials:
"the --api-token flag to any command.\n"
"Use `airflowctl auth login --skip-keyring ...` to dismiss
this error."
) from e
+ except (KeyringError, ValueError) as e:
+ # A wrong EncryptedKeyring password raises ValueError.
+ raise AirflowCtlKeyringException(
+ f"Cannot save credentials to the keyring: {str(e) or
type(e).__name__}"
+ ) from e
+ return True
def load(self) -> Credentials:
"""Load the credentials from keyring and URL from disk file."""
@@ -303,7 +310,8 @@ class Credentials:
config_path = _safe_path_under_airflow_home(default_config_dir,
self.input_cli_config_file)
try:
self.api_url = _read_api_url(config_path)
- if self.client_kind == ClientKind.NO_AUTH:
+ # Neither kind sends a token, so a locked or missing keyring must
not block them.
+ if self.client_kind in (ClientKind.AUTH, ClientKind.NO_AUTH):
return self
if self.api_token is not None:
return self
diff --git a/airflow-ctl/src/airflowctl/api/operations.py
b/airflow-ctl/src/airflowctl/api/operations.py
index 342c61ee0ea..118d3806fb7 100644
--- a/airflow-ctl/src/airflowctl/api/operations.py
+++ b/airflow-ctl/src/airflowctl/api/operations.py
@@ -49,6 +49,7 @@ from airflowctl.api.datamodels.generated import (
BulkBodyVariableBody,
BulkResponse,
ClearTaskInstancesBody,
+ CliLoginMetadataResponse,
Config,
ConnectionBody,
ConnectionCollectionResponse,
@@ -369,6 +370,40 @@ class LoginOperations:
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."""
+ response = self.client.post(
+ token_url,
+ json={
+ "grant_type": "authorization_code",
+ "code": code,
+ "code_verifier": code_verifier,
+ "redirect_uri": redirect_uri,
+ },
+ )
+ return LoginResponse.model_validate_json(response.content)
+
# Operations
class AssetsOperations(BaseOperations):
diff --git a/airflow-ctl/src/airflowctl/ctl/cli_config.py
b/airflow-ctl/src/airflowctl/ctl/cli_config.py
index f71d6f3db03..2d135fd047f 100755
--- a/airflow-ctl/src/airflowctl/ctl/cli_config.py
+++ b/airflow-ctl/src/airflowctl/ctl/cli_config.py
@@ -25,6 +25,7 @@ import ast
import datetime
import inspect
import json
+import math
import os
import sys
import typing
@@ -234,6 +235,17 @@ def positive_int(*, allow_zero):
return _check
+def positive_finite_float(value):
+ """Parse a float argument that must be positive and finite."""
+ try:
+ parsed = float(value)
+ except ValueError:
+ parsed = None
+ if parsed is None or not math.isfinite(parsed) or parsed <= 0:
+ raise argparse.ArgumentTypeError(f"invalid positive number: '{value}'")
+ return parsed
+
+
def string_list_type(val):
"""Parse comma-separated list and returns list of string (strips
whitespace)."""
return [x.strip() for x in val.split(",")]
@@ -345,6 +357,30 @@ ARG_AUTH_PASSWORD = Arg(
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 run on this machine, because the login redirects to
127.0.0.1"
+ ),
+)
+ARG_AUTH_TIMEOUT = Arg(
+ flags=("--timeout",),
+ type=positive_finite_float,
+ default=None,
+ dest="timeout",
+ help="With --sso, seconds to wait for the browser login to complete
(default: 300)",
+)
# Dag Commands Args
ARG_DAG_ID = Arg(
@@ -1243,7 +1279,8 @@ AUTH_COMMANDS = (
description=(
"Log in to the Airflow API server and store the credentials for
the selected environment. "
"Pass --api-token (or set AIRFLOW_CLI_TOKEN), or --username and
--password; "
- "missing credentials are prompted for when running in a terminal."
+ "missing credentials are prompted for when running in a terminal. "
+ "Pass --sso to log in through the browser when the API server
offers it."
),
func=lazy_load_command("airflowctl.ctl.commands.auth_command.login"),
args=(
@@ -1252,6 +1289,9 @@ AUTH_COMMANDS = (
ARG_AUTH_USERNAME,
ARG_AUTH_PASSWORD,
ARG_AUTH_SKIP_KEYRING,
+ ARG_AUTH_SSO,
+ ARG_AUTH_NO_BROWSER,
+ ARG_AUTH_TIMEOUT,
),
),
ActionCommand(
@@ -1265,7 +1305,8 @@ AUTH_COMMANDS = (
name="token",
help="Generate and print a JWT token for the given credentials",
description=(
- "Authenticate with username and password and print the access
token to stdout. "
+ "Authenticate with username and password, or through the browser
with --sso, "
+ "and print the access token to stdout. "
"Username and password are prompted interactively if not provided.
"
"In non-interactive runs, pass --username and either pass
--password "
"or pipe the password on stdin."
@@ -1275,6 +1316,9 @@ AUTH_COMMANDS = (
ARG_AUTH_URL,
ARG_AUTH_USERNAME,
ARG_AUTH_PASSWORD,
+ ARG_AUTH_SSO,
+ ARG_AUTH_NO_BROWSER,
+ ARG_AUTH_TIMEOUT,
),
),
)
diff --git a/airflow-ctl/src/airflowctl/ctl/commands/auth_command.py
b/airflow-ctl/src/airflowctl/ctl/commands/auth_command.py
index 6440000fce0..4d1103afd8e 100644
--- a/airflow-ctl/src/airflowctl/ctl/commands/auth_command.py
+++ b/airflow-ctl/src/airflowctl/ctl/commands/auth_command.py
@@ -27,10 +27,12 @@ import sys
import keyring
import rich
from keyring.errors import NoKeyringError
+from rich.console import Console
from rich.markup import escape
from airflowctl.api.client import (
NEW_API_CLIENT,
+ Client,
ClientKind,
Credentials,
_is_token_in_keyring,
@@ -40,7 +42,46 @@ from airflowctl.api.client import (
)
from airflowctl.api.datamodels.auth_generated import LoginBody
from airflowctl.ctl.console_formatting import AirflowConsole
-from airflowctl.exceptions import AirflowCtlCredentialInvalidException
+from airflowctl.ctl.utils.browser_login import get_authorization_code,
resolve_endpoint
+from airflowctl.exceptions import (
+ AirflowCtlBrowserLoginException,
+ AirflowCtlCredentialInvalidException,
+ AirflowCtlKeyringException,
+)
+
+DEFAULT_SSO_TIMEOUT = 300
+
+
+def _exit_on_sso_only_args(args) -> None:
+ if not args.sso and (args.no_browser or args.timeout is not None):
+ rich.print("[red]--no-browser and --timeout can only be used with
--sso.", file=sys.stderr)
+ sys.exit(1)
+
+
+def _get_token_with_browser(args, api_client: Client, api_url: str) -> str:
+ """Log in through the browser and return the CLI token, if the API server
offers it."""
+ metadata = api_client.login.get_cli_login_metadata(api_url)
+ if (
+ "authorization_code" not in metadata.grant_types_supported
+ or "S256" not in metadata.code_challenge_methods_supported
+ or not metadata.authorization_endpoint
+ or not metadata.token_endpoint
+ ):
+ raise AirflowCtlBrowserLoginException(f"{api_url} does not offer
browser login (--sso).")
+
+ authorization_url = resolve_endpoint(api_url,
metadata.authorization_endpoint)
+ token_url = resolve_endpoint(api_url, metadata.token_endpoint)
+ authorization_code = get_authorization_code(
+ authorization_url=authorization_url,
+ open_browser=not args.no_browser,
+ timeout=DEFAULT_SSO_TIMEOUT if args.timeout is None else args.timeout,
+ )
+ return api_client.login.login_with_authorization_code(
+ token_url,
+ code=authorization_code.code,
+ code_verifier=authorization_code.code_verifier,
+ redirect_uri=authorization_code.redirect_uri,
+ ).access_token
@provide_api_client(kind=ClientKind.AUTH)
@@ -53,6 +94,43 @@ def login(args, api_client=NEW_API_CLIENT) -> None:
password = args.password
token = args.api_token or os.environ.get("AIRFLOW_CLI_TOKEN")
+ _exit_on_sso_only_args(args)
+ if args.sso:
+ if args.api_token or username or password:
+ rich.print(
+ "[red]--sso is not compatible with --api-token, --username or
--password.", file=sys.stderr
+ )
+ 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))}", file=sys.stderr)
+ sys.exit(1)
+ not_stored_reason = ""
+ try:
+ if not Credentials(
+ api_url=api_url,
+ api_token=api_token,
+ api_environment=args.env,
+ client_kind=ClientKind.AUTH,
+ ).save(args.skip_keyring):
+ not_stored_reason = "The token was not stored."
+ except AirflowCtlKeyringException as e:
+ not_stored_reason = escape(str(e).splitlines()[0])
+ except (OSError, EOFError) as e:
+ not_stored_reason = escape(
+ f"Could not save the credentials: {str(e).splitlines()[0] if
str(e) else type(e).__name__}"
+ )
+ if not_stored_reason:
+ # Nothing stores the token, so this is the only way to use the
login that just happened.
+ print(api_token)
+ Console(stderr=True).print(
+ f"[yellow]{not_stored_reason}\nSet AIRFLOW_CLI_TOKEN to the
printed token to use it.[/yellow]"
+ )
+ return
+ rich.print(success_message)
+ return
+
# If credentials are incomplete, prompt interactively on a real terminal
if not token and not (username and password):
if not sys.stdin.isatty():
@@ -119,6 +197,19 @@ def login(args, api_client=NEW_API_CLIENT) -> None:
def get_token(args, api_client=NEW_API_CLIENT) -> None:
"""Generate and print a JWT token for the given credentials to stdout."""
api_url = args.api_url or get_default_api_url()
+
+ _exit_on_sso_only_args(args)
+ if args.sso:
+ if args.username or args.password:
+ rich.print("[red]--sso is not compatible with --username or
--password.", file=sys.stderr)
+ sys.exit(1)
+ try:
+ print(_get_token_with_browser(args, api_client, api_url))
+ except Exception as e:
+ rich.print(f"[red]Token generation failed:
{escape(str(e))}[/red]", file=sys.stderr)
+ sys.exit(1)
+ return
+
username = args.username
password = args.password
diff --git a/airflow-ctl/src/airflowctl/ctl/utils/browser_login.py
b/airflow-ctl/src/airflowctl/ctl/utils/browser_login.py
new file mode 100644
index 00000000000..09a0e2a0905
--- /dev/null
+++ b/airflow-ctl/src/airflowctl/ctl/utils/browser_login.py
@@ -0,0 +1,195 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Browser login with the authorization code flow and PKCE (RFC 7636), over a
loopback redirect (RFC 8252)."""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import os
+import secrets
+import sys
+import time
+import webbrowser
+from dataclasses import dataclass
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from urllib.parse import parse_qs, urlencode, urljoin, urlsplit
+
+from rich.console import Console
+from rich.markup import escape
+
+from airflowctl.exceptions import AirflowCtlBrowserLoginException
+
+CALLBACK_PATH = "/callback"
+_MAX_REQUEST_WAIT = 60.0
+# Sent before the code is exchanged for a token, so it must not claim that the
login worked.
+_CALLBACK_PAGE = (
+ b"<!doctype html><title>airflowctl</title>"
+ b"<p>You can close this window and return to the terminal to see the
result of the login.</p>"
+)
+_CALLBACK_FAILED_PAGE = (
+ b"<!doctype html><title>airflowctl</title><p>Login failed. Return to the
terminal for details.</p>"
+)
+_CALLBACK_WRONG_STATE_PAGE = (
+ b"<!doctype html><title>airflowctl</title>"
+ b"<p>This link is not for the current airflowctl login. "
+ b"Open the latest login URL printed in the terminal.</p>"
+)
+
+
+@dataclass
+class AuthorizationCode:
+ """Authorization code returned to the loopback redirect, with what the
token endpoint needs to redeem it."""
+
+ code: str
+ code_verifier: str
+ redirect_uri: str
+
+
+def build_pkce_pair() -> tuple[str, str]:
+ """Return a PKCE ``(code_verifier, code_challenge)`` pair for the ``S256``
method."""
+ code_verifier = secrets.token_urlsafe(64)
+ digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
+ code_challenge =
base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+ return code_verifier, code_challenge
+
+
+def resolve_endpoint(api_url: str, endpoint: str) -> str:
+ """Return the URL of a login metadata endpoint, which must be on the API
server."""
+ url = urljoin(api_url, endpoint)
+ if urlsplit(url)[:2] != urlsplit(api_url)[:2]:
+ raise AirflowCtlBrowserLoginException(f"{endpoint} is not an endpoint
of {api_url}.")
+ return url
+
+
+def _has_login_state(params: dict[str, str], state: str) -> bool:
+ """Return whether the callback parameters carry the ``state`` of this
login."""
+ # compare_digest raises TypeError on non-ASCII str.
+ return secrets.compare_digest(params.get("state", "").encode(),
state.encode())
+
+
+def _find_login_error(params: dict[str, str]) -> str | None:
+ """Return why the callback parameters of this login do not complete it, or
``None`` if they do."""
+ if "error" in params:
+ return f"Login refused: {params.get('error_description') or
params['error']}"
+ if not params.get("code"):
+ return "The login response contains no authorization code."
+ return None
+
+
+def _open_browser(url: str) -> None:
+ """Open ``url`` in the default browser without giving the browser process
our stdout."""
+ # A browser started by xdg-open keeps fd 1 open, so `TOKEN=$(airflowctl
auth token --sso)` would hang.
+ sys.stdout.flush()
+ try:
+ saved_stdout = os.dup(1)
+ except OSError:
+ webbrowser.open(url)
+ return
+ try:
+ os.dup2(2, 1)
+ webbrowser.open(url)
+ finally:
+ os.dup2(saved_stdout, 1)
+ os.close(saved_stdout)
+
+
+class _CallbackServer(HTTPServer):
+ state: str
+ callback_params: dict[str, str] | None = None
+ login_error: str | None = None
+
+
+class _CallbackHandler(BaseHTTPRequestHandler):
+ server: _CallbackServer
+ # server.timeout only bounds accept(), so an idle connection such as a
browser preconnect would block.
+ timeout = 2
+
+ def do_GET(self) -> None:
+ url = urlsplit(self.path)
+ if url.path != CALLBACK_PATH or self.server.callback_params is not
None:
+ self.send_error(404)
+ return
+ params = {key: values[0] for key, values in
parse_qs(url.query).items()}
+ if not _has_login_state(params, self.server.state):
+ # Any local process can reach this port, so only the real redirect
may end the wait.
+ self._send_page(400, _CALLBACK_WRONG_STATE_PAGE)
+ return
+ login_error = _find_login_error(params)
+ self.server.callback_params = params
+ self.server.login_error = login_error
+ self._send_page(400 if login_error else 200, _CALLBACK_FAILED_PAGE if
login_error else _CALLBACK_PAGE)
+
+ def _send_page(self, status: int, page: bytes) -> None:
+ self.send_response(status)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.end_headers()
+ self.wfile.write(page)
+
+ def log_message(self, format, *args) -> None:
+ # Request lines contain the authorization code.
+ pass
+
+
+def get_authorization_code(
+ *, authorization_url: str, open_browser: bool, timeout: float
+) -> AuthorizationCode:
+ """
+ Run the browser part of the login and return the authorization code it
produced.
+
+ :param authorization_url: URL of the ``authorization_endpoint`` from the
CLI login metadata
+ :param open_browser: open the login page in the default browser, otherwise
only print its URL
+ :param timeout: seconds to wait for the user to finish logging in
+ """
+ code_verifier, code_challenge = build_pkce_pair()
+ state = secrets.token_urlsafe(32)
+
+ with _CallbackServer(("127.0.0.1", 0), _CallbackHandler) as server:
+ server.state = state
+ redirect_uri =
f"http://127.0.0.1:{server.server_address[1]}{CALLBACK_PATH}"
+ query = urlencode(
+ {
+ "redirect_uri": redirect_uri,
+ "state": state,
+ "code_challenge": code_challenge,
+ "code_challenge_method": "S256",
+ }
+ )
+ separator = "&" if urlsplit(authorization_url).query else "?"
+ login_url = f"{authorization_url}{separator}{query}"
+ # `auth token --sso` prints the token on stdout.
+ Console(stderr=True, soft_wrap=True).print(
+ f"[blue]Log in from your browser:[/blue] {escape(login_url)}"
+ )
+ if open_browser:
+ _open_browser(login_url)
+
+ deadline = time.monotonic() + timeout
+ while server.callback_params is None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise AirflowCtlBrowserLoginException(f"No login completed
within {timeout:g} seconds.")
+ # poll() rejects a timeout above 2**31 ms, which a long --timeout
exceeds.
+ server.timeout = min(remaining, _MAX_REQUEST_WAIT)
+ server.handle_request()
+ params = server.callback_params
+ login_error = server.login_error
+
+ if login_error:
+ raise AirflowCtlBrowserLoginException(login_error)
+ return AuthorizationCode(code=params["code"], code_verifier=code_verifier,
redirect_uri=redirect_uri)
diff --git a/airflow-ctl/src/airflowctl/exceptions.py
b/airflow-ctl/src/airflowctl/exceptions.py
index dc52d09ca52..b14ce06e7a6 100644
--- a/airflow-ctl/src/airflowctl/exceptions.py
+++ b/airflow-ctl/src/airflowctl/exceptions.py
@@ -48,3 +48,7 @@ class AirflowCtlConnectionException(AirflowCtlException):
class AirflowCtlKeyringException(AirflowCtlException):
"""Raise when a keyring error occurs while performing an operation."""
+
+
+class AirflowCtlBrowserLoginException(AirflowCtlException):
+ """Raise when the browser login of ``auth login --sso`` cannot complete."""
diff --git a/airflow-ctl/tests/airflow_ctl/api/test_client.py
b/airflow-ctl/tests/airflow_ctl/api/test_client.py
index aa5120c04d6..23679d4e68d 100644
--- a/airflow-ctl/tests/airflow_ctl/api/test_client.py
+++ b/airflow-ctl/tests/airflow_ctl/api/test_client.py
@@ -433,6 +433,24 @@ class TestCredentials:
monkeypatch.setattr("airflowctl.api.client.keyring", mock_keyring)
return mock_keyring
+ @pytest.mark.parametrize(
+ ("skip_keyring", "debug_mode", "expected"),
+ [
+ pytest.param(False, False, True, id="keyring"),
+ pytest.param(True, False, False, id="skip-keyring"),
+ pytest.param(True, True, True, id="skip-keyring-in-debug-mode"),
+ ],
+ )
+ def test_save_returns_whether_token_is_stored(
+ self, keyring_store, monkeypatch, skip_keyring, debug_mode, expected
+ ):
+ if debug_mode:
+ monkeypatch.setenv("AIRFLOW_CLI_DEBUG_MODE", "true")
+
+ credentials = Credentials(api_url="http://localhost:8080",
api_token="TOKEN", api_environment="prod")
+
+ assert credentials.save(skip_keyring=skip_keyring) is expected
+
def test_save_skip_keyring_does_not_reuse_token_of_earlier_login(self,
keyring_store):
Credentials(api_url="http://old:8080", api_token="OLD_TOKEN",
api_environment="prod").save()
Credentials(api_url="http://new:8080", api_token="NEW_TOKEN",
api_environment="prod").save(
@@ -496,9 +514,11 @@ class TestCredentials:
Credentials(api_url="http://old:8080", api_token="OLD_TOKEN",
api_environment="prod").save()
keyring_store.set_password.side_effect = error
- with pytest.raises(type(error)):
+ with pytest.raises(AirflowCtlKeyringException) as excinfo:
Credentials(api_url="http://new:8080", api_token="NEW_TOKEN",
api_environment="prod").save()
+ assert excinfo.value.__cause__ is error
+
credentials = Credentials(client_kind=ClientKind.CLI,
api_environment="prod").load()
assert (credentials.api_url, credentials.api_token) ==
("http://new:8080", None)
@@ -658,6 +678,21 @@ class TestCredentials:
with pytest.raises(AirflowCtlCredentialInvalidException, match="is not
a JSON object"):
Credentials(client_kind=ClientKind.CLI).load()
+ @patch("airflowctl.api.client.keyring", autospec=True)
+ def test_load_auth_kind_skips_a_locked_keyring(self, mock_keyring,
monkeypatch, tmp_path):
+ """`auth login` sends no token, so a locked keyring must not stop it
before it starts."""
+ monkeypatch.setenv("AIRFLOW_HOME", str(tmp_path))
+ monkeypatch.setenv("AIRFLOW_CLI_ENVIRONMENT", "TEST_LOCKED_KEYRING")
+ (tmp_path / "TEST_LOCKED_KEYRING.json").write_text(
+ json.dumps({"api_url": "http://x"}), encoding="utf-8"
+ )
+ mock_keyring.get_password.side_effect = KeyringLocked("Keyring is
locked")
+
+ credentials = Credentials(client_kind=ClientKind.AUTH).load()
+
+ assert (credentials.api_url, credentials.api_token) == ("http://x",
None)
+ mock_keyring.get_password.assert_not_called()
+
def test_load_tolerates_an_unusable_file_for_auth_login(self, monkeypatch,
tmp_path):
"""`auth login` is the recovery the error recommends, so it must
survive an unusable file."""
monkeypatch.setenv("AIRFLOW_HOME", str(tmp_path))
diff --git a/airflow-ctl/tests/airflow_ctl/api/test_operations.py
b/airflow-ctl/tests/airflow_ctl/api/test_operations.py
index 0a963bbd61b..4b378164818 100644
--- a/airflow-ctl/tests/airflow_ctl/api/test_operations.py
+++ b/airflow-ctl/tests/airflow_ctl/api/test_operations.py
@@ -22,7 +22,7 @@ import json
import uuid
from math import ceil
from typing import TYPE_CHECKING
-from unittest.mock import Mock
+from unittest.mock import Mock, patch
import httpx
import pytest
@@ -122,7 +122,12 @@ from airflowctl.api.datamodels.generated import (
XComResponse,
XComResponseNative,
)
-from airflowctl.api.operations import BaseOperations, _build_query_params,
_tolerant_model
+from airflowctl.api.operations import (
+ BaseOperations,
+ ServerResponseError,
+ _build_query_params,
+ _tolerant_model,
+)
from airflowctl.exceptions import AirflowCtlConnectionException
if TYPE_CHECKING:
@@ -2979,6 +2984,117 @@ class TestAuthOperations:
)
assert response.access_token == "NO_TOKEN"
+ def test_get_cli_login_metadata(self):
+ metadata = {
+ "grant_types_supported": ["password", "authorization_code"],
+ "code_challenge_methods_supported": ["S256"],
+ "authorization_endpoint": "/auth/login/cli",
+ "device_authorization_endpoint": None,
+ "token_endpoint": "/auth/token/cli",
+ }
+
+ def handle_request(request: httpx.Request) -> httpx.Response:
+ assert request.url.path == "/prefix/api/v2/auth/cli/metadata"
+ return httpx.Response(200, json=metadata)
+
+ client =
make_api_client(transport=httpx.MockTransport(handle_request),
kind=ClientKind.AUTH)
+
+ response = client.login.get_cli_login_metadata("http://server/prefix/")
+
+ assert response.model_dump() == metadata
+
+ @pytest.mark.parametrize(
+ "response",
+ [
+ pytest.param(httpx.Response(404, json={"detail": "Not Found"}),
id="json"),
+ pytest.param(httpx.Response(404, text="Not Found"), id="text"),
+ ],
+ )
+ def test_get_cli_login_metadata_without_discovery(self, response):
+ client = make_api_client(
+ transport=httpx.MockTransport(lambda request: response),
kind=ClientKind.AUTH
+ )
+
+ metadata = client.login.get_cli_login_metadata("http://server")
+
+ assert metadata.grant_types_supported == []
+ assert metadata.token_endpoint is None
+
+ def test_get_cli_login_metadata_server_error(self):
+ client = make_api_client(
+ transport=httpx.MockTransport(lambda request: httpx.Response(403,
json={"detail": "Forbidden"})),
+ kind=ClientKind.AUTH,
+ )
+
+ with pytest.raises(ServerResponseError):
+ client.login.get_cli_login_metadata("http://server")
+
+ def test_login_with_authorization_code(self):
+ def handle_request(request: httpx.Request) -> httpx.Response:
+ assert str(request.url) == "http://server/auth/token/cli"
+ assert json.loads(request.content) == {
+ "grant_type": "authorization_code",
+ "code": "code",
+ "code_verifier": "verifier",
+ "redirect_uri": "http://127.0.0.1:1234/callback",
+ }
+ return httpx.Response(201, json={"access_token": "TOKEN"})
+
+ client =
make_api_client(transport=httpx.MockTransport(handle_request),
kind=ClientKind.AUTH)
+
+ response = client.login.login_with_authorization_code(
+ "http://server/auth/token/cli",
+ code="code",
+ code_verifier="verifier",
+ redirect_uri="http://127.0.0.1:1234/callback",
+ )
+
+ assert response.access_token == "TOKEN"
+
+ @patch("airflowctl.api.client.Client.request.retry.sleep", autospec=True)
+ def test_login_with_authorization_code_retries_connect_error(self,
mock_sleep):
+ outcomes: list[httpx.Response | httpx.ConnectError] = [
+ httpx.ConnectError("Connection refused"),
+ httpx.Response(201, json={"access_token": "TOKEN"}),
+ ]
+
+ def handle_request(request: httpx.Request) -> httpx.Response:
+ outcome = outcomes.pop(0)
+ if isinstance(outcome, httpx.ConnectError):
+ raise outcome
+ return outcome
+
+ client =
make_api_client(transport=httpx.MockTransport(handle_request),
kind=ClientKind.AUTH)
+
+ response = client.login.login_with_authorization_code(
+ "http://server/auth/token/cli",
+ code="code",
+ code_verifier="verifier",
+ redirect_uri="http://127.0.0.1:1234/callback",
+ )
+
+ assert response.access_token == "TOKEN"
+ assert outcomes == []
+
+ def test_login_with_authorization_code_is_not_retried(self):
+ requests = []
+
+ def handle_request(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ return httpx.Response(503, json={"detail": "Unavailable"})
+
+ client =
make_api_client(transport=httpx.MockTransport(handle_request),
kind=ClientKind.AUTH)
+
+ with pytest.raises(ServerResponseError):
+ client.login.login_with_authorization_code(
+ "http://server/auth/token/cli",
+ code="code",
+ code_verifier="verifier",
+ redirect_uri="http://127.0.0.1:1234/callback",
+ )
+
+ assert len(requests) == 1
+
class TestXComOperations:
"""Test suite for XCom operations."""
diff --git a/airflow-ctl/tests/airflow_ctl/ctl/commands/test_auth_command.py
b/airflow-ctl/tests/airflow_ctl/ctl/commands/test_auth_command.py
index 11a30dd3741..554358f6656 100644
--- a/airflow-ctl/tests/airflow_ctl/ctl/commands/test_auth_command.py
+++ b/airflow-ctl/tests/airflow_ctl/ctl/commands/test_auth_command.py
@@ -22,12 +22,44 @@ import tempfile
from unittest import mock
from unittest.mock import patch
+import httpx
import pytest
+import structlog
+from keyring.errors import KeyringLocked, NoKeyringError, PasswordSetError
from airflowctl.api.client import Client, ClientKind
from airflowctl.api.datamodels.auth_generated import LoginResponse
from airflowctl.ctl import cli_parser
from airflowctl.ctl.commands import auth_command
+from airflowctl.ctl.utils.browser_login import AuthorizationCode
+from airflowctl.exceptions import AirflowCtlBrowserLoginException
+
+SSO_METADATA = {
+ "grant_types_supported": ["password", "refresh_token",
"authorization_code"],
+ "code_challenge_methods_supported": ["S256"],
+ "authorization_endpoint": "/auth/login/cli",
+ "device_authorization_endpoint": None,
+ "token_endpoint": "/auth/token/cli",
+}
+AUTHORIZATION_CODE = AuthorizationCode(
+ code="code", code_verifier="verifier",
redirect_uri="http://127.0.0.1:1234/callback"
+)
+
+
+def _make_sso_api_client(metadata: dict) -> Client:
+ def handle_request(request: httpx.Request) -> httpx.Response:
+ if request.url.path == "/api/v2/auth/cli/metadata":
+ return httpx.Response(200, json=metadata)
+ assert str(request.url) == "http://localhost:8080/auth/token/cli"
+ assert json.loads(request.content)["code_verifier"] == "verifier"
+ return httpx.Response(201, json={"access_token": "SSO_TOKEN"})
+
+ return Client(
+ base_url="test://server",
+ transport=httpx.MockTransport(handle_request),
+ token="",
+ kind=ClientKind.AUTH,
+ )
class TestCliAuthCommands:
@@ -298,6 +330,293 @@ class TestCliAuthCommands:
api_client=api_client,
)
+ @patch("airflowctl.ctl.commands.auth_command.get_authorization_code",
autospec=True)
+ @patch("airflowctl.api.client.keyring")
+ def test_login_with_sso(self, mock_keyring, mock_get_authorization_code,
monkeypatch, tmp_path):
+ monkeypatch.setenv("AIRFLOW_HOME", str(tmp_path))
+ mock_get_authorization_code.return_value = AUTHORIZATION_CODE
+ mock_keyring.get_password.return_value = None
+
+ auth_command.login(
+ self.parser.parse_args(
+ [
+ "auth",
+ "login",
+ "--api-url",
+ "http://localhost:8080",
+ "--sso",
+ "--no-browser",
+ "--timeout",
+ "30",
+ ]
+ ),
+ api_client=_make_sso_api_client(SSO_METADATA),
+ )
+
+ mock_get_authorization_code.assert_called_once_with(
+ authorization_url="http://localhost:8080/auth/login/cli",
+ open_browser=False,
+ timeout=30,
+ )
+ mock_keyring.set_password.assert_called_once_with("airflowctl",
"api_token_production", "SSO_TOKEN")
+
+ @patch("airflowctl.ctl.commands.auth_command.get_authorization_code",
autospec=True)
+ @patch("airflowctl.api.client.keyring")
+ def test_login_with_sso_skip_keyring_prints_token(
+ self, mock_keyring, mock_get_authorization_code, capsys, monkeypatch,
tmp_path
+ ):
+ monkeypatch.setenv("AIRFLOW_HOME", str(tmp_path))
+ mock_get_authorization_code.return_value = AUTHORIZATION_CODE
+ mock_keyring.get_password.return_value = None
+
+ auth_command.login(
+ self.parser.parse_args(
+ ["auth", "login", "--api-url", "http://localhost:8080",
"--sso", "--skip-keyring"]
+ ),
+ api_client=_make_sso_api_client(SSO_METADATA),
+ )
+
+ assert capsys.readouterr().out == "SSO_TOKEN\n"
+ mock_keyring.set_password.assert_not_called()
+
+ @patch("airflowctl.ctl.commands.auth_command.get_authorization_code",
autospec=True)
+ @patch("airflowctl.api.client.keyring", autospec=True)
+ def
test_login_with_sso_skip_keyring_in_debug_mode_reports_the_stored_token(
+ self, mock_keyring, mock_get_authorization_code, capsys, monkeypatch,
tmp_path
+ ):
+ monkeypatch.setenv("AIRFLOW_HOME", str(tmp_path))
+ monkeypatch.setenv("AIRFLOW_CLI_DEBUG_MODE", "true")
+ mock_get_authorization_code.return_value = AUTHORIZATION_CODE
+
+ auth_command.login(
+ self.parser.parse_args(
+ ["auth", "login", "--api-url", "http://localhost:8080",
"--sso", "--skip-keyring"]
+ ),
+ api_client=_make_sso_api_client(SSO_METADATA),
+ )
+
+ captured = capsys.readouterr()
+ assert "SSO_TOKEN" not in captured.out
+ assert "Login successful!" in captured.out
+ assert captured.err == ""
+ debug_creds = json.loads((tmp_path /
"debug_creds_production.json").read_text())
+ assert debug_creds == {"api_token_production": "SSO_TOKEN"}
+
+ @pytest.mark.parametrize(
+ ("error", "expected_cause"),
+ [
+ pytest.param(
+ NoKeyringError("no backend"),
+ "Keyring backend is not available. Cannot save credentials.",
+ id="no-keyring",
+ ),
+ pytest.param(
+ KeyringLocked("Failed to unlock!"),
+ "Cannot save credentials to the keyring: Failed to unlock!",
+ id="locked",
+ ),
+ pytest.param(
+ PasswordSetError(),
+ "Cannot save credentials to the keyring: PasswordSetError",
+ id="set-error",
+ ),
+ pytest.param(
+ ValueError("Incorrect Password"),
+ "Cannot save credentials to the keyring: Incorrect Password",
+ id="wrong-password",
+ ),
+ ],
+ )
+ # structlog prints to stdout unless configured, which __main__ does but
the tests don't.
+ @patch("airflowctl.api.client.log", spec=structlog.stdlib.BoundLogger)
+ @patch("airflowctl.ctl.commands.auth_command.get_authorization_code",
autospec=True)
+ @patch("airflowctl.api.client.keyring")
+ def test_login_with_sso_keyring_failure_prints_token(
+ self,
+ mock_keyring,
+ mock_get_authorization_code,
+ mock_log,
+ error,
+ expected_cause,
+ capsys,
+ monkeypatch,
+ tmp_path,
+ ):
+ monkeypatch.setenv("AIRFLOW_HOME", str(tmp_path))
+ mock_get_authorization_code.return_value = AUTHORIZATION_CODE
+ mock_keyring.get_password.return_value = None
+ mock_keyring.set_password.side_effect = error
+
+ auth_command.login(
+ self.parser.parse_args(["auth", "login", "--api-url",
"http://localhost:8080", "--sso"]),
+ api_client=_make_sso_api_client(SSO_METADATA),
+ )
+
+ captured = capsys.readouterr()
+ assert captured.out == "SSO_TOKEN\n"
+ assert captured.err.splitlines() == [
+ expected_cause,
+ "Set AIRFLOW_CLI_TOKEN to the printed token to use it.",
+ ]
+
+ @pytest.mark.parametrize(
+ ("error", "expected_cause"),
+ [
+ pytest.param(
+ PermissionError(13, "Permission denied"),
+ "Could not save the credentials: [Errno 13] Permission denied",
+ id="read-only-home",
+ ),
+ pytest.param(
+ OSError(28, "No space left on device"),
+ "Could not save the credentials: [Errno 28] No space left on
device",
+ id="disk-full",
+ ),
+ pytest.param(EOFError(), "Could not save the credentials:
EOFError", id="no-tty-for-password"),
+ ],
+ )
+ @patch("airflowctl.ctl.commands.auth_command.Credentials.save",
autospec=True)
+ @patch("airflowctl.ctl.commands.auth_command.get_authorization_code",
autospec=True)
+ def test_login_with_sso_save_failure_prints_token(
+ self, mock_get_authorization_code, mock_save, error, expected_cause,
capsys
+ ):
+ mock_get_authorization_code.return_value = AUTHORIZATION_CODE
+ mock_save.side_effect = error
+
+ auth_command.login(
+ self.parser.parse_args(["auth", "login", "--api-url",
"http://localhost:8080", "--sso"]),
+ api_client=_make_sso_api_client(SSO_METADATA),
+ )
+
+ captured = capsys.readouterr()
+ assert captured.out == "SSO_TOKEN\n"
+ assert captured.err.splitlines() == [
+ expected_cause,
+ "Set AIRFLOW_CLI_TOKEN to the printed token to use it.",
+ ]
+
+ @pytest.mark.parametrize(
+ "metadata",
+ [
+ pytest.param({**SSO_METADATA, "grant_types_supported":
["password"]}, id="no-authorization-code"),
+ pytest.param({**SSO_METADATA, "code_challenge_methods_supported":
["plain"]}, id="no-s256"),
+ pytest.param({**SSO_METADATA, "authorization_endpoint": None},
id="no-authorization-endpoint"),
+ pytest.param(
+ {**SSO_METADATA, "authorization_endpoint":
"//evil.example.com/login"},
+ id="foreign-authorization-endpoint",
+ ),
+ pytest.param(
+ {**SSO_METADATA, "token_endpoint":
"https://evil.example.com/token"},
+ id="foreign-token-endpoint",
+ ),
+ ],
+ )
+ @patch("airflowctl.ctl.commands.auth_command.get_authorization_code",
autospec=True)
+ def test_login_with_sso_not_offered(self, mock_get_authorization_code,
metadata):
+ with pytest.raises(SystemExit):
+ auth_command.login(
+ self.parser.parse_args(["auth", "login", "--api-url",
"http://localhost:8080", "--sso"]),
+ api_client=_make_sso_api_client(metadata),
+ )
+
+ mock_get_authorization_code.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "extra_args",
+ [["--username", "user"], ["--password", "pass"], ["--api-token",
"token"]],
+ )
+ @patch("airflowctl.ctl.commands.auth_command.get_authorization_code",
autospec=True)
+ def test_login_with_sso_incompatible_args(self,
mock_get_authorization_code, extra_args, capsys):
+ with pytest.raises(SystemExit):
+ auth_command.login(
+ self.parser.parse_args(
+ ["auth", "login", "--api-url", "http://localhost:8080",
"--sso", *extra_args]
+ ),
+ api_client=_make_sso_api_client(SSO_METADATA),
+ )
+
+ mock_get_authorization_code.assert_not_called()
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ assert "--sso is not compatible" in captured.err
+
+ @pytest.mark.parametrize("extra_args", [["--username", "user"],
["--password", "pass"]])
+ @patch("airflowctl.ctl.commands.auth_command.get_authorization_code",
autospec=True)
+ def test_get_token_with_sso_incompatible_args(self,
mock_get_authorization_code, extra_args, capsys):
+ with pytest.raises(SystemExit):
+ auth_command.get_token(
+ self.parser.parse_args(
+ ["auth", "token", "--api-url", "http://localhost:8080",
"--sso", *extra_args]
+ ),
+ api_client=_make_sso_api_client(SSO_METADATA),
+ )
+
+ mock_get_authorization_code.assert_not_called()
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ assert "--sso is not compatible" in captured.err
+
+ @pytest.mark.parametrize(
+ ("command", "subcommand"),
+ [pytest.param(auth_command.login, "login", id="login"),
(auth_command.get_token, "token")],
+ )
+ @patch("airflowctl.ctl.commands.auth_command.get_authorization_code",
autospec=True)
+ def test_sso_error_is_not_read_as_markup(self,
mock_get_authorization_code, command, subcommand, capsys):
+ mock_get_authorization_code.side_effect =
AirflowCtlBrowserLoginException("refused [/oops]")
+
+ with pytest.raises(SystemExit):
+ command(
+ self.parser.parse_args(["auth", subcommand, "--api-url",
"http://localhost:8080", "--sso"]),
+ api_client=_make_sso_api_client(SSO_METADATA),
+ )
+
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ assert "refused [/oops]" in captured.err
+
+ @patch("airflowctl.ctl.commands.auth_command.get_authorization_code",
autospec=True)
+ def test_get_token_with_sso(self, mock_get_authorization_code, capsys):
+ mock_get_authorization_code.return_value = AUTHORIZATION_CODE
+
+ auth_command.get_token(
+ self.parser.parse_args(["auth", "token", "--api-url",
"http://localhost:8080", "--sso"]),
+ api_client=_make_sso_api_client(SSO_METADATA),
+ )
+
+ assert capsys.readouterr().out == "SSO_TOKEN\n"
+ mock_get_authorization_code.assert_called_once_with(
+ authorization_url="http://localhost:8080/auth/login/cli",
+ open_browser=True,
+ timeout=auth_command.DEFAULT_SSO_TIMEOUT,
+ )
+
+ @pytest.mark.parametrize(
+ ("command", "args"),
+ [
+ pytest.param(auth_command.login, ["login", "--api-token",
"token"], id="login"),
+ pytest.param(auth_command.get_token, ["token", "--username", "u",
"--password", "p"], id="token"),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "extra_args",
+ [pytest.param(["--no-browser"], id="no-browser"),
pytest.param(["--timeout", "30"], id="timeout")],
+ )
+ @patch("airflowctl.api.client.keyring")
+ def test_sso_only_args_without_sso(self, mock_keyring, command, args,
extra_args, capsys):
+ api_client = mock.MagicMock()
+
+ with pytest.raises(SystemExit):
+ command(
+ self.parser.parse_args(["auth", *args, "--api-url",
"http://localhost:8080", *extra_args]),
+ api_client=api_client,
+ )
+
+ api_client.login.login_with_username_and_password.assert_not_called()
+ mock_keyring.set_password.assert_not_called()
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ assert "--no-browser and --timeout can only be used with --sso" in
captured.err
+
class TestCliAuthToken:
parser = cli_parser.get_parser()
diff --git a/airflow-ctl/tests/airflow_ctl/ctl/test_cli_config.py
b/airflow-ctl/tests/airflow_ctl/ctl/test_cli_config.py
index a88d03c6a93..4cf614a29a7 100644
--- a/airflow-ctl/tests/airflow_ctl/ctl/test_cli_config.py
+++ b/airflow-ctl/tests/airflow_ctl/ctl/test_cli_config.py
@@ -64,6 +64,7 @@ from airflowctl.ctl.cli_config import (
is_iso_datetime_type,
json_dict_type,
merge_commands,
+ positive_finite_float,
safe_call_command,
)
from airflowctl.ctl.console_formatting import AirflowConsole
@@ -669,6 +670,14 @@ class TestCommandFactory:
class TestCliConfigMethods:
+ @pytest.mark.parametrize("value", ["0", "-1", "inf", "nan", "abc"])
+ def test_positive_finite_float_rejects_invalid_values(self, value):
+ with pytest.raises(argparse.ArgumentTypeError, match="invalid positive
number"):
+ positive_finite_float(value)
+
+ def test_positive_finite_float_accepts_positive_values(self):
+ assert positive_finite_float("0.5") == 0.5
+
@pytest.mark.parametrize("method", ["GET", "HEAD", "OPTIONS", "POST",
"PUT", "PATCH", "DELETE"])
@pytest.mark.parametrize(
("failure", "ambiguous"),
diff --git a/airflow-ctl/tests/airflow_ctl/ctl/utils/test_browser_login.py
b/airflow-ctl/tests/airflow_ctl/ctl/utils/test_browser_login.py
new file mode 100644
index 00000000000..842e6f3bab3
--- /dev/null
+++ b/airflow-ctl/tests/airflow_ctl/ctl/utils/test_browser_login.py
@@ -0,0 +1,281 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import base64
+import hashlib
+import os
+import queue
+import socket
+import threading
+import urllib.error
+import urllib.request
+from unittest.mock import patch
+from urllib.parse import parse_qs, urlencode, urlsplit
+
+import pytest
+
+from airflowctl.ctl.utils.browser_login import build_pkce_pair,
get_authorization_code, resolve_endpoint
+from airflowctl.exceptions import AirflowCtlBrowserLoginException
+
+
+def _fake_browser(build_callback_query, pages):
+ """Return a ``webbrowser.open`` stand-in that calls back and puts
``(status, body)`` on ``pages``."""
+
+ def open_login_page(login_url):
+ params = {key: values[0] for key, values in
parse_qs(urlsplit(login_url).query).items()}
+ callback_url =
f"{params['redirect_uri']}?{urlencode(build_callback_query(params))}"
+
+ def call_back():
+ redirect = urlsplit(params["redirect_uri"])
+ with pytest.raises(urllib.error.HTTPError):
+ urllib.request.urlopen(f"http://{redirect.netloc}/favicon.ico")
+ try:
+ response = urllib.request.urlopen(callback_url)
+ except urllib.error.HTTPError as e:
+ response = e
+ pages.put((response.status, response.read()))
+
+ threading.Thread(target=call_back, daemon=True).start()
+ return True
+
+ return open_login_page
+
+
+def test_resolve_endpoint():
+ assert (
+ resolve_endpoint("https://airflow.example.com/prefix",
"/prefix/auth/token/cli")
+ == "https://airflow.example.com/prefix/auth/token/cli"
+ )
+
+
+def test_build_pkce_pair():
+ code_verifier, code_challenge = build_pkce_pair()
+
+ assert 43 <= len(code_verifier) <= 128
+ expected =
base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).rstrip(b"=").decode()
+ assert code_challenge == expected
+
+
+@patch("airflowctl.ctl.utils.browser_login.webbrowser.open", autospec=True)
+def test_get_authorization_code(mock_open, capsys):
+ seen_params = {}
+ pages = queue.Queue()
+
+ def build_callback_query(params):
+ seen_params.update(params)
+ return {"code": "the-code", "state": params["state"]}
+
+ mock_open.side_effect = _fake_browser(build_callback_query, pages)
+
+ result = get_authorization_code(
+ authorization_url="https://airflow.example.com/prefix/auth/login/cli",
+ open_browser=True,
+ timeout=10,
+ )
+
+ printed = capsys.readouterr()
+ assert printed.out == ""
+ assert printed.err == f"Log in from your browser:
{mock_open.call_args.args[0]}\n"
+ login_url = urlsplit(mock_open.call_args.args[0])
+ assert (login_url.netloc, login_url.path) == ("airflow.example.com",
"/prefix/auth/login/cli")
+ assert seen_params["code_challenge_method"] == "S256"
+ assert result.code == "the-code"
+ assert result.redirect_uri == seen_params["redirect_uri"]
+ assert urlsplit(result.redirect_uri).hostname == "127.0.0.1"
+ challenge =
base64.urlsafe_b64encode(hashlib.sha256(result.code_verifier.encode()).digest())
+ assert challenge.rstrip(b"=").decode() == seen_params["code_challenge"]
+ status, page = pages.get(timeout=5)
+ assert status == 200
+ assert b"return to the terminal to see the result" in page
+
+
[email protected](
+ ("build_callback_query", "message"),
+ [
+ pytest.param(
+ lambda params: {
+ "error": "access_denied",
+ "error_description": "User refused",
+ "state": params["state"],
+ },
+ "Login refused: User refused",
+ id="error",
+ ),
+ pytest.param(
+ lambda params: {"state": params["state"]},
+ "contains no authorization code",
+ id="no-code",
+ ),
+ ],
+)
+@patch("airflowctl.ctl.utils.browser_login.webbrowser.open", autospec=True)
+def test_get_authorization_code_rejects_callback(mock_open,
build_callback_query, message):
+ pages = queue.Queue()
+ mock_open.side_effect = _fake_browser(build_callback_query, pages)
+
+ with pytest.raises(AirflowCtlBrowserLoginException, match=message):
+ get_authorization_code(
+ authorization_url="http://localhost:8080/auth/login/cli",
+ open_browser=True,
+ timeout=10,
+ )
+
+ status, page = pages.get(timeout=5)
+ assert status == 400
+ assert b"Login failed" in page
+
+
[email protected](
+ "stray_query",
+ [
+ pytest.param({"code": "stray-code", "state": "forged"},
id="state-mismatch"),
+ pytest.param({"code": "stray-code", "state": "forgé"},
id="non-ascii-state"),
+ pytest.param({"code": "stray-code"}, id="no-state"),
+ pytest.param({"error": "access_denied", "state": "forged"},
id="error-with-wrong-state"),
+ ],
+)
+@patch("airflowctl.ctl.utils.browser_login.webbrowser.open", autospec=True)
+def test_get_authorization_code_keeps_waiting_after_stray_callback(mock_open,
stray_query):
+ stray_pages = []
+
+ def open_login_page(login_url):
+ params = {key: values[0] for key, values in
parse_qs(urlsplit(login_url).query).items()}
+
+ def call_back():
+ try:
+
urllib.request.urlopen(f"{params['redirect_uri']}?{urlencode(stray_query)}")
+ except urllib.error.HTTPError as e:
+ stray_pages.append((e.code, e.read()))
+ query = urlencode({"code": "the-code", "state": params["state"]})
+ urllib.request.urlopen(f"{params['redirect_uri']}?{query}").read()
+
+ threading.Thread(target=call_back, daemon=True).start()
+ return True
+
+ mock_open.side_effect = open_login_page
+
+ result = get_authorization_code(
+ authorization_url="http://localhost:8080/auth/login/cli",
+ open_browser=True,
+ timeout=10,
+ )
+
+ assert result.code == "the-code"
+ assert len(stray_pages) == 1
+ assert stray_pages[0][0] == 400
+ assert b"not for the current airflowctl login" in stray_pages[0][1]
+
+
+@patch("airflowctl.ctl.utils.browser_login.webbrowser.open", autospec=True)
+def test_get_authorization_code_keeps_browser_output_off_stdout(mock_open,
capfd):
+ fake_browser = _fake_browser(lambda params: {"code": "the-code", "state":
params["state"]}, queue.Queue())
+
+ def open_noisy_browser(login_url):
+ os.write(1, b"Opening in existing browser session.\n")
+ return fake_browser(login_url)
+
+ mock_open.side_effect = open_noisy_browser
+
+ get_authorization_code(
+ authorization_url="http://localhost:8080/auth/login/cli",
+ open_browser=True,
+ timeout=10,
+ )
+ os.write(1, b"token\n")
+
+ captured = capfd.readouterr()
+ assert captured.out == "token\n"
+ assert "Opening in existing browser session." in captured.err
+
+
+@patch("airflowctl.ctl.utils.browser_login.webbrowser.open", autospec=True)
+def test_get_authorization_code_keeps_endpoint_query(mock_open):
+ mock_open.side_effect = _fake_browser(
+ lambda params: {"code": "the-code", "state": params["state"]},
queue.Queue()
+ )
+
+ result = get_authorization_code(
+
authorization_url="https://airflow.example.com/auth/login/cli?tenant=a",
+ open_browser=True,
+ timeout=10,
+ )
+
+ assert result.code == "the-code"
+ login_params = parse_qs(urlsplit(mock_open.call_args.args[0]).query)
+ assert login_params["tenant"] == ["a"]
+ assert login_params["redirect_uri"] == [result.redirect_uri]
+
+
+@patch("airflowctl.ctl.utils.browser_login.webbrowser.open", autospec=True)
+def test_get_authorization_code_accepts_a_very_long_timeout(mock_open):
+ mock_open.side_effect = _fake_browser(
+ lambda params: {"code": "the-code", "state": params["state"]},
queue.Queue()
+ )
+
+ result = get_authorization_code(
+ authorization_url="http://localhost:8080/auth/login/cli",
+ open_browser=True,
+ timeout=10_000_000,
+ )
+
+ assert result.code == "the-code"
+
+
+@patch("airflowctl.ctl.utils.browser_login.webbrowser.open", autospec=True)
+def test_get_authorization_code_drops_idle_connection(mock_open):
+ closed_by_server = []
+
+ def open_login_page(login_url):
+ params = {key: values[0] for key, values in
parse_qs(urlsplit(login_url).query).items()}
+ redirect = urlsplit(params["redirect_uri"])
+
+ def call_back():
+ with socket.create_connection((redirect.hostname, redirect.port),
timeout=10) as idle:
+ try:
+ closed_by_server.append(idle.recv(1) == b"")
+ except TimeoutError:
+ closed_by_server.append(False)
+ query = urlencode({"code": "the-code", "state": params["state"]})
+ urllib.request.urlopen(f"{params['redirect_uri']}?{query}").read()
+
+ threading.Thread(target=call_back, daemon=True).start()
+ return True
+
+ mock_open.side_effect = open_login_page
+
+ result = get_authorization_code(
+ authorization_url="http://localhost:8080/auth/login/cli",
+ open_browser=True,
+ timeout=30,
+ )
+
+ assert closed_by_server == [True]
+ assert result.code == "the-code"
+
+
+@patch("airflowctl.ctl.utils.browser_login.webbrowser.open", autospec=True)
+def test_get_authorization_code_no_browser_times_out(mock_open):
+ with pytest.raises(AirflowCtlBrowserLoginException, match="No login
completed within 0.2 seconds"):
+ get_authorization_code(
+ authorization_url="http://localhost:8080/auth/login/cli",
+ open_browser=False,
+ timeout=0.2,
+ )
+
+ mock_open.assert_not_called()
diff --git a/docs/spelling_wordlist.txt b/docs/spelling_wordlist.txt
index 8b3841a8d7b..02ff683960a 100644
--- a/docs/spelling_wordlist.txt
+++ b/docs/spelling_wordlist.txt
@@ -1710,6 +1710,7 @@ sslkey
sslmode
sslrootcert
ssm
+sso
Stackdriver
stackdriver
stacklevel