streamwright-console 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.
- streamwright/console/__init__.py +29 -0
- streamwright/console/api/__init__.py +20 -0
- streamwright/console/api/acks.py +162 -0
- streamwright/console/api/app.py +401 -0
- streamwright/console/api/login.py +139 -0
- streamwright/console/api/logs.py +113 -0
- streamwright/console/api/openapi.py +205 -0
- streamwright/console/api/query.py +113 -0
- streamwright/console/auth/__init__.py +21 -0
- streamwright/console/auth/access.py +99 -0
- streamwright/console/auth/authenticator.py +45 -0
- streamwright/console/auth/passwords.py +83 -0
- streamwright/console/auth/sessions.py +65 -0
- streamwright/console/auth/sso.py +186 -0
- streamwright/console/auth/throttle.py +60 -0
- streamwright/console/auth/users.py +111 -0
- streamwright/console/cli/__init__.py +21 -0
- streamwright/console/cli/admin.py +267 -0
- streamwright/console/cli/main.py +110 -0
- streamwright/console/config/__init__.py +18 -0
- streamwright/console/config/check.py +48 -0
- streamwright/console/config/console.py +289 -0
- streamwright/console/config/login.py +141 -0
- streamwright/console/config/service.py +32 -0
- streamwright/console/db/__init__.py +18 -0
- streamwright/console/db/migrations/0001_console_users.py +40 -0
- streamwright/console/db/migrations/__init__.py +29 -0
- streamwright/console/db/tables/__init__.py +34 -0
- streamwright/console/db/tables/base.py +24 -0
- streamwright/console/db/tables/migrations.py +27 -0
- streamwright/console/db/tables/users.py +42 -0
- streamwright/console/db/users.py +95 -0
- streamwright/console/guide.md +99 -0
- streamwright/console/static/app.js +2014 -0
- streamwright/console/static/favicon.png +0 -0
- streamwright/console/static/favicon.svg +1 -0
- streamwright/console/static/index.html +66 -0
- streamwright/console/static/streamwright-logo-dark.svg +1 -0
- streamwright/console/static/style.css +410 -0
- streamwright/console/views/__init__.py +21 -0
- streamwright/console/views/attention.py +145 -0
- streamwright/console/views/filters.py +62 -0
- streamwright/console/views/job_page.py +97 -0
- streamwright/console/views/job_runs.py +222 -0
- streamwright/console/views/job_summaries.py +123 -0
- streamwright/console/views/overview.py +156 -0
- streamwright/console/views/reads.py +354 -0
- streamwright/console/views/run_log.py +77 -0
- streamwright/console/views/stores.py +190 -0
- streamwright_console-0.3.0.dist-info/METADATA +109 -0
- streamwright_console-0.3.0.dist-info/RECORD +55 -0
- streamwright_console-0.3.0.dist-info/WHEEL +5 -0
- streamwright_console-0.3.0.dist-info/entry_points.txt +5 -0
- streamwright_console-0.3.0.dist-info/licenses/LICENSE +201 -0
- streamwright_console-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""
|
|
18
|
+
Who may do what in the console, and how a caller is named: pick a client (its `principals`), acknowledge its problems
|
|
19
|
+
(its `ack_principals`), read its runs' log files (its `log_principals`, else all its principals), the name the page
|
|
20
|
+
shows, and who an acknowledgement records.
|
|
21
|
+
|
|
22
|
+
- A caller is an API key (`key:ops`), a JWT's subject, a console user (`user:alice`, auth.login.users) or a person
|
|
23
|
+
single sign-on named (`sso:<subject>`, with their email and groups). Without auth there is one: the local user.
|
|
24
|
+
- A client lists names: an API key's id grants that key alone; any other name is a console user's id, an SSO email,
|
|
25
|
+
a JWT's subject, or a group of an SSO sign-in or a JWT (its `groups` claim).
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from streamwright.core.jobs.state.tables import KEY_LEN
|
|
29
|
+
from streamwright.core.runtime.whoami import whoami
|
|
30
|
+
|
|
31
|
+
from streamwright.console.auth.sessions import KINDS
|
|
32
|
+
|
|
33
|
+
__all__ = ["display_name", "may_ack", "may_pick", "may_read_logs", "recorded_as"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _names(principal):
|
|
37
|
+
"""The names a client may list for a person: their id, SSO email, groups."""
|
|
38
|
+
groups = principal.claims.get("groups")
|
|
39
|
+
names = {principal.name, principal.claims.get("email") if principal.kind == "sso" else None}
|
|
40
|
+
names.update(group for group in (groups if isinstance(groups, list) else ()) if isinstance(group, str))
|
|
41
|
+
return names - {None}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _listed(console, principal, listed):
|
|
45
|
+
if not console.has_auth:
|
|
46
|
+
return True # the one local user
|
|
47
|
+
keys = {key.id for key in console.api_keys}
|
|
48
|
+
if principal.kind == "key":
|
|
49
|
+
return principal.name in keys and principal.name in listed
|
|
50
|
+
if principal.kind not in ("jwt", *KINDS):
|
|
51
|
+
return False
|
|
52
|
+
names = _names(principal)
|
|
53
|
+
return any(name in names for name in listed if name not in keys) # a key's id is no person's name
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def may_pick(console, principal, client):
|
|
57
|
+
"""Whether the caller may pick the client: no auth (the one local user), or listed in its principals."""
|
|
58
|
+
return _listed(console, principal, client.principals)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def may_ack(console, principal, client):
|
|
62
|
+
"""Whether the caller may acknowledge the client's problems from the page: no auth, or in its ack_principals."""
|
|
63
|
+
return not console.has_auth or (may_pick(console, principal, client) and
|
|
64
|
+
_listed(console, principal, client.ack_principals))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def may_read_logs(console, principal, client):
|
|
68
|
+
"""Whether the caller may read the client's runs' log files: who may pick it, narrowed by its log_principals."""
|
|
69
|
+
return not console.has_auth or (may_pick(console, principal, client) and (
|
|
70
|
+
not client.log_principals or _listed(console, principal, client.log_principals)))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def display_name(principal):
|
|
74
|
+
"""How the page names the caller: a person's name (or email), an API key's id, the local user."""
|
|
75
|
+
claims = principal.claims
|
|
76
|
+
if principal.kind == "anonymous":
|
|
77
|
+
return whoami()
|
|
78
|
+
if principal.kind == "key":
|
|
79
|
+
return "API key %s" % principal.name
|
|
80
|
+
return claims.get("name") or claims.get("email") or claims.get("preferred_username") or principal.name
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def recorded_as(principal):
|
|
84
|
+
"""What an acknowledgement records as who: `Alice Smith (user:alice)`, `Alice Smith (alice@corp.com)`, `key:ops`,
|
|
85
|
+
`alice@corp.com (jwt:00u1ab)`, or the local user (`alice@host`)."""
|
|
86
|
+
claims = principal.claims
|
|
87
|
+
if principal.kind == "anonymous":
|
|
88
|
+
text = whoami()
|
|
89
|
+
elif principal.kind == "key":
|
|
90
|
+
text = principal.id
|
|
91
|
+
elif principal.kind == "user":
|
|
92
|
+
text = "%s (%s)" % (claims["name"], principal.id) if claims.get("name") else principal.id
|
|
93
|
+
elif principal.kind == "sso":
|
|
94
|
+
known = claims.get("email") or principal.id
|
|
95
|
+
text = "%s (%s)" % (claims["name"], known) if claims.get("name") else known
|
|
96
|
+
else:
|
|
97
|
+
label = claims.get("email") or claims.get("preferred_username") or claims.get("name")
|
|
98
|
+
text = "%s (%s)" % (label, principal.id) if label else principal.id
|
|
99
|
+
return text[:KEY_LEN]
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""Who calls the console: serve's Authenticator (API keys, JWTs), and the console's own sessions (auth.login), each
|
|
18
|
+
console user's checked against their database (streamwright.console.auth.users)."""
|
|
19
|
+
|
|
20
|
+
from types import MappingProxyType
|
|
21
|
+
|
|
22
|
+
from streamwright.core.http_service.auth import Authenticator
|
|
23
|
+
from streamwright.core.http_service.errors import RequestError
|
|
24
|
+
|
|
25
|
+
__all__ = ["ConsoleAuthenticator"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ConsoleAuthenticator:
|
|
29
|
+
"""serve's Authenticator (API keys, JWTs), and the console's own sessions (auth.login)."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, console, sessions=None, users=None, base=None):
|
|
32
|
+
self.sessions, self.users = sessions, users
|
|
33
|
+
self.base = base or Authenticator(console)
|
|
34
|
+
|
|
35
|
+
def authenticate(self, authorization):
|
|
36
|
+
scheme, _, token = (authorization or "").partition(" ")
|
|
37
|
+
token = token.strip()
|
|
38
|
+
if self.sessions is not None and scheme.lower() == "bearer" and token.count(".") == 2:
|
|
39
|
+
principal = self.sessions.read(token)
|
|
40
|
+
if principal is not None:
|
|
41
|
+
if principal.kind == "user" and (self.users is None or not self.users.current(principal)):
|
|
42
|
+
raise RequestError(401, "unauthorized", "the session ended: sign in again",
|
|
43
|
+
MappingProxyType({"WWW-Authenticate": "Bearer"}))
|
|
44
|
+
return principal
|
|
45
|
+
return self.base.authenticate(authorization)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""
|
|
18
|
+
Console users' passwords: scrypt hashes (Python's standard library), kept as `scrypt$N$r$p$SALT$HASH` (base64), so a
|
|
19
|
+
stronger cost later leaves the stored ones readable. A check compares in constant time; one for a name that does not
|
|
20
|
+
exist runs against a stand-in hash, so its time does not tell that. Each check takes 32 MiB for a tenth of a second:
|
|
21
|
+
at most CHECKS_AT_ONCE run at once.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import base64
|
|
25
|
+
import functools
|
|
26
|
+
import hashlib
|
|
27
|
+
import hmac
|
|
28
|
+
import secrets
|
|
29
|
+
import threading
|
|
30
|
+
|
|
31
|
+
__all__ = ["CHECKS_AT_ONCE", "MIN_LENGTH", "check_password", "hash_password", "password_problem"]
|
|
32
|
+
|
|
33
|
+
N, R, P = 2 ** 15, 8, 1 # scrypt's cost: 128 * R * N bytes (32 MiB) a hash
|
|
34
|
+
MIN_LENGTH, MAX_LENGTH = 12, 1024
|
|
35
|
+
CHECKS_AT_ONCE = 4
|
|
36
|
+
_MAX_MEMORY = 128 * 1024 * 1024
|
|
37
|
+
_CHECKS = threading.BoundedSemaphore(CHECKS_AT_ONCE)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _b64(data):
|
|
41
|
+
return base64.b64encode(data).decode("ascii").rstrip("=")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _unb64(text):
|
|
45
|
+
return base64.b64decode(text + "=" * (-len(text) % 4), validate=True)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _scrypt(password, salt, n, r, p):
|
|
49
|
+
return hashlib.scrypt(password.encode("utf-8", "surrogatepass"), salt=salt, n=n, r=r, p=p, maxmem=_MAX_MEMORY,
|
|
50
|
+
dklen=32)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def password_problem(password):
|
|
54
|
+
"""Why `password` cannot be a console user's (too short or too long), or None."""
|
|
55
|
+
if len(password) < MIN_LENGTH:
|
|
56
|
+
return "a password has at least %d characters" % MIN_LENGTH
|
|
57
|
+
return "a password has at most %d characters" % MAX_LENGTH if len(password) > MAX_LENGTH else None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def hash_password(password):
|
|
61
|
+
"""The scrypt hash of `password`, with a random salt and its cost."""
|
|
62
|
+
salt = secrets.token_bytes(16)
|
|
63
|
+
return "scrypt$%d$%d$%d$%s$%s" % (N, R, P, _b64(salt), _b64(_scrypt(password, salt, N, R, P)))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@functools.lru_cache(maxsize=1)
|
|
67
|
+
def _stand_in():
|
|
68
|
+
return hash_password(secrets.token_urlsafe(24))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def check_password(password, stored):
|
|
72
|
+
"""Whether `password` is the one `stored` hashes; `stored` None (no such user): checked against a stand-in."""
|
|
73
|
+
known = stored is not None
|
|
74
|
+
try:
|
|
75
|
+
name, n, r, p, salt, digest = (stored if known else _stand_in()).split("$")
|
|
76
|
+
cost, salt, digest = (int(n), int(r), int(p)), _unb64(salt), _unb64(digest)
|
|
77
|
+
except ValueError: # not a hash this module made
|
|
78
|
+
return False
|
|
79
|
+
if name != "scrypt" or len(password) > MAX_LENGTH:
|
|
80
|
+
return False
|
|
81
|
+
with _CHECKS:
|
|
82
|
+
found = _scrypt(password, salt, *cost)
|
|
83
|
+
return hmac.compare_digest(found, digest) and known
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""
|
|
18
|
+
Console sessions: what the page sends back (`Authorization: Bearer`) once a person signed in on the login page, a
|
|
19
|
+
token the console signs (HS256 with auth.login.session_secret_env) naming them, that ends at its expiry
|
|
20
|
+
(auth.login.session_ttl). Nothing is stored: a new secret signs everyone out. A console user's session carries a
|
|
21
|
+
fingerprint of their password's hash, so a new password or their removal ends it (streamwright.console.auth.users).
|
|
22
|
+
The token is a JWT of the console's own: a provider's JWT (asymmetric keys) is never one, nor the other way round.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
import datetime
|
|
26
|
+
import time
|
|
27
|
+
from types import MappingProxyType
|
|
28
|
+
|
|
29
|
+
import jwt
|
|
30
|
+
from streamwright.core.http_service.auth import Principal
|
|
31
|
+
|
|
32
|
+
__all__ = ["KINDS", "Sessions"]
|
|
33
|
+
|
|
34
|
+
KINDS = ("user", "sso") # a console user's session, a single sign-on's
|
|
35
|
+
_AUDIENCE = "streamwright-console"
|
|
36
|
+
_CLAIMS = ("name", "email", "groups", "pw") # the person's: what the console shows, records and matches
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Sessions:
|
|
40
|
+
"""Issues and reads the sessions of auth.login (`clock`: the time a session starts, in seconds)."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, login, clock=time.time):
|
|
43
|
+
self._secret, self.seconds, self._clock = login.session_secret, login.session_seconds, clock
|
|
44
|
+
|
|
45
|
+
def issue(self, principal):
|
|
46
|
+
"""{token, expires_at} of a session of `principal` (a Principal of kind user or sso)."""
|
|
47
|
+
now = int(self._clock())
|
|
48
|
+
claims = {"iss": _AUDIENCE, "aud": _AUDIENCE, "iat": now, "exp": now + self.seconds, "kind": principal.kind,
|
|
49
|
+
"sub": principal.name}
|
|
50
|
+
claims.update((key, principal.claims[key]) for key in _CLAIMS if principal.claims.get(key) is not None)
|
|
51
|
+
expires = datetime.datetime.fromtimestamp(claims["exp"], datetime.UTC)
|
|
52
|
+
return {"token": jwt.encode(claims, self._secret, algorithm="HS256"),
|
|
53
|
+
"expires_at": expires.isoformat().replace("+00:00", "Z")}
|
|
54
|
+
|
|
55
|
+
def read(self, token):
|
|
56
|
+
"""The Principal a session token names, or None (not one of this console's, changed, or expired)."""
|
|
57
|
+
try:
|
|
58
|
+
claims = jwt.decode(token, self._secret, algorithms=["HS256"], audience=_AUDIENCE, issuer=_AUDIENCE,
|
|
59
|
+
options={"require": ["exp", "iat", "iss", "aud", "sub"]})
|
|
60
|
+
except jwt.PyJWTError:
|
|
61
|
+
return None
|
|
62
|
+
if claims.get("kind") not in KINDS or not isinstance(claims.get("sub"), str) or not claims["sub"]:
|
|
63
|
+
return None
|
|
64
|
+
return Principal(claims["kind"], claims["sub"], MappingProxyType({key: claims[key] for key in _CLAIMS
|
|
65
|
+
if key in claims}))
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""
|
|
18
|
+
Single sign-on with OpenID Connect (auth.login.sso): the authorization code flow, with PKCE, state and nonce.
|
|
19
|
+
|
|
20
|
+
1. GET /login/sso: the console makes a state, a nonce and a PKCE verifier (kept here PENDING_SECONDS) and sends the
|
|
21
|
+
person to the provider's authorization endpoint (from ISSUER/.well-known/openid-configuration).
|
|
22
|
+
2. The provider sends them back to /login/callback with a code and the state: the console swaps the code (with the
|
|
23
|
+
verifier, and the client secret when there is one) for tokens at the token endpoint, then checks the ID token: its
|
|
24
|
+
signature (the provider's JWKS), issuer, audience (client_id), expiry and nonce.
|
|
25
|
+
3. The ID token names the person: subject, email (unless the provider says it is not verified), name, and the groups
|
|
26
|
+
console.yaml lists (its `groups` claim). The page gets a one-time code (CODE_SECONDS, once) in its address, and
|
|
27
|
+
swaps it for the console's session: no token travels in an address.
|
|
28
|
+
What is in flight lives in this process: run one console process (a restart loses the sign-ins under way).
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
import base64
|
|
32
|
+
import hashlib
|
|
33
|
+
import secrets
|
|
34
|
+
import threading
|
|
35
|
+
import time
|
|
36
|
+
import urllib.parse
|
|
37
|
+
from collections import OrderedDict
|
|
38
|
+
from types import MappingProxyType
|
|
39
|
+
|
|
40
|
+
import jwt
|
|
41
|
+
import requests
|
|
42
|
+
from streamwright.core.http_service.auth import LEEWAY_SECONDS, Principal, key_algorithms
|
|
43
|
+
|
|
44
|
+
__all__ = ["CODE_SECONDS", "PENDING_SECONDS", "Sso", "SsoError"]
|
|
45
|
+
|
|
46
|
+
PENDING_SECONDS, CODE_SECONDS, DISCOVERY_SECONDS = 600, 60, 3600
|
|
47
|
+
SCOPES = "openid email profile"
|
|
48
|
+
_TIMEOUT = 10
|
|
49
|
+
_MOST_PENDING = 1000
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class SsoError(Exception):
|
|
53
|
+
"""A sign-in the console cannot finish: a state it did not make, the provider's error, an ID token that fails."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _b64(data):
|
|
57
|
+
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Sso:
|
|
61
|
+
"""The single sign-on of auth.login.sso (`groups`: the names console.yaml lists; others are left out)."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, settings, *, groups=(), http=None, jwks=None, clock=time.monotonic):
|
|
64
|
+
self.settings, self.groups, self._clock = settings, frozenset(groups), clock
|
|
65
|
+
self._http, self._given_keys, self._keys = http or requests.Session(), jwks, None
|
|
66
|
+
self._lock, self._pending, self._codes = threading.Lock(), OrderedDict(), OrderedDict()
|
|
67
|
+
self._discovered, self._discovered_at = None, None
|
|
68
|
+
|
|
69
|
+
def _get(self, url):
|
|
70
|
+
try:
|
|
71
|
+
response = self._http.get(url, timeout=_TIMEOUT)
|
|
72
|
+
found = response.json() if response.status_code == 200 else None
|
|
73
|
+
except (requests.RequestException, ValueError) as exc:
|
|
74
|
+
raise SsoError("%s: %s" % (url, exc)) from exc
|
|
75
|
+
if not isinstance(found, dict):
|
|
76
|
+
raise SsoError("%s: HTTP %s, not a JSON object" % (url, response.status_code))
|
|
77
|
+
return found
|
|
78
|
+
|
|
79
|
+
def _discovery(self):
|
|
80
|
+
"""The provider's discovery document (read again after DISCOVERY_SECONDS)."""
|
|
81
|
+
if self._discovered is None or self._clock() - self._discovered_at > DISCOVERY_SECONDS:
|
|
82
|
+
issuer = self.settings.issuer
|
|
83
|
+
found = self._get(issuer.rstrip("/") + "/.well-known/openid-configuration")
|
|
84
|
+
if str(found.get("issuer", "")).rstrip("/") != issuer.rstrip("/"):
|
|
85
|
+
raise SsoError("the provider's issuer is %r, not %r" % (found.get("issuer"), issuer))
|
|
86
|
+
missing = [key for key in ("authorization_endpoint", "token_endpoint", "jwks_uri") if not found.get(key)]
|
|
87
|
+
if missing:
|
|
88
|
+
raise SsoError("the provider's discovery document has no %s" % ", ".join(missing))
|
|
89
|
+
self._discovered, self._discovered_at = found, self._clock()
|
|
90
|
+
return self._discovered
|
|
91
|
+
|
|
92
|
+
def _signing_keys(self):
|
|
93
|
+
"""The provider's keys (its JWKS, read again when the discovery document names another)."""
|
|
94
|
+
uri = self._discovery()["jwks_uri"]
|
|
95
|
+
with self._lock:
|
|
96
|
+
if self._given_keys is not None:
|
|
97
|
+
return self._given_keys
|
|
98
|
+
if self._keys is None or self._keys.uri != uri:
|
|
99
|
+
self._keys = jwt.PyJWKClient(uri, cache_keys=True, lifespan=300, timeout=_TIMEOUT)
|
|
100
|
+
return self._keys
|
|
101
|
+
|
|
102
|
+
def _keep(self, kept, key, value):
|
|
103
|
+
"""Keeps `value` under `key`, dropping what expired and, past _MOST_PENDING, the oldest."""
|
|
104
|
+
with self._lock:
|
|
105
|
+
now = self._clock()
|
|
106
|
+
for old in [old for old, (_, at) in kept.items() if now - at > PENDING_SECONDS]:
|
|
107
|
+
kept.pop(old)
|
|
108
|
+
kept[key] = (value, now)
|
|
109
|
+
while len(kept) > _MOST_PENDING:
|
|
110
|
+
kept.popitem(last=False)
|
|
111
|
+
|
|
112
|
+
def _take(self, kept, key, seconds):
|
|
113
|
+
with self._lock:
|
|
114
|
+
found = kept.pop(key, None) if isinstance(key, str) else None
|
|
115
|
+
return found[0] if found is not None and self._clock() - found[1] <= seconds else None
|
|
116
|
+
|
|
117
|
+
def start(self, callback_url):
|
|
118
|
+
"""The provider's authorization address for a new sign-in returning to `callback_url`."""
|
|
119
|
+
endpoint = self._discovery()["authorization_endpoint"]
|
|
120
|
+
state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3))
|
|
121
|
+
self._keep(self._pending, state, (nonce, verifier, callback_url))
|
|
122
|
+
query = urllib.parse.urlencode({
|
|
123
|
+
"response_type": "code", "client_id": self.settings.client_id, "redirect_uri": callback_url,
|
|
124
|
+
"scope": SCOPES, "state": state, "nonce": nonce, "code_challenge_method": "S256",
|
|
125
|
+
"code_challenge": _b64(hashlib.sha256(verifier.encode("ascii")).digest())})
|
|
126
|
+
return endpoint + ("&" if "?" in endpoint else "?") + query
|
|
127
|
+
|
|
128
|
+
def finish(self, state, code, error=None):
|
|
129
|
+
"""A one-time code for the person the provider signed in (the callback's state and code); SsoError."""
|
|
130
|
+
pending = self._take(self._pending, state, PENDING_SECONDS)
|
|
131
|
+
if pending is None:
|
|
132
|
+
raise SsoError("a sign-in this console did not start, or older than %d minutes" % (PENDING_SECONDS // 60))
|
|
133
|
+
if error or not code:
|
|
134
|
+
raise SsoError("the provider says: %s" % (error or "no code"))
|
|
135
|
+
nonce, verifier, callback_url = pending
|
|
136
|
+
claims = self._checked(self._tokens(code, verifier, callback_url), nonce)
|
|
137
|
+
groups = claims.get("groups")
|
|
138
|
+
person = {"name": claims.get("name") if isinstance(claims.get("name"), str) else None,
|
|
139
|
+
"email": claims.get("email") if isinstance(claims.get("email"), str) and
|
|
140
|
+
claims.get("email_verified") is not False else None,
|
|
141
|
+
"groups": sorted({group for group in (groups if isinstance(groups, list) else ())
|
|
142
|
+
if isinstance(group, str) and group in self.groups})}
|
|
143
|
+
one_time = secrets.token_urlsafe(32)
|
|
144
|
+
self._keep(self._codes, one_time, Principal("sso", claims["sub"], MappingProxyType(person)))
|
|
145
|
+
return one_time
|
|
146
|
+
|
|
147
|
+
def exchange(self, code):
|
|
148
|
+
"""The person a one-time code stands for (once, within CODE_SECONDS), or None."""
|
|
149
|
+
return self._take(self._codes, code, CODE_SECONDS)
|
|
150
|
+
|
|
151
|
+
def _tokens(self, code, verifier, callback_url):
|
|
152
|
+
settings = self.settings
|
|
153
|
+
data = {"grant_type": "authorization_code", "code": code, "redirect_uri": callback_url,
|
|
154
|
+
"code_verifier": verifier}
|
|
155
|
+
auth = (settings.client_id, settings.client_secret) if settings.client_secret else None
|
|
156
|
+
if auth is None:
|
|
157
|
+
data["client_id"] = settings.client_id # a public client names itself
|
|
158
|
+
url = self._discovery()["token_endpoint"]
|
|
159
|
+
try:
|
|
160
|
+
response = self._http.post(url, data=data, auth=auth, timeout=_TIMEOUT)
|
|
161
|
+
found = response.json()
|
|
162
|
+
except (requests.RequestException, ValueError) as exc:
|
|
163
|
+
raise SsoError("the token endpoint: %s" % exc) from exc
|
|
164
|
+
if response.status_code != 200 or not isinstance(found, dict) or not found.get("id_token"):
|
|
165
|
+
error = found.get("error") if isinstance(found, dict) else None
|
|
166
|
+
raise SsoError("the token endpoint answered HTTP %s%s" % (response.status_code,
|
|
167
|
+
": %s" % error if error else ""))
|
|
168
|
+
return found["id_token"]
|
|
169
|
+
|
|
170
|
+
def _checked(self, id_token, nonce):
|
|
171
|
+
discovery = self._discovery()
|
|
172
|
+
try:
|
|
173
|
+
key = self._signing_keys().get_signing_key_from_jwt(id_token)
|
|
174
|
+
claims = jwt.decode(id_token, key.key, algorithms=key_algorithms(key), audience=self.settings.client_id,
|
|
175
|
+
issuer=discovery["issuer"], leeway=LEEWAY_SECONDS,
|
|
176
|
+
options={"require": ["exp", "iat", "iss", "aud", "sub"]})
|
|
177
|
+
except Exception as exc: # a bad token, a key it does not fit, an unreachable JWKS
|
|
178
|
+
raise SsoError("the ID token: %s" % exc) from exc
|
|
179
|
+
audiences = claims["aud"] if isinstance(claims["aud"], list) else [claims["aud"]]
|
|
180
|
+
if len(audiences) > 1 and claims.get("azp") != self.settings.client_id:
|
|
181
|
+
raise SsoError("the ID token is for several audiences, and not authorized for this console (azp)")
|
|
182
|
+
if not secrets.compare_digest(str(claims.get("nonce", "")), nonce):
|
|
183
|
+
raise SsoError("the ID token's nonce is not this sign-in's")
|
|
184
|
+
if not isinstance(claims["sub"], str) or not claims["sub"]:
|
|
185
|
+
raise SsoError("the ID token names no subject")
|
|
186
|
+
return claims
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""Failed sign-ins slow down: a name waits WAIT_SECONDS after NAME_FAILURES of them, an address after
|
|
18
|
+
ADDRESS_FAILURES (behind a proxy the address is the proxy's: it allows more)."""
|
|
19
|
+
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
from collections import OrderedDict
|
|
23
|
+
|
|
24
|
+
__all__ = ["ADDRESS_FAILURES", "NAME_FAILURES", "WAIT_SECONDS", "Throttle"]
|
|
25
|
+
|
|
26
|
+
NAME_FAILURES, ADDRESS_FAILURES, WAIT_SECONDS = 5, 20, 60
|
|
27
|
+
_KEPT = 10000 # names and addresses remembered at most
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Throttle:
|
|
31
|
+
"""Failed sign-ins: a name waits WAIT_SECONDS after NAME_FAILURES of them, an address after ADDRESS_FAILURES."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, clock=time.monotonic):
|
|
34
|
+
self._clock, self._failed, self._lock = clock, OrderedDict(), threading.Lock()
|
|
35
|
+
|
|
36
|
+
def _recent(self, key):
|
|
37
|
+
now = self._clock()
|
|
38
|
+
times = [at for at in self._failed.get(key, ()) if now - at < WAIT_SECONDS]
|
|
39
|
+
if times:
|
|
40
|
+
self._failed[key] = times
|
|
41
|
+
else:
|
|
42
|
+
self._failed.pop(key, None)
|
|
43
|
+
return times
|
|
44
|
+
|
|
45
|
+
def waiting(self, name, address):
|
|
46
|
+
with self._lock:
|
|
47
|
+
return (len(self._recent(("name", name.lower()))) >= NAME_FAILURES or
|
|
48
|
+
len(self._recent(("address", address))) >= ADDRESS_FAILURES)
|
|
49
|
+
|
|
50
|
+
def failed(self, name, address):
|
|
51
|
+
with self._lock:
|
|
52
|
+
for key in (("name", name.lower()), ("address", address)):
|
|
53
|
+
self._failed[key] = [*self._recent(key), self._clock()]
|
|
54
|
+
self._failed.move_to_end(key)
|
|
55
|
+
while len(self._failed) > _KEPT:
|
|
56
|
+
self._failed.popitem(last=False)
|
|
57
|
+
|
|
58
|
+
def succeeded(self, name):
|
|
59
|
+
with self._lock:
|
|
60
|
+
self._failed.pop(("name", name.lower()), None)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""
|
|
18
|
+
The console users of auth.login.users, as the console signs them in: read from the console's own database
|
|
19
|
+
(streamwright.console.db.users) on sign-in, and again at most every CHECK_SECONDS for each session, so a new password,
|
|
20
|
+
or their removal, ends it. While the database cannot be read, a session stands.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import hashlib
|
|
24
|
+
import logging
|
|
25
|
+
import threading
|
|
26
|
+
import time
|
|
27
|
+
from collections import OrderedDict
|
|
28
|
+
from types import MappingProxyType
|
|
29
|
+
|
|
30
|
+
from streamwright.core.http_service.auth import Principal
|
|
31
|
+
from streamwright.core.http_service.state_store import open_state
|
|
32
|
+
from streamwright.core.runtime.redact import Redactor
|
|
33
|
+
|
|
34
|
+
from streamwright.console.auth.passwords import check_password
|
|
35
|
+
from streamwright.console.db.users import ConsoleStore
|
|
36
|
+
from streamwright.console.views.stores import bounded
|
|
37
|
+
|
|
38
|
+
__all__ = ["CHECK_SECONDS", "Users", "UsersUnreachableError"]
|
|
39
|
+
|
|
40
|
+
LOG = logging.getLogger("streamwright.console")
|
|
41
|
+
CHECK_SECONDS = 60
|
|
42
|
+
_KEPT = 10000 # sessions remembered as checked at most
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class UsersUnreachableError(Exception):
|
|
46
|
+
"""The console users' database cannot be read (the console's log says why)."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _fingerprint(password_hash):
|
|
50
|
+
return hashlib.sha256(password_hash.encode("utf-8")).hexdigest()[:16]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Users:
|
|
54
|
+
"""The console users of auth.login.users (a StateSpec): sign-ins, and whether a session's user is still current."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, spec, *, secrets=(), opener=None, clock=time.monotonic):
|
|
57
|
+
"""`secrets`: the values put in `spec` (masked in log lines)."""
|
|
58
|
+
self._spec, self._clock, self._redact = spec, clock, Redactor()
|
|
59
|
+
self._opener = opener or (lambda found: open_state(bounded(found), existing=True, read_only=True).as_family(
|
|
60
|
+
ConsoleStore))
|
|
61
|
+
self._store, self._lock, self._current = None, threading.Lock(), OrderedDict()
|
|
62
|
+
for value in secrets:
|
|
63
|
+
self._redact.add(value)
|
|
64
|
+
|
|
65
|
+
def _get(self, user_id):
|
|
66
|
+
try:
|
|
67
|
+
with self._lock:
|
|
68
|
+
if self._store is None:
|
|
69
|
+
self._store = self._opener(self._spec)
|
|
70
|
+
store = self._store
|
|
71
|
+
return store.get_user(user_id)
|
|
72
|
+
except Exception as exc: # the driver's error, a file missing, no sw_console_users yet
|
|
73
|
+
with self._lock:
|
|
74
|
+
self._store = None
|
|
75
|
+
LOG.warning("%s", self._redact("the console users cannot be read: %s: %s (their tables come from "
|
|
76
|
+
"`streamwright console migrate --url URL`)" % (
|
|
77
|
+
type(exc).__name__, str(exc).split("\n", 1)[0])))
|
|
78
|
+
raise UsersUnreachableError(type(exc).__name__) from exc
|
|
79
|
+
|
|
80
|
+
def sign_in(self, user_id, password):
|
|
81
|
+
"""The Principal of a console user whose password this is, or None; UsersUnreachableError."""
|
|
82
|
+
found = self._get(user_id)
|
|
83
|
+
if not check_password(password, found["password_hash"] if found else None):
|
|
84
|
+
return None
|
|
85
|
+
self._checked((user_id, _fingerprint(found["password_hash"])))
|
|
86
|
+
return Principal("user", user_id, MappingProxyType({"name": found["name"],
|
|
87
|
+
"pw": _fingerprint(found["password_hash"])}))
|
|
88
|
+
|
|
89
|
+
def _checked(self, key):
|
|
90
|
+
"""The user and password hash `key` were current just now."""
|
|
91
|
+
with self._lock:
|
|
92
|
+
self._current[key] = self._clock()
|
|
93
|
+
self._current.move_to_end(key)
|
|
94
|
+
while len(self._current) > _KEPT:
|
|
95
|
+
self._current.popitem(last=False)
|
|
96
|
+
|
|
97
|
+
def current(self, principal):
|
|
98
|
+
"""Whether a session's user still exists with the password it signed in with (asked at most every
|
|
99
|
+
CHECK_SECONDS; while the database cannot be read, the session stands)."""
|
|
100
|
+
key = (principal.name, principal.claims.get("pw"))
|
|
101
|
+
with self._lock:
|
|
102
|
+
if self._clock() - self._current.get(key, float("-inf")) < CHECK_SECONDS:
|
|
103
|
+
return True
|
|
104
|
+
try:
|
|
105
|
+
found = self._get(principal.name)
|
|
106
|
+
except UsersUnreachableError:
|
|
107
|
+
return True
|
|
108
|
+
if found is None or _fingerprint(found["password_hash"]) != key[1]:
|
|
109
|
+
return False
|
|
110
|
+
self._checked(key)
|
|
111
|
+
return True
|