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.
Files changed (55) hide show
  1. streamwright/console/__init__.py +29 -0
  2. streamwright/console/api/__init__.py +20 -0
  3. streamwright/console/api/acks.py +162 -0
  4. streamwright/console/api/app.py +401 -0
  5. streamwright/console/api/login.py +139 -0
  6. streamwright/console/api/logs.py +113 -0
  7. streamwright/console/api/openapi.py +205 -0
  8. streamwright/console/api/query.py +113 -0
  9. streamwright/console/auth/__init__.py +21 -0
  10. streamwright/console/auth/access.py +99 -0
  11. streamwright/console/auth/authenticator.py +45 -0
  12. streamwright/console/auth/passwords.py +83 -0
  13. streamwright/console/auth/sessions.py +65 -0
  14. streamwright/console/auth/sso.py +186 -0
  15. streamwright/console/auth/throttle.py +60 -0
  16. streamwright/console/auth/users.py +111 -0
  17. streamwright/console/cli/__init__.py +21 -0
  18. streamwright/console/cli/admin.py +267 -0
  19. streamwright/console/cli/main.py +110 -0
  20. streamwright/console/config/__init__.py +18 -0
  21. streamwright/console/config/check.py +48 -0
  22. streamwright/console/config/console.py +289 -0
  23. streamwright/console/config/login.py +141 -0
  24. streamwright/console/config/service.py +32 -0
  25. streamwright/console/db/__init__.py +18 -0
  26. streamwright/console/db/migrations/0001_console_users.py +40 -0
  27. streamwright/console/db/migrations/__init__.py +29 -0
  28. streamwright/console/db/tables/__init__.py +34 -0
  29. streamwright/console/db/tables/base.py +24 -0
  30. streamwright/console/db/tables/migrations.py +27 -0
  31. streamwright/console/db/tables/users.py +42 -0
  32. streamwright/console/db/users.py +95 -0
  33. streamwright/console/guide.md +99 -0
  34. streamwright/console/static/app.js +2014 -0
  35. streamwright/console/static/favicon.png +0 -0
  36. streamwright/console/static/favicon.svg +1 -0
  37. streamwright/console/static/index.html +66 -0
  38. streamwright/console/static/streamwright-logo-dark.svg +1 -0
  39. streamwright/console/static/style.css +410 -0
  40. streamwright/console/views/__init__.py +21 -0
  41. streamwright/console/views/attention.py +145 -0
  42. streamwright/console/views/filters.py +62 -0
  43. streamwright/console/views/job_page.py +97 -0
  44. streamwright/console/views/job_runs.py +222 -0
  45. streamwright/console/views/job_summaries.py +123 -0
  46. streamwright/console/views/overview.py +156 -0
  47. streamwright/console/views/reads.py +354 -0
  48. streamwright/console/views/run_log.py +77 -0
  49. streamwright/console/views/stores.py +190 -0
  50. streamwright_console-0.3.0.dist-info/METADATA +109 -0
  51. streamwright_console-0.3.0.dist-info/RECORD +55 -0
  52. streamwright_console-0.3.0.dist-info/WHEEL +5 -0
  53. streamwright_console-0.3.0.dist-info/entry_points.txt +5 -0
  54. streamwright_console-0.3.0.dist-info/licenses/LICENSE +201 -0
  55. streamwright_console-0.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,289 @@
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.yaml: the clients a console shows, where each one's state databases are, how their credentials are found, and
19
+ who may pick each client. Nothing connects at start: a client's lookups run, and its stores open, when it is picked.
20
+
21
+ kind: console # what the file is (required)
22
+ bind: 127.0.0.1:8090 # a non-loopback address needs `auth`
23
+ auth: {api_keys: [...], jwt: {...}} # as serve.yaml's; and login: {users, sso, ...}, the login page's
24
+ allow_lookup_exec: false # command and function lookups (as --allow-lookup-exec)
25
+ cache: {clients: 20, ttl: 10m} # clients kept open, and how long their resolved secrets are kept
26
+ links: {logs: "https://splunk.example.com/...q=req%3D{request_id}"} # a batch's logs, by its request id
27
+ defaults: # merged into every client ({{ client.id }} is the client's id)
28
+ lookups: {db: {type: aws_secretsmanager, secret_id: "sw/clients/{{ client.id }}/state"}}
29
+ secrets: {password: {lookup: {from: db, field: password}}}
30
+ include: [clients/*.yaml] # files holding only `clients:`
31
+ clients:
32
+ acme: # the client's id: its URL segment (/v1/clients/acme)
33
+ name: Acme Corp
34
+ principals: [ops, acme-team] # API key ids, console users, SSO emails, JWT subjects, or groups
35
+ ack_principals: [ops] # who of them may also acknowledge from the page (default: nobody)
36
+ stores: # each a serve.yaml `state` block: url, or connection and schema
37
+ main: {state: {connection: {provider: postgres, host: acme-db, database: sw, user: console_ro,
38
+ password: "{{ secrets.password }}"}, schema: sw}}
39
+ lookups: {...} # the client's own, beside the defaults' (the jobs' spec.lookups)
40
+ secrets: {...} # name: {lookup: {from, field}}; a secret without one comes from
41
+ # STREAMWRIGHT_SECRET_<NAME>
42
+ """
43
+
44
+ import copy
45
+ import os
46
+ import re
47
+ from dataclasses import dataclass, field
48
+ from types import MappingProxyType
49
+ from typing import Any
50
+
51
+ from streamwright.core.config.inputs import InputError, parse_duration
52
+ from streamwright.core.http_service.access import AUTH_FIELD, Access, Jwt, access_problems, api_keys_of, bind_address
53
+ from streamwright.core.http_service.config_files import DURATION_FIELD, declared_entries, read_yaml
54
+ from streamwright.core.http_service.errors import ConfigError
55
+ from streamwright.core.http_service.state import STATE_CONNECTION_FIELD, STATE_HINTS, STATE_SCHEMA_FIELD
56
+ from streamwright.core.jobs.fields import Field
57
+ from streamwright.core.jobs.lookups.rules import INPUT_LOOKUP_FIELD, LOOKUPS_FIELD
58
+
59
+ from streamwright.console.config.login import LOGIN_FIELD, login_of
60
+
61
+ __all__ = ["CONSOLE_FIELD", "KIND", "Client", "Console", "ConsoleError", "load_console"]
62
+
63
+ KIND = "console" # console.yaml's `kind:`
64
+ DEFAULT_BIND = "127.0.0.1:8090"
65
+ CLIENT_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
66
+ _CLIENT_REF = re.compile(r"\{\{\s*client\.(id|name)\s*\}\}")
67
+ _FILLED_IN = "{{ client.id }} and {{ client.name }} are filled in"
68
+ _JOB_LOOKUP = LOOKUPS_FIELD.values # a console's lookups are a job's, but for database ones
69
+ _LOOKUP_KINDS = ("command", "function", "aws_secretsmanager")
70
+ _LOOKUPS_FIELD = Field("object", values=Field("object", fields={
71
+ "type": Field("string", required=True, enum=_LOOKUP_KINDS, hints={
72
+ "database": "a database lookup needs a job's connections, and a console has none"}),
73
+ "format": _JOB_LOOKUP.fields["format"],
74
+ }, discriminator="type", variants={
75
+ "command": {**_JOB_LOOKUP.variants["command"], "command": Field(
76
+ "array", min_items=1, items=Field("string"), description="the program and its arguments (no shell); %s; pass "
77
+ "sensitive values on stdin, not here" % _FILLED_IN)},
78
+ "function": _JOB_LOOKUP.variants["function"],
79
+ "aws_secretsmanager": _JOB_LOOKUP.variants["aws_secretsmanager"],
80
+ }), description="values fetched when the client is picked, to resolve its secrets (%s); command and function lookups "
81
+ "need `allow_lookup_exec: true`" % _FILLED_IN)
82
+ _SECRET_FIELD = Field("object", fields={
83
+ "lookup": Field("object", fields={
84
+ "from": Field("string", required=True, description="one of the client's lookups (its own or the defaults')"),
85
+ "field": INPUT_LOOKUP_FIELD.fields["field"]}, description="the lookup whose value (or a field of it) it is"),
86
+ "description": Field("string")}, description="a secret: its lookup (else STREAMWRIGHT_SECRET_<NAME>)")
87
+ _SECRETS_FIELD = Field("object", values=_SECRET_FIELD,
88
+ description="the secrets its stores' state blocks use ({{ secrets.NAME }}), by name")
89
+ _STORE_FIELD = Field("object", fields={"state": Field("object", required=True, fields={
90
+ "url": Field("string", description="a state database URL, as `state --url` takes one (a relative sqlite:///PATH "
91
+ "starts at the folder of the file declaring the client); {{ secrets.NAME }} "
92
+ "for credentials"),
93
+ "connection": STATE_CONNECTION_FIELD,
94
+ "schema": STATE_SCHEMA_FIELD,
95
+ }, hints=STATE_HINTS, description="a state database of the client's jobs, read only: url, or connection and "
96
+ "schema (as serve.yaml's `state`; not a job's runtime.state)"),
97
+ "logs": Field("object", fields={"dir": Field("string", required=True, description=(
98
+ "the folder its runs write their log files to (their --log-dir), as this host sees it: a local path or a "
99
+ "shared mount; relative to the file declaring the client"))},
100
+ description="its runs' own log files, shown on the page (default: none)")})
101
+ CLIENT_FIELD = Field("object", fields={
102
+ "name": Field("string", description="shown in the client picker (default: the id)"),
103
+ "principals": Field("array", min_items=1, items=Field("string"),
104
+ description="who may pick the client: API key ids, console users, SSO emails, JWT subjects "
105
+ "or groups (required with auth)"),
106
+ "ack_principals": Field("array", min_items=1, items=Field("string"),
107
+ description="who of its principals may also acknowledge its problems from the page "
108
+ "(default: nobody; with no auth, the one local user may)"),
109
+ "log_principals": Field("array", min_items=1, items=Field("string"),
110
+ description="who of its principals may read its runs' log files (default: all of them; "
111
+ "logs may hold row values a step logs)"),
112
+ "stores": Field("object", required=True, min_items=1, values=_STORE_FIELD,
113
+ description="the state databases of the client's jobs, by name"),
114
+ "lookups": _LOOKUPS_FIELD,
115
+ "secrets": _SECRETS_FIELD,
116
+ })
117
+ _DEFAULTS_FIELD = Field("object", fields={"lookups": _LOOKUPS_FIELD, "secrets": _SECRETS_FIELD},
118
+ description="lookups and secrets every client has (its own of the same name win); %s per "
119
+ "client" % _FILLED_IN)
120
+ CONSOLE_FIELD = Field("object", fields={
121
+ "kind": Field("string", required=True, enum=(KIND,), description="always %s: the file is a console.yaml" % KIND,
122
+ hints={"serve": "a serve.yaml: `streamwright serve` serves it"}),
123
+ "bind": Field("string", description="host:port (default %s)" % DEFAULT_BIND),
124
+ "auth": Field("object", fields={**AUTH_FIELD.fields, "login": LOGIN_FIELD},
125
+ description="who may sign in: API keys and/or JWTs, as serve.yaml's, and people on the login page "
126
+ "(login); required off loopback"),
127
+ "allow_lookup_exec": Field("boolean", description="command and function lookups may run (default false)"),
128
+ "cache": Field("object", fields={
129
+ "clients": Field("integer", minimum=1, description="clients kept open at once (default 20)"),
130
+ "ttl": DURATION_FIELD}, description="clients kept open, and how long their looked-up secrets are kept"),
131
+ "links": Field("object", fields={
132
+ "logs": Field("string", pattern=r"^https?://", description="a batch's logs: {request_id} and {job_id} are "
133
+ "filled in")},
134
+ description="links to other tools"),
135
+ "defaults": _DEFAULTS_FIELD,
136
+ "include": Field("array", min_items=1, items=Field("string"),
137
+ description="files of more clients: paths or globs relative to console.yaml, each holding only "
138
+ "`clients:`"),
139
+ "clients": Field("object", values=CLIENT_FIELD,
140
+ description="the clients by id (their URL segment); more in files `include` names"),
141
+ }, discriminator="kind", hints={
142
+ "cors": "the console serves its page and its API from one origin, so it takes no CORS settings (serve.yaml's "
143
+ "`cors` lets pages on other origins call serve)"})
144
+ INCLUDED_FIELD = Field("object", fields={
145
+ "kind": Field("string", enum=(KIND,), description="optional: with it, the file is a console.yaml of its own too"),
146
+ "clients": Field("object", required=True, min_items=1, values=CLIENT_FIELD)},
147
+ description="a file console.yaml's `include` names: only `clients:`, its paths relative to it")
148
+
149
+
150
+ class ConsoleError(ConfigError):
151
+ """console.yaml cannot be used: every problem, one per line."""
152
+
153
+
154
+ @dataclass(frozen=True)
155
+ class Client:
156
+ """One client: its stores (state blocks), and the lookups and secrets that resolve their credentials."""
157
+ id: str
158
+ name: str
159
+ principals: tuple
160
+ stores: Any # {name: state block}, {{ client.* }} rendered
161
+ lookups: Any # the jobs' spec.lookups, defaults merged in
162
+ secrets: Any # {name: {lookup: {from, field}}}, defaults merged in
163
+ folder: str # relative sqlite:/// paths start here
164
+ source: str = "" # the included file declaring it (relative), or ""
165
+ ack_principals: tuple = () # who may acknowledge from the page
166
+ log_principals: tuple = () # who may read its runs' logs (default: all its principals)
167
+ log_dirs: Any = field(default_factory=lambda: MappingProxyType({})) # {store: its runs' log folder}
168
+
169
+
170
+ @dataclass(frozen=True)
171
+ class Console(Access):
172
+ path: str
173
+ host: str
174
+ port: int
175
+ api_keys: tuple = ()
176
+ jwt: Any = None
177
+ clients: Any = field(default_factory=lambda: MappingProxyType({}))
178
+ allow_lookup_exec: bool = False
179
+ cache_clients: int = 20
180
+ cache_seconds: int = 600
181
+ logs_link: str | None = None
182
+ login: Any = None # a config.login.Login: the login page's users, SSO and sessions
183
+
184
+ @property
185
+ def has_auth(self):
186
+ return bool(self.api_keys) or self.jwt is not None or self.login is not None
187
+
188
+ @property
189
+ def keys_only(self):
190
+ return bool(self.api_keys) and self.jwt is None and self.login is None
191
+
192
+
193
+ def _rendered(value, client_id, name):
194
+ """`value` with {{ client.id }} and {{ client.name }} filled in (other references are left as they are)."""
195
+ if isinstance(value, dict):
196
+ return {key: _rendered(item, client_id, name) for key, item in value.items()}
197
+ if isinstance(value, list):
198
+ return [_rendered(item, client_id, name) for item in value]
199
+ if isinstance(value, str):
200
+ return _CLIENT_REF.sub(lambda match: client_id if match.group(1) == "id" else name, value)
201
+ return value
202
+
203
+
204
+ def _client(client_id, entry, defaults, folder, *, source, problems):
205
+ where = "%sclients.%s" % ("%s: " % source if source else "", client_id)
206
+ if not CLIENT_ID.match(str(client_id)):
207
+ problems.append("%s: a client id is its URL segment (/v1/clients/ID): 1-64 of letters, digits and _ . -, "
208
+ "starting with a letter or digit" % where)
209
+ name = entry.get("name") or client_id
210
+ lookups = _rendered({**copy.deepcopy(dict(defaults.get("lookups") or {})), **(entry.get("lookups") or {})},
211
+ client_id, name)
212
+ secrets = _rendered({**copy.deepcopy(dict(defaults.get("secrets") or {})), **(entry.get("secrets") or {})},
213
+ client_id, name)
214
+ stores = _rendered(copy.deepcopy(dict(entry["stores"])), client_id, name)
215
+ for secret, definition in secrets.items():
216
+ source_name = ((definition or {}).get("lookup") or {}).get("from")
217
+ if source_name is not None and source_name not in lookups:
218
+ problems.append("%s.secrets.%s.lookup.from: no lookup %r (lookups: %s)" % (
219
+ where, secret, source_name, ", ".join(sorted(lookups)) or "none"))
220
+ for store, block in stores.items():
221
+ state = block.get("state") or {}
222
+ if ("url" in state) == ("connection" in state):
223
+ problems.append("%s.stores.%s.state: give exactly one of url or connection" % (where, store))
224
+ elif "connection" in state and not (state["connection"] or {}).get("provider"):
225
+ problems.append("%s.stores.%s.state.connection.provider: required" % (where, store))
226
+ log_dirs = {store: os.path.abspath(os.path.join(folder or ".", os.path.expanduser(block["logs"]["dir"])))
227
+ for store, block in stores.items() if (block.get("logs") or {}).get("dir")}
228
+ return Client(client_id, name, tuple(entry.get("principals") or ()), MappingProxyType(stores),
229
+ MappingProxyType(lookups), MappingProxyType(secrets), folder, source,
230
+ tuple(entry.get("ack_principals") or ()), tuple(entry.get("log_principals") or ()),
231
+ MappingProxyType(log_dirs))
232
+
233
+
234
+ def _clients(data, path, problems):
235
+ clients, defaults = {}, data.get("defaults") or {}
236
+ for client_id, entry, folder, label in declared_entries(data, "clients", path, INCLUDED_FIELD, problems,
237
+ file_name="console.yaml"):
238
+ clients[client_id] = _client(client_id, entry, defaults, folder, source=label, problems=problems)
239
+ if not clients and not problems and not data.get("include"): # the included files hold them (or a problem)
240
+ problems.append("clients: no client: list them under `clients` or in files named by `include`")
241
+ return MappingProxyType(dict(sorted(clients.items(), key=lambda item: item[1].name.lower())))
242
+
243
+
244
+ def _subset_problems(console):
245
+ """With auth, a client's ack_principals and log_principals are among its principals: who cannot see a client
246
+ cannot acknowledge its problems or read its logs."""
247
+ if not console.has_auth:
248
+ return []
249
+ return ["%sclients.%s.%s: %r is not one of its principals" % (
250
+ "%s: " % client.source if client.source else "", client.id, key, name)
251
+ for client in console.clients.values() for key in ("ack_principals", "log_principals")
252
+ for name in getattr(client, key) if name not in client.principals]
253
+
254
+
255
+ def load_console(path, environ=None, *, static=False, text=None):
256
+ """
257
+ The Console of console.yaml at `path`; raises ConsoleError. `static` (streamwright validate): what the environment
258
+ gives (API key digests) is not required. No lookup runs and no store opens here. `text`: console.yaml's YAML, read
259
+ as the file at `path`; with no `path`, nothing it names (included files) is read.
260
+ """
261
+ environ = os.environ if environ is None else environ
262
+ path = os.path.abspath(path) if path else None
263
+ data = read_yaml(path or "console.yaml", CONSOLE_FIELD, "", text=text, error=ConsoleError)
264
+ problems, ignored = [], []
265
+ host, port = bind_address(data.get("bind", DEFAULT_BIND), problems)
266
+ auth = data.get("auth") or {}
267
+ jwt = auth.get("jwt")
268
+ cache = data.get("cache") or {}
269
+ try:
270
+ ttl = int(parse_duration(cache.get("ttl", "10m")).total_seconds())
271
+ except InputError as exc:
272
+ problems.append("cache.ttl: %s" % exc)
273
+ ttl = 600
274
+ console = Console(path=path, host=host, port=port,
275
+ api_keys=api_keys_of(auth, environ, problems, ignored if static else problems),
276
+ jwt=Jwt(**jwt) if jwt else None, clients=_clients(data, path, problems),
277
+ allow_lookup_exec=bool(data.get("allow_lookup_exec", False)),
278
+ cache_clients=int(cache.get("clients", 20)), cache_seconds=ttl,
279
+ logs_link=(data.get("links") or {}).get("logs"),
280
+ login=login_of(auth.get("login"), os.path.dirname(path or os.path.abspath("console.yaml")),
281
+ environ, problems, ignored if static else problems))
282
+ problems.extend(access_problems(
283
+ console, [("%sclients.%s" % ("%s: " % client.source if client.source else "", client.id), client.principals)
284
+ for client in console.clients.values()], file_name="console.yaml", kind="console", what="client",
285
+ who="users"))
286
+ problems.extend(_subset_problems(console))
287
+ if problems:
288
+ raise ConsoleError(problems)
289
+ return console
@@ -0,0 +1,141 @@
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.yaml's auth.login: how people sign in on the console's login page, beside the API keys and JWTs of scripts.
19
+
20
+ auth:
21
+ login:
22
+ users: {url: "sqlite:///console-users.db"} # console users: the console's own database (`streamwright console
23
+ # migrate`, `console users add`): url, or connection and schema
24
+ sso: # OpenID Connect: Okta, Entra ID, Google, Keycloak, ...
25
+ label: Okta # "Sign in with Okta"
26
+ issuer: https://example.okta.com/oauth2/default
27
+ client_id: 0oa1b2c3d4
28
+ client_secret_env: SW_CONSOLE_SSO_SECRET # optional: a public client uses PKCE alone
29
+ session_secret_env: SW_CONSOLE_SESSION_SECRET # signs the sessions: at least 32 characters
30
+ session_ttl: 8h # how long a sign-in lasts (default 8h)
31
+ """
32
+
33
+ from dataclasses import dataclass, field
34
+ from typing import Any
35
+
36
+ from streamwright.core.config.inputs import InputError, parse_duration
37
+ from streamwright.core.http_service.config_files import DURATION_FIELD
38
+ from streamwright.core.http_service.state import STATE_CONNECTION_FIELD, STATE_HINTS, STATE_SCHEMA_FIELD, state_spec
39
+ from streamwright.core.jobs.fields import Field
40
+
41
+ __all__ = ["LOGIN_FIELD", "Login", "Sso", "login_of", "users_spec"]
42
+
43
+ MIN_SECRET = 32
44
+ _SESSION_SECONDS = (300, 7 * 86400) # 5 minutes to 7 days
45
+ LOGIN_FIELD = Field("object", fields={
46
+ "users": Field("object", fields={
47
+ "url": Field("string", description="a state database URL, as `state --url` takes one (a relative "
48
+ "sqlite:///PATH starts at console.yaml's folder); {{ secrets.NAME }} for "
49
+ "credentials (STREAMWRIGHT_SECRET_NAME)"),
50
+ "connection": STATE_CONNECTION_FIELD,
51
+ "schema": STATE_SCHEMA_FIELD,
52
+ }, hints=STATE_HINTS, description="console users: the console's own database (sw_console_users; `streamwright "
53
+ "console migrate` creates its tables, `console users add` adds them): url, or "
54
+ "connection and schema"),
55
+ "sso": Field("object", fields={
56
+ "label": Field("string", description="the button says \"Sign in with LABEL\" (default: SSO)"),
57
+ "issuer": Field("string", required=True, pattern=r"^https://",
58
+ description="the provider's issuer URL: its /.well-known/openid-configuration is read"),
59
+ "client_id": Field("string", required=True, description="the console's client id at the provider"),
60
+ "client_secret_env": Field("string", description="the variable holding its client secret (none: a public "
61
+ "client, PKCE alone)"),
62
+ }, description="single sign-on (OpenID Connect): the provider names the person (name, email, groups)"),
63
+ "session_secret_env": Field("string", required=True,
64
+ description="the variable holding the secret that signs the sessions (at least %d "
65
+ "characters; a new one signs everyone out)" % MIN_SECRET),
66
+ "session_ttl": Field("string", pattern=DURATION_FIELD.pattern, description="how long a sign-in lasts (default 8h; "
67
+ "5m to 7d)"),
68
+ }, description="people sign in on the console's login page: console users (a database) and/or single sign-on")
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class Sso:
73
+ label: str
74
+ issuer: str
75
+ client_id: str
76
+ client_secret: str | None = field(default=None, repr=False)
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class Login:
81
+ """How people sign in: console users (a StateSpec), SSO, and their sessions' secret and length."""
82
+ users: Any = field(default=None, repr=False) # a StateSpec: its URL may hold a password
83
+ sso: Sso | None = None
84
+ session_secret: str = field(default="", repr=False)
85
+ session_seconds: int = 8 * 3600
86
+ users_secrets: tuple = field(default=(), repr=False) # the secret values in `users`, masked in log lines
87
+
88
+
89
+ def users_spec(block, folder, environ, problems, env_problems, *, where="auth.login.users"):
90
+ """(the StateSpec of auth.login.users (`block`), the secret values put in it); its problems named by `where`."""
91
+ if ("url" in block) == ("connection" in block):
92
+ problems.append("%s: give exactly one of url or connection" % where)
93
+ return None, ()
94
+ if str(block.get("url", "")).startswith("duckdb:"):
95
+ problems.append("%s.url: a DuckDB file has one writer at a time (a job's): keep the users in SQLite or a "
96
+ "database server" % where)
97
+ return None, ()
98
+ found, missing, secrets = [], [], []
99
+ spec = state_spec(block, folder, environ, found, missing, queue=False, enrol=secrets.append)
100
+ problems.extend(problem.replace("state.", where + ".", 1) for problem in found)
101
+ env_problems.extend(problem.replace("state.", where + ".", 1) for problem in missing)
102
+ return spec, tuple(secrets)
103
+
104
+
105
+ def _session_seconds(login, problems):
106
+ try:
107
+ seconds = int(parse_duration(login.get("session_ttl", "8h")).total_seconds())
108
+ except InputError as exc:
109
+ problems.append("auth.login.session_ttl: %s" % exc)
110
+ return 8 * 3600
111
+ if not _SESSION_SECONDS[0] <= seconds <= _SESSION_SECONDS[1]:
112
+ problems.append("auth.login.session_ttl: from 5m to 7d")
113
+ return seconds
114
+
115
+
116
+ def login_of(login, folder, environ, problems, env_problems):
117
+ """The Login of an auth.login section (None without one); what the environment gives is checked into
118
+ `env_problems`."""
119
+ if login is None:
120
+ return None
121
+ if not login.get("users") and not login.get("sso"):
122
+ problems.append("auth.login: give users (console users) and/or sso (single sign-on)")
123
+ secret = environ.get(login["session_secret_env"]) or ""
124
+ if not secret:
125
+ env_problems.append("auth.login.session_secret_env: the environment variable %s is not set" %
126
+ login["session_secret_env"])
127
+ elif len(secret) < MIN_SECRET:
128
+ env_problems.append("auth.login.session_secret_env: %s has %d characters: at least %d (e.g. `openssl rand "
129
+ "-hex 32`)" % (login["session_secret_env"], len(secret), MIN_SECRET))
130
+ sso = login.get("sso")
131
+ client_secret = None
132
+ if sso and sso.get("client_secret_env"):
133
+ client_secret = environ.get(sso["client_secret_env"]) or None
134
+ if client_secret is None:
135
+ env_problems.append("auth.login.sso.client_secret_env: the environment variable %s is not set" %
136
+ sso["client_secret_env"])
137
+ users, secrets = users_spec(login["users"], folder, environ, problems, env_problems) if login.get("users") else (
138
+ None, ())
139
+ return Login(users=users, sso=Sso(sso.get("label") or "SSO", sso["issuer"], sso["client_id"], client_secret)
140
+ if sso else None, session_secret=secret, session_seconds=_session_seconds(login, problems),
141
+ users_secrets=secrets)
@@ -0,0 +1,32 @@
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
+ """console.yaml as `streamwright validate` and the MCP tools see it: its schema, guide and checks, as core's
18
+ ServiceConfig (the `streamwright.service_configs` entry point names CONSOLE)."""
19
+
20
+ from streamwright.core.service_configs import ServiceConfig
21
+
22
+ from streamwright.console.config.check import validate_console, validate_console_text
23
+ from streamwright.console.config.console import CONSOLE_FIELD, INCLUDED_FIELD, KIND
24
+
25
+ __all__ = ["CONSOLE"]
26
+
27
+ CONSOLE = ServiceConfig(
28
+ name=KIND, file="console.yaml", code="console-config",
29
+ title="console.yaml: the clients `streamwright console` shows, their state stores and who may pick each",
30
+ field=CONSOLE_FIELD, included=INCLUDED_FIELD,
31
+ check=lambda path, text: (validate_console(path, text), []), check_text=validate_console_text,
32
+ package="streamwright.console")
@@ -0,0 +1,18 @@
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
+ """The console's own database (auth.login.users): its tables, one module each (tables), its store and users (users),
18
+ and their migrations (migrations)."""
@@ -0,0 +1,40 @@
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
+ """Console migration 0001: sw_console_users and the ledger sw_console_migrations, with their comments."""
18
+
19
+ import uuid
20
+
21
+ from streamwright.core.jobs.state.migrations import ddl
22
+
23
+ from streamwright.console.db.tables import console_tables
24
+
25
+ VERSION = 1
26
+ NAME = "0001_console_users"
27
+ DESCRIPTION = "Create the console's tables (sw_console_users, sw_console_migrations)"
28
+ TABLE_ORDER = ("sw_console_migrations", "sw_console_users")
29
+
30
+
31
+ def get_statements(dialect_name, schema=None):
32
+ """The ordered DDL statements of this migration."""
33
+ tables = console_tables(schema)
34
+ return [statement for name in TABLE_ORDER for statement in ddl.create_statements(dialect_name, tables[name])]
35
+
36
+
37
+ def apply(conn, dialect, schema=None):
38
+ """Creates the tables; returns the database's identity (as the console's)."""
39
+ ddl.execute(conn, dialect, get_statements(dialect.name, schema=schema))
40
+ return str(uuid.uuid4())
@@ -0,0 +1,29 @@
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's migrations: modules NNNN_name.py, applied by core's migration runner as the job state's are, recorded
19
+ in sw_console_migrations. CONSOLE_TABLES is their family (its tables, its ledger, how a person applies them).
20
+ """
21
+
22
+ from streamwright.core.jobs.state.migrations import TableFamily
23
+
24
+ from streamwright.console.db.tables import console_tables
25
+
26
+ __all__ = ["CONSOLE_TABLES"]
27
+
28
+ CONSOLE_TABLES = TableFamily("console", __name__, console_tables, "sw_console_migrations",
29
+ "apply them with `streamwright console migrate --url URL`")
@@ -0,0 +1,34 @@
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's own tables, one module each (as core's state tables): sw_console_users (users) and the ledger
19
+ sw_console_migrations (migrations). They live in the database console.yaml's auth.login.users names, apart from the
20
+ clients' job state.
21
+ """
22
+
23
+ from streamwright.core.jobs.state.tables import tables_of
24
+
25
+ from streamwright.console.db.tables.base import metadata
26
+ from streamwright.console.db.tables.migrations import sw_console_migrations
27
+ from streamwright.console.db.tables.users import sw_console_users
28
+
29
+ __all__ = ["console_tables", "metadata", "sw_console_migrations", "sw_console_users"]
30
+
31
+
32
+ def console_tables(schema=None):
33
+ """The console's tables by name, bound to the optional schema."""
34
+ return tables_of(metadata, schema)
@@ -0,0 +1,24 @@
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
+ """The MetaData the console's tables share, with core's naming of constraints and indexes."""
18
+
19
+ from sqlalchemy import MetaData
20
+ from streamwright.core.jobs.state.tables import NAMING_CONVENTION
21
+
22
+ __all__ = ["metadata"]
23
+
24
+ metadata = MetaData(naming_convention=dict(NAMING_CONVENTION))
@@ -0,0 +1,27 @@
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
+ """Table sw_console_migrations: the console's migrations applied to its database, and the database's identity (core's
18
+ ledger of a family of tables, as sw_migrations is the job state's)."""
19
+
20
+ from streamwright.core.jobs.state.tables import ledger_table
21
+
22
+ from streamwright.console.db.tables.base import metadata
23
+
24
+ __all__ = ["sw_console_migrations"]
25
+
26
+ sw_console_migrations = ledger_table("sw_console_migrations", metadata,
27
+ "The console's migrations applied to this database, and its identity.")