cli-login 0.1.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.
@@ -0,0 +1,177 @@
1
+ """macOS Keychain, through Apple's Security framework. No plaintext fallback, ever.
2
+
3
+ Importable on every platform; it fails only when used off macOS.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import ctypes as C
9
+ import sys
10
+
11
+ from ..errors import AuthError
12
+
13
+
14
+ class MacOSKeychain:
15
+ """Minimal generic-password adapter. No subprocess arguments, token files or keyring fallback."""
16
+
17
+ def __init__(self):
18
+ if sys.platform != "darwin":
19
+ raise RuntimeError("macOS Keychain is required")
20
+ self.cf = C.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
21
+ self.sec = C.CDLL("/System/Library/Frameworks/Security.framework/Security")
22
+ signatures = {
23
+ "CFStringCreateWithCString": ([C.c_void_p, C.c_char_p, C.c_uint32], C.c_void_p),
24
+ "CFDataCreate": ([C.c_void_p, C.c_void_p, C.c_long], C.c_void_p),
25
+ "CFDictionaryCreate": (
26
+ [C.c_void_p, C.POINTER(C.c_void_p), C.POINTER(C.c_void_p), C.c_long, C.c_void_p, C.c_void_p],
27
+ C.c_void_p,
28
+ ),
29
+ "CFDataGetLength": ([C.c_void_p], C.c_long),
30
+ "CFDataGetBytePtr": ([C.c_void_p], C.c_void_p),
31
+ "CFRelease": ([C.c_void_p], None),
32
+ }
33
+ for name, (arguments, result) in signatures.items():
34
+ function = getattr(self.cf, name)
35
+ function.argtypes, function.restype = arguments, result
36
+ for name, args in {
37
+ "SecItemAdd": [C.c_void_p, C.POINTER(C.c_void_p)],
38
+ "SecItemCopyMatching": [C.c_void_p, C.POINTER(C.c_void_p)],
39
+ "SecItemUpdate": [C.c_void_p, C.c_void_p],
40
+ "SecItemDelete": [C.c_void_p],
41
+ }.items():
42
+ function = getattr(self.sec, name)
43
+ function.argtypes, function.restype = args, C.c_int32
44
+
45
+ def _constant(self, name):
46
+ return C.c_void_p.in_dll(self.sec, name).value
47
+
48
+ def _dictionary(self, service, account, *, value=None, read=False, payload_only=False):
49
+ owned = []
50
+ pairs = []
51
+
52
+ def text(name, text_value):
53
+ pointer = self.cf.CFStringCreateWithCString(None, text_value.encode("utf-8"), 0x08000100)
54
+ if not pointer:
55
+ raise RuntimeError("Keychain allocation failed")
56
+ owned.append(pointer)
57
+ pairs.append((self._constant(name), pointer))
58
+
59
+ if not payload_only:
60
+ pairs.append((self._constant("kSecClass"), self._constant("kSecClassGenericPassword")))
61
+ text("kSecAttrService", service)
62
+ text("kSecAttrAccount", account)
63
+ # Do not trigger an unexpected unlock/authentication dialog from a worker.
64
+ pairs.append((self._constant("kSecUseAuthenticationUI"), self._constant("kSecUseAuthenticationUIFail")))
65
+ if read:
66
+ pairs.append((self._constant("kSecReturnData"), C.c_void_p.in_dll(self.cf, "kCFBooleanTrue").value))
67
+ pairs.append((self._constant("kSecMatchLimit"), self._constant("kSecMatchLimitOne")))
68
+ if value is not None:
69
+ encoded = value.encode("utf-8")
70
+ pointer = self.cf.CFDataCreate(None, encoded, len(encoded))
71
+ if not pointer:
72
+ raise RuntimeError("Keychain allocation failed")
73
+ owned.append(pointer)
74
+ pairs.append((self._constant("kSecValueData"), pointer))
75
+ keys = (C.c_void_p * len(pairs))(*(x[0] for x in pairs))
76
+ values = (C.c_void_p * len(pairs))(*(x[1] for x in pairs))
77
+ pointer = self.cf.CFDictionaryCreate(None, keys, values, len(pairs), None, None)
78
+ if not pointer:
79
+ raise RuntimeError("Keychain allocation failed")
80
+ return pointer, owned
81
+
82
+ def _release(self, dictionary):
83
+ pointer, owned = dictionary
84
+ self.cf.CFRelease(pointer)
85
+ for item in owned:
86
+ self.cf.CFRelease(item)
87
+
88
+ def get_password(self, service, account):
89
+ dictionary = self._dictionary(service, account, read=True)
90
+ result = C.c_void_p()
91
+ try:
92
+ status = self.sec.SecItemCopyMatching(dictionary[0], C.byref(result))
93
+ if status == -25300: # errSecItemNotFound
94
+ return None
95
+ if status != 0:
96
+ raise RuntimeError("Keychain read failed")
97
+ try:
98
+ return C.string_at(self.cf.CFDataGetBytePtr(result), self.cf.CFDataGetLength(result)).decode("utf-8")
99
+ finally:
100
+ self.cf.CFRelease(result)
101
+ finally:
102
+ self._release(dictionary)
103
+
104
+ def set_password(self, service, account, value):
105
+ dictionary = self._dictionary(service, account, value=value)
106
+ try:
107
+ status = self.sec.SecItemAdd(dictionary[0], None)
108
+ finally:
109
+ self._release(dictionary)
110
+ if status == -25299: # errSecDuplicateItem: update without deleting the old secret first.
111
+ query = self._dictionary(service, account)
112
+ payload = self._dictionary(service, account, value=value, payload_only=True)
113
+ try:
114
+ status = self.sec.SecItemUpdate(query[0], payload[0])
115
+ finally:
116
+ self._release(payload)
117
+ self._release(query)
118
+ if status != 0:
119
+ raise RuntimeError("Keychain save failed")
120
+
121
+ def delete_password(self, service, account):
122
+ dictionary = self._dictionary(service, account)
123
+ try:
124
+ status = self.sec.SecItemDelete(dictionary[0])
125
+ finally:
126
+ self._release(dictionary)
127
+ if status not in (0, -25300):
128
+ raise RuntimeError("Keychain delete failed")
129
+
130
+
131
+ class MacOSKeychainStore:
132
+ """Keychain store whose service name is the target's namespace.
133
+
134
+ A product that already stores sessions under a service name keeps that name as its namespace,
135
+ so its existing sessions are found under the same service and key.
136
+ """
137
+
138
+ def __init__(self, namespace: str, backend=None):
139
+ if not namespace:
140
+ raise AuthError("A store namespace is required.")
141
+ if backend is None:
142
+ try:
143
+ backend = MacOSKeychain()
144
+ except Exception: # noqa: BLE001 - backend text must never reach the user
145
+ raise AuthError(
146
+ "macOS Keychain is unavailable. Use the tool on an unlocked Mac; no plaintext credential fallback is supported."
147
+ ) from None
148
+ if not isinstance(backend, MacOSKeychain):
149
+ raise AuthError(
150
+ "A supported OS secure credential store is required; plaintext/fallback backends are refused."
151
+ )
152
+ self.namespace = namespace
153
+ self.backend = backend
154
+
155
+ def get(self, key):
156
+ try:
157
+ return self.backend.get_password(self.namespace, key)
158
+ except Exception: # noqa: BLE001 - backend text must never reach the user
159
+ raise AuthError("Unable to read OS secure credential storage; unlock it and retry.") from None
160
+
161
+ def set(self, key, value):
162
+ try:
163
+ self.backend.set_password(self.namespace, key, value)
164
+ except Exception: # noqa: BLE001 - backend text must never reach the user
165
+ raise AuthError(
166
+ "Unable to save the session in OS secure credential storage; unlock it and retry login."
167
+ ) from None
168
+
169
+ def delete(self, key):
170
+ if self.get(key) is None:
171
+ return
172
+ try:
173
+ self.backend.delete_password(self.namespace, key)
174
+ except Exception: # noqa: BLE001 - backend text must never reach the user
175
+ raise AuthError(
176
+ "Unable to remove the local OS credential; unlock the secure store and retry logout."
177
+ ) from None
@@ -0,0 +1,112 @@
1
+ """Linux Secret Service (D-Bus), through the optional ``secretstorage`` package.
2
+
3
+ Install it with ``pip install "cli-login[linux]"``. Items are labelled and attributed by namespace and
4
+ key. The module never asks for an unlock prompt: a locked or absent keyring is reported as unavailable so that
5
+ selection moves on, and the message says how to recover.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+
12
+ from ..errors import AuthError, StoreUnavailable
13
+
14
+ APPLICATION = "cli-login"
15
+
16
+ INSTALL = 'Install the Linux extra: pip install "cli-login[linux]".'
17
+ NO_BUS = (
18
+ "No Secret Service is reachable (no D-Bus session or no keyring daemon such as gnome-keyring or "
19
+ "KeePassXC); on a cloud machine use the memory agent."
20
+ )
21
+ LOCKED = "The Secret Service keyring is locked; unlock it (log in to the desktop session) and retry."
22
+
23
+
24
+ def _load():
25
+ try:
26
+ import secretstorage
27
+ except ImportError:
28
+ raise StoreUnavailable(INSTALL) from None
29
+ return secretstorage
30
+
31
+
32
+ class SecretServiceStore:
33
+ name = "Secret Service"
34
+
35
+ def __init__(self, namespace: str, *, module=None):
36
+ if not namespace:
37
+ raise AuthError("A store namespace is required.")
38
+ self.namespace = namespace
39
+ self.module = module if module is not None else _load()
40
+
41
+ def _attributes(self, key: str) -> dict:
42
+ return {"application": APPLICATION, "namespace": self.namespace, "key": key}
43
+
44
+ def _is(self, error: Exception, name: str) -> bool:
45
+ cls = getattr(getattr(self.module, "exceptions", None), name, None)
46
+ return isinstance(cls, type) and isinstance(error, cls)
47
+
48
+ def _open(self):
49
+ """(connection, unlocked default collection). Raises StoreUnavailable if there is none."""
50
+ try:
51
+ connection = self.module.dbus_init()
52
+ except Exception: # noqa: BLE001 - backend text must never reach the user
53
+ raise StoreUnavailable(NO_BUS) from None
54
+ try:
55
+ collection = self.module.get_default_collection(connection)
56
+ if collection.is_locked():
57
+ raise StoreUnavailable(LOCKED)
58
+ except StoreUnavailable:
59
+ self._close(connection)
60
+ raise
61
+ except Exception as error: # noqa: BLE001
62
+ self._close(connection)
63
+ raise StoreUnavailable(LOCKED if self._is(error, "LockedException") else NO_BUS) from None
64
+ return connection, collection
65
+
66
+ @staticmethod
67
+ def _close(connection) -> None:
68
+ with contextlib.suppress(Exception):
69
+ connection.close()
70
+
71
+ def probe(self) -> None:
72
+ connection, _ = self._open()
73
+ self._close(connection)
74
+
75
+ def _run(self, action, failure: str):
76
+ try:
77
+ connection, collection = self._open()
78
+ except StoreUnavailable as error:
79
+ raise AuthError(str(error)) from None
80
+ try:
81
+ return action(collection)
82
+ except Exception: # noqa: BLE001 - backend text must never reach the user
83
+ raise AuthError(failure) from None
84
+ finally:
85
+ self._close(connection)
86
+
87
+ def get(self, key):
88
+ def read(collection):
89
+ for item in collection.search_items(self._attributes(key)):
90
+ return item.get_secret().decode("utf-8")
91
+ return None
92
+
93
+ return self._run(read, "Unable to read the Secret Service keyring; unlock it and retry.")
94
+
95
+ def set(self, key, value):
96
+ def write(collection):
97
+ collection.create_item(
98
+ f"{self.namespace}/{key}",
99
+ self._attributes(key),
100
+ value.encode("utf-8"),
101
+ replace=True,
102
+ content_type="text/plain",
103
+ )
104
+
105
+ self._run(write, "Unable to save the session in the Secret Service keyring; unlock it and retry login.")
106
+
107
+ def delete(self, key):
108
+ def remove(collection):
109
+ for item in list(collection.search_items(self._attributes(key))):
110
+ item.delete()
111
+
112
+ self._run(remove, "Unable to remove the session from the Secret Service keyring; unlock it and retry logout.")
@@ -0,0 +1,211 @@
1
+ """Windows Credential Manager, through ctypes (CredWriteW / CredReadW / CredDeleteW / CredEnumerateW).
2
+
3
+ Importable everywhere; the real API loads only on Windows. A generic credential blob holds at most 2,560
4
+ bytes, so a larger value is split into chunks:
5
+
6
+ - ``<namespace>/<key>`` is the *header*. It holds either the whole value (``I1:`` + value) or a pointer to a
7
+ generation of chunks (``C1:<generation>:<count>:<sha256 of the whole value>``).
8
+ - ``<namespace>/<key>#<generation>-<n>`` holds chunk ``n`` of that generation.
9
+
10
+ A generation is random per write, so new chunks never overwrite old ones. A write stores the new chunks, then
11
+ the header (one atomic CredWrite switches the value), then deletes stale chunks. A crash at any point leaves
12
+ either the old value or the new one, never a mix; leftovers are swept by the next write or delete. Callers hold
13
+ the key's lock (``key_lock``) while writing, which is how ``Session`` uses a store.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import secrets
20
+ import sys
21
+
22
+ from ..errors import AuthError, StoreUnavailable
23
+
24
+ MAX_BLOB = 2560 # CRED_MAX_CREDENTIAL_BLOB_SIZE
25
+ CRED_TYPE_GENERIC = 1
26
+ CRED_PERSIST_LOCAL_MACHINE = 2
27
+ ERROR_NOT_FOUND = 1168
28
+ _INLINE = b"I1:"
29
+ _CHUNKED = b"C1:"
30
+
31
+
32
+ class CredentialError(OSError):
33
+ """A Credential Manager call failed; carries only the Windows error code."""
34
+
35
+
36
+ class CredentialManager:
37
+ """The real Win32 API. Tests substitute an in-memory double with the same four methods."""
38
+
39
+ def __init__(self):
40
+ if sys.platform != "win32":
41
+ raise StoreUnavailable("Windows Credential Manager exists only on Windows.")
42
+ import ctypes
43
+ from ctypes import wintypes
44
+
45
+ class FILETIME(ctypes.Structure):
46
+ _fields_ = [("dwLowDateTime", wintypes.DWORD), ("dwHighDateTime", wintypes.DWORD)]
47
+
48
+ class CREDENTIAL(ctypes.Structure):
49
+ _fields_ = [
50
+ ("Flags", wintypes.DWORD),
51
+ ("Type", wintypes.DWORD),
52
+ ("TargetName", wintypes.LPWSTR),
53
+ ("Comment", wintypes.LPWSTR),
54
+ ("LastWritten", FILETIME),
55
+ ("CredentialBlobSize", wintypes.DWORD),
56
+ ("CredentialBlob", ctypes.POINTER(ctypes.c_ubyte)),
57
+ ("Persist", wintypes.DWORD),
58
+ ("AttributeCount", wintypes.DWORD),
59
+ ("Attributes", ctypes.c_void_p),
60
+ ("TargetAlias", wintypes.LPWSTR),
61
+ ("UserName", wintypes.LPWSTR),
62
+ ]
63
+
64
+ self._c = ctypes
65
+ self._CREDENTIAL = CREDENTIAL
66
+ advapi = ctypes.WinDLL("advapi32", use_last_error=True)
67
+ pcred = ctypes.POINTER(CREDENTIAL)
68
+ advapi.CredWriteW.argtypes = [pcred, wintypes.DWORD]
69
+ advapi.CredWriteW.restype = wintypes.BOOL
70
+ advapi.CredReadW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(pcred)]
71
+ advapi.CredReadW.restype = wintypes.BOOL
72
+ advapi.CredDeleteW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD]
73
+ advapi.CredDeleteW.restype = wintypes.BOOL
74
+ advapi.CredEnumerateW.argtypes = [
75
+ wintypes.LPCWSTR,
76
+ wintypes.DWORD,
77
+ ctypes.POINTER(wintypes.DWORD),
78
+ ctypes.POINTER(ctypes.POINTER(pcred)),
79
+ ]
80
+ advapi.CredEnumerateW.restype = wintypes.BOOL
81
+ advapi.CredFree.argtypes = [ctypes.c_void_p]
82
+ advapi.CredFree.restype = None
83
+ self._api = advapi
84
+
85
+ def _fail(self):
86
+ raise CredentialError(self._c.get_last_error(), "credential call failed")
87
+
88
+ def write(self, target: str, blob: bytes, user: str) -> None:
89
+ c = self._c
90
+ buffer = (c.c_ubyte * max(len(blob), 1)).from_buffer_copy(blob or b"\0")
91
+ credential = self._CREDENTIAL()
92
+ credential.Type = CRED_TYPE_GENERIC
93
+ credential.TargetName = target
94
+ credential.CredentialBlobSize = len(blob)
95
+ credential.CredentialBlob = c.cast(buffer, c.POINTER(c.c_ubyte))
96
+ credential.Persist = CRED_PERSIST_LOCAL_MACHINE
97
+ credential.UserName = user
98
+ if not self._api.CredWriteW(c.byref(credential), 0):
99
+ self._fail()
100
+
101
+ def read(self, target: str) -> bytes | None:
102
+ c = self._c
103
+ pointer = c.POINTER(self._CREDENTIAL)()
104
+ if not self._api.CredReadW(target, CRED_TYPE_GENERIC, 0, c.byref(pointer)):
105
+ if c.get_last_error() == ERROR_NOT_FOUND:
106
+ return None
107
+ self._fail()
108
+ try:
109
+ credential = pointer.contents
110
+ return c.string_at(credential.CredentialBlob, credential.CredentialBlobSize) if credential.CredentialBlobSize else b""
111
+ finally:
112
+ self._api.CredFree(pointer)
113
+
114
+ def delete(self, target: str) -> None:
115
+ if not self._api.CredDeleteW(target, CRED_TYPE_GENERIC, 0) and self._c.get_last_error() != ERROR_NOT_FOUND:
116
+ self._fail()
117
+
118
+ def enumerate(self, prefix: str) -> list[str]:
119
+ """Target names that start with ``prefix``."""
120
+ c = self._c
121
+ from ctypes import wintypes
122
+
123
+ count = wintypes.DWORD()
124
+ items = c.POINTER(c.POINTER(self._CREDENTIAL))()
125
+ if not self._api.CredEnumerateW(prefix + "*", 0, c.byref(count), c.byref(items)):
126
+ if c.get_last_error() == ERROR_NOT_FOUND:
127
+ return []
128
+ self._fail()
129
+ try:
130
+ return [items[i].contents.TargetName for i in range(count.value)]
131
+ finally:
132
+ self._api.CredFree(items)
133
+
134
+
135
+ class WindowsCredentialStore:
136
+ name = "Windows Credential Manager"
137
+
138
+ def __init__(self, namespace: str, *, backend=None):
139
+ if not namespace:
140
+ raise AuthError("A store namespace is required.")
141
+ self.namespace = namespace
142
+ self.backend = backend if backend is not None else CredentialManager()
143
+
144
+ def _header(self, key: str) -> str:
145
+ return f"{self.namespace}/{key}"
146
+
147
+ def _chunk(self, key: str, generation: str, index: int) -> str:
148
+ return f"{self.namespace}/{key}#{generation}-{index}"
149
+
150
+ def probe(self) -> None:
151
+ try:
152
+ self.backend.read(self._header("probe"))
153
+ except OSError:
154
+ raise StoreUnavailable("Windows Credential Manager could not be reached; sign in to Windows and retry.") from None
155
+
156
+ def _sweep(self, key: str, keep: str | None) -> None:
157
+ for target in self.backend.enumerate(self._header(key) + "#"):
158
+ if keep is None or not target.startswith(f"{self._header(key)}#{keep}-"):
159
+ self.backend.delete(target)
160
+
161
+ def get(self, key):
162
+ try:
163
+ header = self.backend.read(self._header(key))
164
+ if header is None:
165
+ return None
166
+ if header.startswith(_INLINE):
167
+ return header[len(_INLINE):].decode("utf-8")
168
+ if not header.startswith(_CHUNKED):
169
+ raise ValueError()
170
+ generation, count, digest = header[len(_CHUNKED):].decode("ascii").split(":")
171
+ parts = []
172
+ for index in range(int(count)):
173
+ part = self.backend.read(self._chunk(key, generation, index))
174
+ if part is None:
175
+ raise ValueError()
176
+ parts.append(part)
177
+ value = b"".join(parts)
178
+ if hashlib.sha256(value).hexdigest() != digest:
179
+ raise ValueError()
180
+ return value.decode("utf-8")
181
+ except OSError:
182
+ raise AuthError("Unable to read Windows Credential Manager; retry, or sign in to Windows again.") from None
183
+ except (ValueError, UnicodeDecodeError):
184
+ raise AuthError("The stored session is damaged; run the login command to replace it.") from None
185
+
186
+ def set(self, key, value):
187
+ data = value.encode("utf-8")
188
+ try:
189
+ if len(_INLINE) + len(data) <= MAX_BLOB:
190
+ self.backend.write(self._header(key), _INLINE + data, self.namespace)
191
+ self._sweep(key, None)
192
+ return
193
+ generation = secrets.token_hex(6)
194
+ size = MAX_BLOB
195
+ pieces = [data[i : i + size] for i in range(0, len(data), size)]
196
+ for index, piece in enumerate(pieces):
197
+ self.backend.write(self._chunk(key, generation, index), piece, self.namespace)
198
+ header = f"{generation}:{len(pieces)}:{hashlib.sha256(data).hexdigest()}".encode("ascii")
199
+ self.backend.write(self._header(key), _CHUNKED + header, self.namespace)
200
+ self._sweep(key, generation)
201
+ except OSError:
202
+ raise AuthError(
203
+ "Unable to save the session in Windows Credential Manager; retry login."
204
+ ) from None
205
+
206
+ def delete(self, key):
207
+ try:
208
+ self.backend.delete(self._header(key))
209
+ self._sweep(key, None)
210
+ except OSError:
211
+ raise AuthError("Unable to remove the session from Windows Credential Manager; retry logout.") from None
cli_login/target.py ADDED
@@ -0,0 +1,101 @@
1
+ """The product's target: everything the library needs to sign in, and nothing secret."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import urllib.parse
7
+ from dataclasses import dataclass
8
+
9
+ from .errors import AuthError
10
+
11
+ _SAFE_NAME = re.compile(r"[A-Za-z0-9._-]{1,200}")
12
+
13
+
14
+ def https_url(value: object, label: str, *, origin: bool = False) -> None:
15
+ """Require a plain HTTPS URL (or origin): no credentials, query or fragment."""
16
+ if not isinstance(value, str):
17
+ raise AuthError(f"Invalid {label}: a configured HTTPS URL is required.")
18
+ parsed = urllib.parse.urlsplit(value)
19
+ if (
20
+ parsed.scheme != "https"
21
+ or not parsed.hostname
22
+ or parsed.username
23
+ or parsed.password
24
+ or parsed.query
25
+ or parsed.fragment
26
+ or (origin and parsed.path not in ("", "/"))
27
+ ):
28
+ raise AuthError(f"Invalid {label}: a configured HTTPS {'origin' if origin else 'URL'} is required.")
29
+
30
+
31
+ def is_loopback_callback(callback_uri: str) -> bool:
32
+ """True for a fixed-port HTTP callback on literal 127.0.0.1 or localhost."""
33
+ callback = urllib.parse.urlsplit(callback_uri)
34
+ try:
35
+ port_ok = callback.port is not None and 1024 <= callback.port <= 65535
36
+ except ValueError:
37
+ port_ok = False
38
+ return (
39
+ callback.scheme == "http"
40
+ and callback.hostname in ("127.0.0.1", "localhost")
41
+ and port_ok
42
+ and not (callback.username or callback.password or callback.query or callback.fragment)
43
+ )
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Target:
48
+ issuer: str
49
+ client_id: str
50
+ oauth_domain: str
51
+ token_endpoint: str
52
+ api_endpoint: str
53
+ key: str
54
+ namespace: str
55
+ callback_uri: str
56
+ broker_endpoint: str | None = None
57
+ remote_callback_uri: str | None = None
58
+
59
+ def __post_init__(self):
60
+ https_url(self.issuer, "issuer")
61
+ https_url(self.oauth_domain, "oauth_domain", origin=True)
62
+ https_url(self.token_endpoint, "token_endpoint")
63
+ https_url(self.api_endpoint, "api_endpoint")
64
+ if self.broker_endpoint is not None:
65
+ https_url(self.broker_endpoint, "broker_endpoint")
66
+ # Remote sign-in redirects to the product's own callback page, never to the loopback callback.
67
+ if self.remote_callback_uri is None:
68
+ raise AuthError("A broker needs a remote callback URI: the HTTPS callback page the product serves.")
69
+ if self.remote_callback_uri is not None:
70
+ if self.broker_endpoint is None:
71
+ raise AuthError("A remote callback URI is only used with a broker; configure broker_endpoint as well.")
72
+ https_url(self.remote_callback_uri, "remote_callback_uri")
73
+ object.__setattr__(self, "oauth_domain", self.oauth_domain.rstrip("/"))
74
+ if not self.client_id or not isinstance(self.client_id, str):
75
+ raise AuthError("A registered OAuth client id is required.")
76
+ for label in ("key", "namespace"):
77
+ value = getattr(self, label)
78
+ if not isinstance(value, str) or not _SAFE_NAME.fullmatch(value):
79
+ raise AuthError(f"Invalid {label}: letters, digits, dot, dash and underscore only.")
80
+ if not isinstance(self.callback_uri, str):
81
+ raise AuthError("A callback URI is required.")
82
+ if not is_loopback_callback(self.callback_uri):
83
+ try:
84
+ https_url(self.callback_uri, "callback_uri")
85
+ except AuthError:
86
+ raise AuthError(
87
+ "The callback must be an HTTPS URL, or an HTTP URL on literal 127.0.0.1 or localhost "
88
+ "with a fixed unprivileged port."
89
+ ) from None
90
+
91
+ @property
92
+ def revoke_endpoint(self) -> str:
93
+ return self.oauth_domain + "/oauth2/revoke"
94
+
95
+ @property
96
+ def authorize_endpoint(self) -> str:
97
+ return self.oauth_domain + "/oauth2/authorize"
98
+
99
+ @property
100
+ def has_loopback_callback(self) -> bool:
101
+ return is_loopback_callback(self.callback_uri)