secflow-cli 0.2.4__py3-none-any.whl → 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
secflow_cli/__init__.py CHANGED
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
secflow_cli/__main__.py CHANGED
@@ -1,3 +1,3 @@
1
- from secflow_cli.main import main
1
+ from secflow_cli.bootstrap import main
2
2
 
3
3
  raise SystemExit(main())
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from typing import Any
5
+
6
+ from . import __version__
7
+ from .update_runtime import bootstrap
8
+ from .update_state import Configuration, default_root
9
+
10
+
11
+ def execute(arguments: list[str]) -> int:
12
+ from .main import main
13
+
14
+ return main(arguments, configure=True)
15
+
16
+
17
+ def output(value: dict[str, Any]) -> None:
18
+ from .output import update_result
19
+
20
+ update_result(value)
21
+
22
+
23
+ def main(argv: list[str] | None = None) -> int:
24
+ config = Configuration(
25
+ "secflow-cli", "secflow_cli", __version__, default_root("secflow-cli")
26
+ )
27
+ return bootstrap(
28
+ config,
29
+ list(sys.argv[1:] if argv is None else argv),
30
+ execute,
31
+ output,
32
+ frozen=bool(getattr(sys, "frozen", False)),
33
+ )
34
+
35
+
36
+ if __name__ == "__main__":
37
+ raise SystemExit(main())
@@ -4,6 +4,7 @@ import base64
4
4
  from datetime import datetime, timezone
5
5
  import hashlib
6
6
  import json
7
+ import logging
7
8
  import os
8
9
  import re
9
10
  import sys
@@ -11,12 +12,18 @@ import time
11
12
  from urllib.error import HTTPError
12
13
  from urllib.request import HTTPRedirectHandler, Request, build_opener
13
14
  from uuid import UUID
15
+
16
+
17
+ LOGGER = logging.getLogger(__name__)
14
18
  import webbrowser
15
19
 
16
20
  from secflow_sdk import SecFlowAdminClient
17
21
  from secflow_cli.errors import CliError
18
22
 
19
23
 
24
+ BUSY_WAIT_SECONDS = 60
25
+
26
+
20
27
  def rejected():
21
28
  return CliError(3, "BROWSER_LOGIN_FAILED", "Browser login did not complete. Start a new login; uncertain session exchanges are not retried.")
22
29
 
@@ -32,9 +39,9 @@ def post(url, body, timeout):
32
39
  try:
33
40
  response = build_opener(NoRedirect).open(request, timeout=timeout)
34
41
  except HTTPError as error:
35
- status = error.code
42
+ status, retry_after = error.code, _retry_after(error.headers.get("Retry-After"))
36
43
  error.close()
37
- return status, {}
44
+ return status, {}, retry_after
38
45
  with response:
39
46
  raw = response.read(16385)
40
47
  if len(raw) > 16384:
@@ -42,7 +49,13 @@ def post(url, body, timeout):
42
49
  value = json.loads(raw)
43
50
  if not isinstance(value, dict):
44
51
  raise rejected()
45
- return response.status, value
52
+ return response.status, value, None
53
+
54
+
55
+ def _retry_after(value):
56
+ if not isinstance(value, str) or not re.fullmatch(r"[0-9]{1,4}", value):
57
+ return None
58
+ return min(30, max(1, int(value)))
46
59
 
47
60
 
48
61
  def acquire_session(url, timeout, *, no_browser=False):
@@ -57,7 +70,8 @@ def acquire_session(url, timeout, *, no_browser=False):
57
70
  def _open_browser(verification_uri):
58
71
  try:
59
72
  opened = webbrowser.open(verification_uri)
60
- except Exception:
73
+ except Exception as caught:
74
+ LOGGER.debug("Browser could not be opened", extra={"attributes": {"error.type": type(caught).__name__}})
61
75
  opened = False
62
76
  if not opened:
63
77
  print("Open the URL above manually to continue.", file=sys.stderr)
@@ -75,10 +89,26 @@ def _issued_session(result):
75
89
  return {field: result[field] for field in ("session_token", "session_id", "account_id", "expires_at")}
76
90
 
77
91
 
92
+ def _create(url, proof, timeout):
93
+ give_up = time.monotonic() + BUSY_WAIT_SECONDS
94
+ announced = False
95
+ while True:
96
+ started_at = time.monotonic()
97
+ status, created, retry_after = post(url + "/v1/auth/browser-login", {"poll_challenge": hashlib.sha256(proof.encode()).hexdigest()}, timeout)
98
+ if status != 503 or retry_after is None:
99
+ return status, created, started_at
100
+ remaining = give_up - time.monotonic()
101
+ if remaining <= 0:
102
+ raise CliError(3, "BROWSER_LOGIN_BUSY", "The server is too busy to start a browser login. Try again in a few minutes.")
103
+ if not announced:
104
+ print("The server is busy. Retrying for up to " + str(BUSY_WAIT_SECONDS) + " seconds.", file=sys.stderr)
105
+ announced = True
106
+ time.sleep(min(retry_after, remaining))
107
+
108
+
78
109
  def _acquire_session(url, timeout, *, no_browser):
79
110
  proof = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b"=").decode("ascii")
80
- started_at = time.monotonic()
81
- status, created = post(url + "/v1/auth/browser-login", {"poll_challenge": hashlib.sha256(proof.encode()).hexdigest()}, timeout)
111
+ status, created, started_at = _create(url, proof, timeout)
82
112
  if status == 404:
83
113
  raise CliError(3, "BROWSER_LOGIN_UNAVAILABLE", "This server has not enabled browser login. Use a Slack-issued Admin session.")
84
114
  if status != 201:
@@ -97,18 +127,26 @@ def _acquire_session(url, timeout, *, no_browser):
97
127
  print("Confirm code " + created["user_code"] + " and approve the login in your browser.", file=sys.stderr)
98
128
  if not no_browser:
99
129
  _open_browser(verification_uri)
100
- interval = created["interval"]
101
- while time.monotonic() + interval < deadline:
102
- time.sleep(interval)
130
+ return _poll(url, timeout, identifier, proof, deadline, created["interval"])
131
+
132
+
133
+ def _poll(url, timeout, identifier, proof, deadline, interval):
134
+ wait = interval
135
+ while time.monotonic() + wait < deadline:
136
+ time.sleep(wait)
137
+ wait = interval
103
138
  remaining = deadline - time.monotonic()
104
139
  if remaining <= 0:
105
140
  break
106
- status, result = post(url + "/v1/auth/browser-login/redeem",
107
- {"transaction_id": identifier, "poll_secret": proof}, min(timeout, remaining))
141
+ status, result, retry_after = post(url + "/v1/auth/browser-login/redeem",
142
+ {"transaction_id": identifier, "poll_secret": proof}, min(timeout, remaining))
108
143
  if status == 202 and result == {"status": "pending"}:
109
144
  continue
110
145
  if status == 429:
111
- interval = min(30, interval + 2)
146
+ wait = interval = min(30, interval + 2)
147
+ continue
148
+ if status == 503 and retry_after is not None:
149
+ wait = max(interval, retry_after)
112
150
  continue
113
151
  if status != 200:
114
152
  raise rejected()
@@ -128,7 +166,7 @@ def login(url, timeout, store, reference, *, no_browser=False):
128
166
  except BaseException:
129
167
  try:
130
168
  client.revoke_current_session()
131
- except Exception:
132
- pass
169
+ except Exception as caught:
170
+ LOGGER.debug("New session revocation failed", extra={"attributes": {"error.type": type(caught).__name__}})
133
171
  raise
134
172
  return account, session["expires_at"]