pycarta 0.3.11.dev6__tar.gz → 0.3.13__tar.gz
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.
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/.gitlab-ci.yml +1 -1
- {pycarta-0.3.11.dev6/src/pycarta.egg-info → pycarta-0.3.13}/PKG-INFO +1 -1
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/setup.cfg +1 -1
- pycarta-0.3.13/src/pycarta/auth/__init__.py +189 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/auth/agent.py +1 -1
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/auth/profile.py +1 -1
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/auth/ui.py +6 -88
- pycarta-0.3.13/src/pycarta/auth/weblogin.py +309 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/fs/__init__.py +1 -0
- pycarta-0.3.13/src/pycarta/fs/reference.py +45 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13/src/pycarta.egg-info}/PKG-INFO +1 -1
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta.egg-info/SOURCES.txt +1 -0
- pycarta-0.3.11.dev6/src/pycarta/auth/__init__.py +0 -148
- pycarta-0.3.11.dev6/src/pycarta/auth/weblogin.py +0 -136
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/.gitignore +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/.readthedocs.yml +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/AUTHORS.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/CHANGELOG.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/CONTRIBUTING.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/LICENSE.txt +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/MANIFEST.in +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/README.md +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/README.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/Makefile +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/_static/.gitignore +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/authors.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/changelog.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/conf.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/contributing.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/data-management.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/examples/00_index.ipynb +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/examples/01_authentication.ipynb +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/examples/02_admin.ipynb +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/examples/03_services.ipynb +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/examples/04_mqtt.ipynb +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/examples/05_data_management.ipynb +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/examples/06_seven_bridges.ipynb +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/examples/README.md +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/index.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/installation.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/license.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/mqtt.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/quickstart.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/requirements.txt +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/docs/services.rst +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/pyproject.toml +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/setup.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/__init__.pyi +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/_compat.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/_error_markers.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/file.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/group.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/permission.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/project.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/secret.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/service.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/connection.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/document_history.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/file.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/group.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/item.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/namespace.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/permission_entity.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/permissions.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/project.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/resource_type.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/service.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/user.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/util.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/types/workspace.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/user.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/_helpers.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/advanced.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/aio/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/aio/apitoken.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/aio/auth.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/aio/permission.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/aio/resource.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/apitoken.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/auth.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/compat.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/exceptions.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/permission.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/resource.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/v2/types.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/admin/workspace.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/auth/_http_compat.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/auth/config.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/auth/dialogs/carta_login.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/exceptions.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/_helpers.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/admin.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/aio/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/aio/admin.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/aio/data.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/aio/folders.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/aio/schema.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/concurrent.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/data.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/folders.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/query.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/schema.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/formsdb/types.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/fs/configuration.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/fs/consts.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/fs/file.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/fs/multipart_upload.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/fs/types/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/fs/types/configuration.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/fs/types/exception.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/fs/types/file.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/graph/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/graph/algorithms.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/graph/graph.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/graph/iterator.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/graph/util.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/graph/vertex/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/graph/vertex/types.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/graph/vertex/util.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/graph/visitor/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/graph/visitor/base.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/mqtt/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/mqtt/client.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/mqtt/connection.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/mqtt/credentials.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/mqtt/exceptions.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/mqtt/formatter.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/mqtt/publisher.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/mqtt/subscriber.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/py.typed +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/sbg/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/sbg/base.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/sbg/login.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/sbg/project.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/services/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/services/proxy.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/services/server.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/tablify/__init__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/tablify/__main__.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/tablify/core.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/tablify/io.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/tablify/melt.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/tablify/tablify.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/tablify/types.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta/tablify/utils.py +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta.egg-info/dependency_links.txt +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta.egg-info/not-zip-safe +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta.egg-info/requires.txt +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/src/pycarta.egg-info/top_level.txt +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/static/brand.png +0 -0
- {pycarta-0.3.11.dev6 → pycarta-0.3.13}/tox.ini +0 -0
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import os, sys
|
|
2
|
+
from .agent import CartaAgent
|
|
3
|
+
from .config import CartaConfig
|
|
4
|
+
from .profile import Profile
|
|
5
|
+
|
|
6
|
+
# Public surface — all names remain resolvable after rewrite (D-02a).
|
|
7
|
+
__all__ = [
|
|
8
|
+
"is_headless",
|
|
9
|
+
"CartaAgent",
|
|
10
|
+
"CartaConfig",
|
|
11
|
+
"Profile",
|
|
12
|
+
"CartaLoginUI",
|
|
13
|
+
"CartaProfileUI",
|
|
14
|
+
"CartaWebLogin",
|
|
15
|
+
"HeadlessEnvironmentError",
|
|
16
|
+
"InvalidUI",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
# ---------------------------------------------------------------------------
|
|
20
|
+
# Environment probes (STAY eager — cheap, no side effects, tests patch them)
|
|
21
|
+
#
|
|
22
|
+
# Two independent questions decide which UI classes are usable:
|
|
23
|
+
# is_headless() — can this process reach a graphical session at all?
|
|
24
|
+
# Gates the tkinter dialogs and whether CartaWebLogin
|
|
25
|
+
# launches a browser or prints the login URL.
|
|
26
|
+
# _tk_available() — can a tkinter window be created? Gates CartaLoginUI
|
|
27
|
+
# and CartaProfileUI only; CartaWebLogin never needs Tk.
|
|
28
|
+
# ---------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
_TRUTHY = frozenset(("1", "true", "yes", "on"))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _windows_headless() -> bool:
|
|
34
|
+
try:
|
|
35
|
+
import ctypes
|
|
36
|
+
return not getattr(ctypes, "windll").user32.GetDesktopWindow()
|
|
37
|
+
except Exception:
|
|
38
|
+
return True
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _darwin_headless() -> bool:
|
|
42
|
+
"""True unless the process runs inside a Quartz (WindowServer) session.
|
|
43
|
+
|
|
44
|
+
SSH logins, launchd daemons, and CI runners have no Quartz session, and
|
|
45
|
+
DISPLAY is meaningless on macOS (Aqua Tk ignores it). Creating a Tk
|
|
46
|
+
window outside a Quartz session aborts the interpreter rather than
|
|
47
|
+
raising, so this must be answered before any Tk call.
|
|
48
|
+
"""
|
|
49
|
+
try:
|
|
50
|
+
import ctypes
|
|
51
|
+
import ctypes.util
|
|
52
|
+
app_services = ctypes.CDLL(ctypes.util.find_library("ApplicationServices"))
|
|
53
|
+
copy_session = app_services.CGSessionCopyCurrentDictionary
|
|
54
|
+
copy_session.restype = ctypes.c_void_p
|
|
55
|
+
session = copy_session()
|
|
56
|
+
if not session:
|
|
57
|
+
return True
|
|
58
|
+
# shortcut: a non-NULL session is taken as "GUI available"; a session
|
|
59
|
+
# switched off-console (kCGSessionOnConsoleKey false) would need
|
|
60
|
+
# CFDictionary access to detect.
|
|
61
|
+
core_foundation = ctypes.CDLL(ctypes.util.find_library("CoreFoundation"))
|
|
62
|
+
core_foundation.CFRelease.argtypes = [ctypes.c_void_p]
|
|
63
|
+
core_foundation.CFRelease(session)
|
|
64
|
+
return False
|
|
65
|
+
except Exception:
|
|
66
|
+
return True
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_headless() -> bool:
|
|
70
|
+
"""Return True when no graphical session is reachable from this process.
|
|
71
|
+
|
|
72
|
+
Set ``PYCARTA_HEADLESS=1`` (or ``0``) to override detection.
|
|
73
|
+
"""
|
|
74
|
+
override = os.environ.get("PYCARTA_HEADLESS")
|
|
75
|
+
if override is not None:
|
|
76
|
+
return override.strip().lower() in _TRUTHY
|
|
77
|
+
if sys.platform in ("win32", "cygwin"):
|
|
78
|
+
return _windows_headless()
|
|
79
|
+
if sys.platform == "darwin":
|
|
80
|
+
return _darwin_headless()
|
|
81
|
+
# Linux / BSD: X11 sets DISPLAY; Wayland sets WAYLAND_DISPLAY (XWayland
|
|
82
|
+
# usually sets DISPLAY too, but not always).
|
|
83
|
+
return not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _tk_available() -> bool:
|
|
87
|
+
"""Return True when a tkinter window can be created.
|
|
88
|
+
|
|
89
|
+
Requires the ``_tkinter`` extension (``python3-tk`` on Debian/Ubuntu)
|
|
90
|
+
and, outside Windows/macOS, an X11 display: Tk has no Wayland backend,
|
|
91
|
+
so a Wayland-only session without XWayland cannot show a dialog.
|
|
92
|
+
"""
|
|
93
|
+
try:
|
|
94
|
+
import tkinter # noqa: F401
|
|
95
|
+
except ImportError:
|
|
96
|
+
return False
|
|
97
|
+
if sys.platform not in ("win32", "cygwin", "darwin"):
|
|
98
|
+
return bool(os.environ.get("DISPLAY"))
|
|
99
|
+
return True
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# ---------------------------------------------------------------------------
|
|
103
|
+
# PEP 562 lazy UI resolver — once-cache pattern (D-02)
|
|
104
|
+
#
|
|
105
|
+
# _ui_cache is assigned at module top so importlib.reload() re-runs the module
|
|
106
|
+
# body and resets it to None. __getattr__ MUST NOT write resolved names back
|
|
107
|
+
# into globals() — that would survive reload and bypass the resolver on the
|
|
108
|
+
# next access (HIGH finding; D-02a).
|
|
109
|
+
# ---------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
_ui_cache: dict | None = None
|
|
112
|
+
|
|
113
|
+
_HEADLESS_MSG = (
|
|
114
|
+
"You appear to be running in a headless environment, e.g. Lambda, so UI "
|
|
115
|
+
"components could not be imported. Any attempt to create a GUI or other "
|
|
116
|
+
"interactive element will raise an HeadlessEnvironmentError."
|
|
117
|
+
)
|
|
118
|
+
_NO_TK_MSG = (
|
|
119
|
+
"tkinter is not usable here, so the CartaLoginUI and CartaProfileUI "
|
|
120
|
+
"dialogs are unavailable. Install Tk support for this Python (e.g. "
|
|
121
|
+
"python3-tk on Debian/Ubuntu) or use CartaWebLogin."
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _resolve_ui() -> dict:
|
|
126
|
+
"""Return (building once) the dict of lazy UI names → classes.
|
|
127
|
+
|
|
128
|
+
is_headless() and _tk_available() are called BY NAME so that patches
|
|
129
|
+
applied to pycarta.auth AFTER importlib.reload() are observed at resolve
|
|
130
|
+
time (MEDIUM round-2 finding; D-02a).
|
|
131
|
+
"""
|
|
132
|
+
global _ui_cache
|
|
133
|
+
if _ui_cache is None:
|
|
134
|
+
class HeadlessEnvironmentError(ImportError, RuntimeError):
|
|
135
|
+
def __init__(self, msg: str | None = None):
|
|
136
|
+
super().__init__(msg or _HEADLESS_MSG)
|
|
137
|
+
|
|
138
|
+
class InvalidUI:
|
|
139
|
+
_reason: str | None = None
|
|
140
|
+
|
|
141
|
+
def __new__(cls, *args, **kwargs):
|
|
142
|
+
raise HeadlessEnvironmentError(cls._reason)
|
|
143
|
+
|
|
144
|
+
@classmethod
|
|
145
|
+
def login(cls, *args, **kwargs):
|
|
146
|
+
raise HeadlessEnvironmentError(cls._reason)
|
|
147
|
+
|
|
148
|
+
# Web login is always usable: without a browser it prints the login
|
|
149
|
+
# URL for the user to open elsewhere (see CartaWebLogin).
|
|
150
|
+
from .weblogin import CartaWebLogin
|
|
151
|
+
|
|
152
|
+
headless = is_headless()
|
|
153
|
+
if headless or not _tk_available():
|
|
154
|
+
reason = None if headless else _NO_TK_MSG
|
|
155
|
+
|
|
156
|
+
class CartaLoginUI(InvalidUI):
|
|
157
|
+
_reason = reason
|
|
158
|
+
|
|
159
|
+
class CartaProfileUI(InvalidUI):
|
|
160
|
+
_reason = reason
|
|
161
|
+
else:
|
|
162
|
+
from .ui import ( # type: ignore[attr-defined]
|
|
163
|
+
CartaLogin as CartaLoginUI,
|
|
164
|
+
CartaProfile as CartaProfileUI,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
_ui_cache = {
|
|
168
|
+
"HeadlessEnvironmentError": HeadlessEnvironmentError,
|
|
169
|
+
"InvalidUI": InvalidUI,
|
|
170
|
+
"CartaLoginUI": CartaLoginUI,
|
|
171
|
+
"CartaProfileUI": CartaProfileUI,
|
|
172
|
+
"CartaWebLogin": CartaWebLogin,
|
|
173
|
+
}
|
|
174
|
+
return _ui_cache
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
_UI_NAMES = frozenset(
|
|
178
|
+
["CartaLoginUI", "CartaProfileUI", "CartaWebLogin", "HeadlessEnvironmentError", "InvalidUI"]
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def __getattr__(name: str) -> object:
|
|
183
|
+
if name in _UI_NAMES:
|
|
184
|
+
return _resolve_ui()[name]
|
|
185
|
+
raise AttributeError(f"module 'pycarta.auth' has no attribute {name!r}")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def __dir__() -> list:
|
|
189
|
+
return sorted(__all__)
|
|
@@ -195,7 +195,7 @@ class AuthenticationAgent(ABC):
|
|
|
195
195
|
# region Authentication API
|
|
196
196
|
@property
|
|
197
197
|
def environment(self) -> str | None:
|
|
198
|
-
return self._profile.environment
|
|
198
|
+
return self._profile.environment or "production"
|
|
199
199
|
|
|
200
200
|
@environment.setter
|
|
201
201
|
def environment(self, value: str) -> None:
|
|
@@ -12,7 +12,7 @@ class Profile:
|
|
|
12
12
|
profile_name: Optional[str] = None
|
|
13
13
|
|
|
14
14
|
def is_production(self):
|
|
15
|
-
return self.environment
|
|
15
|
+
return (self.environment is None) or self.environment.lower() == "production"
|
|
16
16
|
|
|
17
17
|
def invalidate_token(self) -> bool:
|
|
18
18
|
"""
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import sys
|
|
2
2
|
import os
|
|
3
|
-
import json
|
|
3
|
+
import json # noqa: F401 — patched by tests/auth/test_ui_coverage.py
|
|
4
4
|
import logging
|
|
5
|
-
import subprocess
|
|
6
|
-
import time
|
|
5
|
+
import subprocess # noqa: F401 — patched by tests/auth/test_ui_coverage.py
|
|
6
|
+
import time # noqa: F401 — patched by tests/auth/test_ui_coverage.py
|
|
7
7
|
from pycarta.auth import (
|
|
8
8
|
CartaAgent,
|
|
9
9
|
CartaConfig,
|
|
@@ -12,7 +12,9 @@ from pycarta.auth import (
|
|
|
12
12
|
from pycarta.exceptions import (
|
|
13
13
|
ProfileNotFoundException,
|
|
14
14
|
)
|
|
15
|
-
from .weblogin import
|
|
15
|
+
from .weblogin import ( # noqa: F401 — re-exported for backward compatibility
|
|
16
|
+
CartaWebLogin, CognitoLoginServer, HOST, PORT,
|
|
17
|
+
)
|
|
16
18
|
|
|
17
19
|
try:
|
|
18
20
|
# Interactive login
|
|
@@ -180,90 +182,6 @@ class CartaLogin:
|
|
|
180
182
|
# endregion
|
|
181
183
|
|
|
182
184
|
|
|
183
|
-
# region Carta Web Login
|
|
184
|
-
class CartaWebLogin():
|
|
185
|
-
@classmethod
|
|
186
|
-
def login(
|
|
187
|
-
cls,
|
|
188
|
-
environment: str | None=None,
|
|
189
|
-
host: str | None=None,
|
|
190
|
-
) -> CartaAgent:
|
|
191
|
-
def open_website(url: str) -> None:
|
|
192
|
-
try:
|
|
193
|
-
if sys.platform.startswith("darwin"): # macOS
|
|
194
|
-
subprocess.run(["open", url], check=True)
|
|
195
|
-
elif os.name == "nt": # Windows
|
|
196
|
-
os.startfile(url)
|
|
197
|
-
elif os.name == "posix": # Linux or Unix
|
|
198
|
-
subprocess.run(["xdg-open", url], check=True)
|
|
199
|
-
else:
|
|
200
|
-
raise RuntimeError(f"Unsupported platform: {sys.platform}")
|
|
201
|
-
except Exception as e:
|
|
202
|
-
logger.error(f"Failed to open {url}")
|
|
203
|
-
raise
|
|
204
|
-
|
|
205
|
-
def wait_for_job(check, max_attempts=-1, base_delay=1, max_delay=5) -> bool:
|
|
206
|
-
"""
|
|
207
|
-
Wait for a job to complete, with exponential backoff.
|
|
208
|
-
|
|
209
|
-
Parameters
|
|
210
|
-
----------
|
|
211
|
-
check : function
|
|
212
|
-
The function to execute: func() -> bool.
|
|
213
|
-
max_attempts : int, optional
|
|
214
|
-
The maximum number of attempts to make. Default: -1 (infinite).
|
|
215
|
-
base_delay : int, optional
|
|
216
|
-
The base delay in seconds. Default: 1.
|
|
217
|
-
max_delay : int, optional
|
|
218
|
-
The maximum delay in seconds. Default: 30.
|
|
219
|
-
|
|
220
|
-
Returns
|
|
221
|
-
-------
|
|
222
|
-
bool
|
|
223
|
-
True if the job completed successfully, False otherwise.
|
|
224
|
-
"""
|
|
225
|
-
delay = base_delay
|
|
226
|
-
while max_attempts != 0:
|
|
227
|
-
try:
|
|
228
|
-
if check():
|
|
229
|
-
return True
|
|
230
|
-
except Exception as e:
|
|
231
|
-
break
|
|
232
|
-
delay = min(2*delay, max_delay)
|
|
233
|
-
time.sleep(delay)
|
|
234
|
-
max_attempts -= 1
|
|
235
|
-
return False
|
|
236
|
-
|
|
237
|
-
agent = CartaAgent(
|
|
238
|
-
environment=environment,
|
|
239
|
-
host=host,
|
|
240
|
-
)
|
|
241
|
-
# Get the Cognito (IdP) information
|
|
242
|
-
response = agent.get("auth", authorize=False)
|
|
243
|
-
response.raise_for_status()
|
|
244
|
-
data = response.json()
|
|
245
|
-
logger.debug(f"Auth info: {data}")
|
|
246
|
-
|
|
247
|
-
# Spin up web server and request to authenticate
|
|
248
|
-
with CognitoLoginServer(region=data["region"],
|
|
249
|
-
user_pool=data["userPoolId"],
|
|
250
|
-
client_id=data["userPoolWebClientId"]) as server:
|
|
251
|
-
open_website(f"{HOST}:{PORT}/login")
|
|
252
|
-
logger.info(f"Waiting for login to complete...")
|
|
253
|
-
wait_for_job(server.is_finished, max_attempts=7)
|
|
254
|
-
logger.info(f"Login attempt complete: {data}")
|
|
255
|
-
if server.token is not None:
|
|
256
|
-
data = server.token
|
|
257
|
-
agent.token = data["id_token"]
|
|
258
|
-
agent._profile.username = data["userinfo"]["cognito:username"]
|
|
259
|
-
logger.debug("Login succeded.")
|
|
260
|
-
else:
|
|
261
|
-
logger.error("Login failed")
|
|
262
|
-
raise RuntimeError("Login failed")
|
|
263
|
-
return agent
|
|
264
|
-
# endregion
|
|
265
|
-
|
|
266
|
-
|
|
267
185
|
# region CartaProfile
|
|
268
186
|
class CartaProfile(UsernamePasswordDialog):
|
|
269
187
|
def __init__(self, title: None | str=None, *args, **kwds):
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import secrets
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
import webbrowser
|
|
9
|
+
from urllib.parse import parse_qs, urlencode, urlparse
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from .agent import CartaAgent
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# Where the server will be hosted.
|
|
19
|
+
HOST = "http://localhost"
|
|
20
|
+
PORT = 3000
|
|
21
|
+
REDIRECT_URI = f"{HOST}:{PORT}" # registered with the Cognito app client
|
|
22
|
+
SCOPE = "aws.cognito.signin.user.admin email openid profile"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CognitoLoginServer:
|
|
26
|
+
def __init__(self, client_id, region, user_pool, *, log_level="error"):
|
|
27
|
+
self.process = None
|
|
28
|
+
self.token = None
|
|
29
|
+
self.client_id = client_id
|
|
30
|
+
self.region = region
|
|
31
|
+
self.user_pool = user_pool
|
|
32
|
+
self._thread = None
|
|
33
|
+
self._server = None
|
|
34
|
+
self._log_level = log_level
|
|
35
|
+
|
|
36
|
+
def run(self):
|
|
37
|
+
# Lazy imports: uvicorn, fastapi, starlette require pycarta[carta] extras.
|
|
38
|
+
# These are only needed when the web login server is actually started.
|
|
39
|
+
import uvicorn
|
|
40
|
+
from authlib.integrations.starlette_client import OAuth
|
|
41
|
+
from fastapi import FastAPI, Request
|
|
42
|
+
from fastapi.responses import HTMLResponse
|
|
43
|
+
from starlette.staticfiles import StaticFiles
|
|
44
|
+
from starlette.middleware.sessions import SessionMiddleware
|
|
45
|
+
|
|
46
|
+
self_ = self # capture self to use in routes.
|
|
47
|
+
|
|
48
|
+
app = FastAPI()
|
|
49
|
+
app.add_middleware(SessionMiddleware, secret_key="pycarta-weblogin-secret-key")
|
|
50
|
+
# Serve static assets (e.g., brand logo) from ./static if present
|
|
51
|
+
try:
|
|
52
|
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
|
53
|
+
except Exception:
|
|
54
|
+
# If the directory is missing, continue without static mount
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
# Setup OAuth
|
|
58
|
+
oauth = OAuth()
|
|
59
|
+
# Cognito Config
|
|
60
|
+
oauth.register(
|
|
61
|
+
name='oidc',
|
|
62
|
+
authority=f"https://cognito-idp.{self.region}.amazonaws.com/{self.user_pool}",
|
|
63
|
+
client_id=self.client_id,
|
|
64
|
+
server_metadata_url=f"https://cognito-idp.{self.region}.amazonaws.com/{self.user_pool}/.well-known/openid-configuration",
|
|
65
|
+
client_kwargs={'scope': SCOPE, 'code_challenge_method': 'S256'}
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
@app.get("/", response_class=HTMLResponse)
|
|
69
|
+
async def index(request: Request):
|
|
70
|
+
self_.token = await oauth.oidc.authorize_access_token(request)
|
|
71
|
+
userinfo = self_.token["userinfo"]
|
|
72
|
+
given, family = userinfo.get("given_name", ""), userinfo.get("family_name", "")
|
|
73
|
+
html = f"""
|
|
74
|
+
<!doctype html>
|
|
75
|
+
<html lang=\"en\">
|
|
76
|
+
<head>
|
|
77
|
+
<meta charset=\"utf-8\" />
|
|
78
|
+
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />
|
|
79
|
+
<title>Logged In</title>
|
|
80
|
+
<style>
|
|
81
|
+
:root {{
|
|
82
|
+
--brand-green: rgb(110, 182, 95);
|
|
83
|
+
--brand-gray: rgb(83, 83, 83);
|
|
84
|
+
--bg: #f7f7f7;
|
|
85
|
+
--card-bg: #ffffff;
|
|
86
|
+
}}
|
|
87
|
+
html, body {{ height: 100%; margin: 0; background: var(--bg); font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif; color: var(--brand-gray); }}
|
|
88
|
+
.wrap {{ min-height: 100%; display: flex; align-items: center; justify-content: center; padding: 24px; }}
|
|
89
|
+
.card {{ background: var(--card-bg); border-radius: 12px; box-shadow: 0 6px 20px rgba(0,0,0,0.08); padding: 28px 28px 24px; max-width: 520px; width: 100%; text-align: center; }}
|
|
90
|
+
.brand {{ display: inline-flex; align-items: center; gap: 14px; margin-bottom: 14px; }}
|
|
91
|
+
.brand img {{ width: 56px; height: 56px; }}
|
|
92
|
+
.brand-name {{ font-weight: 700; letter-spacing: 0.3px; color: var(--brand-gray); }}
|
|
93
|
+
h1 {{ margin: 8px 0 6px; font-size: 1.4rem; color: var(--brand-gray); }}
|
|
94
|
+
.success {{ display: inline-flex; align-items: center; gap: 8px; color: var(--brand-green); font-weight: 600; margin-top: 6px; }}
|
|
95
|
+
.success .dot {{ width: 10px; height: 10px; border-radius: 50%; background: var(--brand-green); display: inline-block; }}
|
|
96
|
+
p {{ margin: 10px 0 0; line-height: 1.5; }}
|
|
97
|
+
.hint {{ margin-top: 14px; font-size: 0.95rem; color: var(--brand-gray); opacity: 0.9; }}
|
|
98
|
+
.footer {{ margin-top: 16px; font-size: 0.8rem; opacity: 0.8; }}
|
|
99
|
+
</style>
|
|
100
|
+
</head>
|
|
101
|
+
<body>
|
|
102
|
+
<div class=\"wrap\">
|
|
103
|
+
<div class=\"card\">
|
|
104
|
+
<div class=\"brand\">
|
|
105
|
+
<img src=\"/static/brand.png\" alt=\"Brand\" onerror=\"this.style.display='none'\" />
|
|
106
|
+
<span class=\"brand-name\">Signed in to Carta</span>
|
|
107
|
+
</div>
|
|
108
|
+
<h1>Welcome{(', ' + given + ' ' + family) if (given or family) else ''}!</h1>
|
|
109
|
+
<div class=\"success\"><span class=\"dot\"></span> You are now signed in.</div>
|
|
110
|
+
<p class=\"hint\">You may safely close this window.</p>
|
|
111
|
+
<div class=\"footer\">If it doesn't close automatically, you can close it yourself.</div>
|
|
112
|
+
</div>
|
|
113
|
+
</div>
|
|
114
|
+
<script>
|
|
115
|
+
// Optional: try to auto-close after a brief delay when embedded as a popup
|
|
116
|
+
setTimeout(function() {{ try {{ window.close(); }} catch(e) {{}} }}, 5000);
|
|
117
|
+
</script>
|
|
118
|
+
</body>
|
|
119
|
+
</html>
|
|
120
|
+
"""
|
|
121
|
+
return HTMLResponse(content=html)
|
|
122
|
+
|
|
123
|
+
@app.get("/login")
|
|
124
|
+
async def login(request: Request):
|
|
125
|
+
return await oauth.oidc.authorize_redirect(request, REDIRECT_URI)
|
|
126
|
+
|
|
127
|
+
config = uvicorn.Config(app, host="0.0.0.0", port=PORT, log_level=self._log_level)
|
|
128
|
+
self._server = uvicorn.Server(config=config)
|
|
129
|
+
self._server.run()
|
|
130
|
+
# uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="error")
|
|
131
|
+
|
|
132
|
+
def __enter__(self):
|
|
133
|
+
self._thread = threading.Thread(target=self.run, daemon=True)
|
|
134
|
+
self._thread.start()
|
|
135
|
+
# Wait for server to start
|
|
136
|
+
while self._server is None or not self._server.started:
|
|
137
|
+
time.sleep(0.1)
|
|
138
|
+
return self
|
|
139
|
+
|
|
140
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
141
|
+
if self._server:
|
|
142
|
+
self._server.should_exit = True
|
|
143
|
+
# self._server.force_exit = True
|
|
144
|
+
self._server = None
|
|
145
|
+
if self._thread:
|
|
146
|
+
self._thread.join(timeout=3)
|
|
147
|
+
self._thread = None
|
|
148
|
+
return exc_val is None
|
|
149
|
+
|
|
150
|
+
def is_finished(self) -> bool:
|
|
151
|
+
return self.token is not None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class CartaWebLogin:
|
|
155
|
+
"""Log in through the Carta web UI (Cognito hosted UI).
|
|
156
|
+
|
|
157
|
+
With a graphical session, a loopback server on localhost receives the
|
|
158
|
+
OAuth callback and the browser shows a signed-in page. Without one
|
|
159
|
+
(SSH, containers, CI), the authorize URL is printed; the user logs in on
|
|
160
|
+
their own machine and pastes the authorization code back. Both paths
|
|
161
|
+
use PKCE, so no client secret is involved.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
#: Seconds to wait for the loopback callback.
|
|
165
|
+
TIMEOUT = 300
|
|
166
|
+
POLL_INTERVAL = 1
|
|
167
|
+
|
|
168
|
+
@classmethod
|
|
169
|
+
def login(
|
|
170
|
+
cls,
|
|
171
|
+
environment: str | None=None,
|
|
172
|
+
host: str | None=None,
|
|
173
|
+
) -> CartaAgent:
|
|
174
|
+
from . import is_headless # by name, so test patches are observed
|
|
175
|
+
|
|
176
|
+
agent = CartaAgent(
|
|
177
|
+
environment=environment,
|
|
178
|
+
host=host,
|
|
179
|
+
)
|
|
180
|
+
# Get the Cognito (IdP) information
|
|
181
|
+
response = agent.get("auth", authorize=False)
|
|
182
|
+
response.raise_for_status()
|
|
183
|
+
data = response.json()
|
|
184
|
+
logger.debug(f"Auth info: {data}")
|
|
185
|
+
|
|
186
|
+
result = None if is_headless() else cls._browser_login(data)
|
|
187
|
+
if result is None:
|
|
188
|
+
result = cls._paste_back_login(data)
|
|
189
|
+
id_token, username = result
|
|
190
|
+
agent.token = id_token
|
|
191
|
+
agent._profile.username = username
|
|
192
|
+
logger.debug("Login succeeded.")
|
|
193
|
+
return agent
|
|
194
|
+
|
|
195
|
+
# ----------------------------------------------------------------- GUI
|
|
196
|
+
@classmethod
|
|
197
|
+
def _browser_login(cls, data: dict) -> tuple[str, str] | None:
|
|
198
|
+
"""Loopback-server flow. None when no browser could be launched."""
|
|
199
|
+
with CognitoLoginServer(region=data["region"],
|
|
200
|
+
user_pool=data["userPoolId"],
|
|
201
|
+
client_id=data["userPoolWebClientId"]) as server:
|
|
202
|
+
if not cls._open_browser(f"{HOST}:{PORT}/login"):
|
|
203
|
+
return None
|
|
204
|
+
logger.info("Waiting for login to complete...")
|
|
205
|
+
cls._wait_until(server.is_finished)
|
|
206
|
+
if server.token is None:
|
|
207
|
+
logger.error("Login failed")
|
|
208
|
+
raise RuntimeError("Login failed")
|
|
209
|
+
token = server.token
|
|
210
|
+
return token["id_token"], token["userinfo"]["cognito:username"]
|
|
211
|
+
|
|
212
|
+
@staticmethod
|
|
213
|
+
def _open_browser(url: str) -> bool:
|
|
214
|
+
try:
|
|
215
|
+
return webbrowser.open(url)
|
|
216
|
+
except webbrowser.Error:
|
|
217
|
+
return False
|
|
218
|
+
|
|
219
|
+
@classmethod
|
|
220
|
+
def _wait_until(cls, check) -> bool:
|
|
221
|
+
"""Poll ``check()`` until it returns True or TIMEOUT elapses."""
|
|
222
|
+
deadline = time.monotonic() + cls.TIMEOUT
|
|
223
|
+
while time.monotonic() < deadline:
|
|
224
|
+
if check():
|
|
225
|
+
return True
|
|
226
|
+
time.sleep(cls.POLL_INTERVAL)
|
|
227
|
+
return False
|
|
228
|
+
|
|
229
|
+
# ------------------------------------------------------------ headless
|
|
230
|
+
@classmethod
|
|
231
|
+
def _paste_back_login(cls, data: dict) -> tuple[str, str]:
|
|
232
|
+
"""PKCE authorization-code flow with the code pasted back by hand."""
|
|
233
|
+
endpoints = cls._oidc_endpoints(data["region"], data["userPoolId"])
|
|
234
|
+
client_id = data["userPoolWebClientId"]
|
|
235
|
+
verifier = secrets.token_urlsafe(64)
|
|
236
|
+
challenge = base64.urlsafe_b64encode(
|
|
237
|
+
hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
|
|
238
|
+
state = secrets.token_urlsafe(16)
|
|
239
|
+
url = endpoints["authorization_endpoint"] + "?" + urlencode({
|
|
240
|
+
"response_type": "code",
|
|
241
|
+
"client_id": client_id,
|
|
242
|
+
"redirect_uri": REDIRECT_URI,
|
|
243
|
+
"scope": SCOPE,
|
|
244
|
+
"state": state,
|
|
245
|
+
"code_challenge": challenge,
|
|
246
|
+
"code_challenge_method": "S256",
|
|
247
|
+
})
|
|
248
|
+
print(cls._manual_instructions(url))
|
|
249
|
+
try:
|
|
250
|
+
pasted = input("Paste the code or the full redirect URL here: ").strip()
|
|
251
|
+
except EOFError:
|
|
252
|
+
raise RuntimeError("Login failed: no authorization code entered") from None
|
|
253
|
+
code = cls._parse_code(pasted, state)
|
|
254
|
+
response = httpx.post(endpoints["token_endpoint"], data={
|
|
255
|
+
"grant_type": "authorization_code",
|
|
256
|
+
"client_id": client_id,
|
|
257
|
+
"code": code,
|
|
258
|
+
"redirect_uri": REDIRECT_URI,
|
|
259
|
+
"code_verifier": verifier,
|
|
260
|
+
})
|
|
261
|
+
if response.status_code != 200:
|
|
262
|
+
logger.error(f"Token exchange failed: {response.text}")
|
|
263
|
+
raise RuntimeError("Login failed: token exchange rejected")
|
|
264
|
+
token = response.json()
|
|
265
|
+
id_token = token["id_token"]
|
|
266
|
+
return id_token, cls._jwt_claims(id_token)["cognito:username"]
|
|
267
|
+
|
|
268
|
+
@staticmethod
|
|
269
|
+
def _oidc_endpoints(region: str, user_pool: str) -> dict:
|
|
270
|
+
url = (f"https://cognito-idp.{region}.amazonaws.com/{user_pool}"
|
|
271
|
+
"/.well-known/openid-configuration")
|
|
272
|
+
response = httpx.get(url)
|
|
273
|
+
response.raise_for_status()
|
|
274
|
+
return response.json()
|
|
275
|
+
|
|
276
|
+
@staticmethod
|
|
277
|
+
def _manual_instructions(url: str) -> str:
|
|
278
|
+
return (
|
|
279
|
+
"No browser could be opened here. Open this URL in a browser on "
|
|
280
|
+
f"your own computer to log in to Carta:\n\n {url}\n\n"
|
|
281
|
+
"After signing in, the browser will fail to load "
|
|
282
|
+
f"{REDIRECT_URI}/?code=... (nothing is listening there). That is "
|
|
283
|
+
"expected: copy the address from the address bar, or just the "
|
|
284
|
+
"value of its `code` parameter. Codes expire after five minutes.\n"
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
@staticmethod
|
|
288
|
+
def _parse_code(pasted: str, expected_state: str) -> str:
|
|
289
|
+
"""Accept either a bare code or the full redirect URL (state checked)."""
|
|
290
|
+
if "://" not in pasted and "?" not in pasted:
|
|
291
|
+
return pasted
|
|
292
|
+
query = parse_qs(urlparse(pasted).query)
|
|
293
|
+
if query.get("state", [None])[0] != expected_state:
|
|
294
|
+
raise RuntimeError("Login failed: state mismatch in pasted URL")
|
|
295
|
+
code = query.get("code", [None])[0]
|
|
296
|
+
if not code:
|
|
297
|
+
raise RuntimeError("Login failed: no code parameter in pasted URL")
|
|
298
|
+
return code
|
|
299
|
+
|
|
300
|
+
@staticmethod
|
|
301
|
+
def _jwt_claims(token: str) -> dict:
|
|
302
|
+
"""Decode a JWT payload without verification.
|
|
303
|
+
|
|
304
|
+
The token came straight from Cognito's token endpoint over TLS in
|
|
305
|
+
exchange for our PKCE verifier, so its claims are trusted here.
|
|
306
|
+
"""
|
|
307
|
+
payload = token.split(".")[1]
|
|
308
|
+
payload += "=" * (-len(payload) % 4)
|
|
309
|
+
return json.loads(base64.urlsafe_b64decode(payload))
|