inferyx-codegate 1.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.
Files changed (74) hide show
  1. codegate/__init__.py +8 -0
  2. codegate/__main__.py +3 -0
  3. codegate/api/__init__.py +0 -0
  4. codegate/api/admin.py +457 -0
  5. codegate/api/deps.py +36 -0
  6. codegate/api/devproxy.py +132 -0
  7. codegate/api/public.py +371 -0
  8. codegate/app.py +115 -0
  9. codegate/auth/__init__.py +0 -0
  10. codegate/auth/csrf.py +43 -0
  11. codegate/auth/native.py +111 -0
  12. codegate/auth/passwords.py +88 -0
  13. codegate/auth/saml.py +222 -0
  14. codegate/auth/sessions.py +121 -0
  15. codegate/cli/__init__.py +0 -0
  16. codegate/cli/auth_cmd.py +168 -0
  17. codegate/cli/backup_cmd.py +114 -0
  18. codegate/cli/common.py +103 -0
  19. codegate/cli/doctor_cmd.py +136 -0
  20. codegate/cli/main.py +526 -0
  21. codegate/cli/nginx_setup.py +220 -0
  22. codegate/cli/setup_cmd.py +401 -0
  23. codegate/cli/ssh_setup.py +114 -0
  24. codegate/cli/upgrade_cmd.py +209 -0
  25. codegate/config.py +161 -0
  26. codegate/db.py +297 -0
  27. codegate/errors.py +122 -0
  28. codegate/jobs.py +133 -0
  29. codegate/pages.py +177 -0
  30. codegate/resources/__init__.py +20 -0
  31. codegate/resources/docker/Dockerfile +36 -0
  32. codegate/resources/nginx/codegate.conf.tmpl +51 -0
  33. codegate/resources/nginx/map.conf +5 -0
  34. codegate/resources/nginx/site.conf.tmpl +9 -0
  35. codegate/resources/nginx/user.conf.tmpl +19 -0
  36. codegate/resources/systemd/codegate-backup.service.tmpl +7 -0
  37. codegate/resources/systemd/codegate-backup.timer +10 -0
  38. codegate/resources/systemd/codegate.service.tmpl +20 -0
  39. codegate/static/admin/3rdpartylicenses.txt +614 -0
  40. codegate/static/admin/chunk-0r_p7pcB.js +672 -0
  41. codegate/static/admin/chunk-BoGqYCjO.js +1260 -0
  42. codegate/static/admin/chunk-BqiJ460N.js +1269 -0
  43. codegate/static/admin/chunk-BtoaIoDj.js +449 -0
  44. codegate/static/admin/chunk-CB4E-q63.js +255 -0
  45. codegate/static/admin/chunk-CMN75K3s.js +181 -0
  46. codegate/static/admin/chunk-CW_CPa20.js +106 -0
  47. codegate/static/admin/chunk-CcgsCK7w.js +393 -0
  48. codegate/static/admin/chunk-Cjwyuum6.js +375 -0
  49. codegate/static/admin/chunk-D6j6hnz3.js +1 -0
  50. codegate/static/admin/chunk-D9RytJgO.js +1 -0
  51. codegate/static/admin/chunk-DA6TldFU.js +35 -0
  52. codegate/static/admin/chunk-DFGdyoNb.js +1 -0
  53. codegate/static/admin/chunk-DXvCZ3pT.js +1 -0
  54. codegate/static/admin/chunk-DstgVdtz.js +27 -0
  55. codegate/static/admin/chunk-kPDFCwHP.js +102 -0
  56. codegate/static/admin/chunk-yikJ2ObQ.js +1 -0
  57. codegate/static/admin/favicon.ico +0 -0
  58. codegate/static/admin/index.html +14 -0
  59. codegate/static/admin/main-LWBML7JF.js +2347 -0
  60. codegate/static/admin/media/material-icons-JLIDJUWE.woff +0 -0
  61. codegate/static/admin/media/material-icons-LEZCGFVT.woff2 +0 -0
  62. codegate/static/admin/styles-YWRWGLKG.css +1 -0
  63. codegate/system/__init__.py +27 -0
  64. codegate/system/base.py +165 -0
  65. codegate/system/devdocker.py +90 -0
  66. codegate/system/fake.py +199 -0
  67. codegate/system/real.py +493 -0
  68. codegate/system/shell.py +40 -0
  69. codegate/users.py +262 -0
  70. codegate/workspace.py +355 -0
  71. inferyx_codegate-1.1.0.dist-info/METADATA +217 -0
  72. inferyx_codegate-1.1.0.dist-info/RECORD +74 -0
  73. inferyx_codegate-1.1.0.dist-info/WHEEL +4 -0
  74. inferyx_codegate-1.1.0.dist-info/entry_points.txt +2 -0
codegate/db.py ADDED
@@ -0,0 +1,297 @@
1
+ """Database (SQLite via SQLAlchemy 2.0) and versioned migrations."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import logging
6
+ from contextlib import contextmanager
7
+ from datetime import datetime, timezone
8
+ from typing import Any, Iterator
9
+
10
+ from sqlalchemy import (Boolean, DateTime, Float, ForeignKey, Integer, String, Text, create_engine,
11
+ event, select, text)
12
+ from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker
13
+
14
+ from .config import get_settings
15
+
16
+ log = logging.getLogger("codegate.db")
17
+
18
+
19
+ def utcnow() -> datetime:
20
+ return datetime.now(timezone.utc).replace(tzinfo=None)
21
+
22
+
23
+ class Base(DeclarativeBase):
24
+ pass
25
+
26
+
27
+ class User(Base):
28
+ __tablename__ = "users"
29
+
30
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
31
+ email: Mapped[str] = mapped_column(String(320), unique=True, index=True)
32
+ username: Mapped[str] = mapped_column(String(32), unique=True, index=True)
33
+ display_name: Mapped[str] = mapped_column(String(200), default="")
34
+ uid: Mapped[int | None] = mapped_column(Integer, nullable=True)
35
+ gid: Mapped[int | None] = mapped_column(Integer, nullable=True)
36
+ # pending | active | disabled
37
+ status: Mapped[str] = mapped_column(String(16), default="pending", index=True)
38
+ is_admin: Mapped[bool] = mapped_column(Boolean, default=False)
39
+ has_workspace: Mapped[bool] = mapped_column(Boolean, default=True)
40
+ # resources
41
+ plan: Mapped[str] = mapped_column(String(32), default="small")
42
+ cpu: Mapped[float] = mapped_column(Float, default=1.0)
43
+ mem_mb: Mapped[int] = mapped_column(Integer, default=2048)
44
+ disk_gb: Mapped[int] = mapped_column(Integer, default=10)
45
+ pids: Mapped[int] = mapped_column(Integer, default=512)
46
+ # permissions
47
+ sudo: Mapped[bool] = mapped_column(Boolean, default=False)
48
+ internet: Mapped[bool] = mapped_column(Boolean, default=True)
49
+ shared_folder: Mapped[bool] = mapped_column(Boolean, default=False)
50
+ image: Mapped[str] = mapped_column(String(200), default="")
51
+ expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
52
+ # runtime
53
+ port: Mapped[int | None] = mapped_column(Integer, nullable=True, unique=True)
54
+ container_id: Mapped[str | None] = mapped_column(String(80), nullable=True)
55
+ provisioned: Mapped[bool] = mapped_column(Boolean, default=False)
56
+ linked_existing: Mapped[bool] = mapped_column(Boolean, default=False)
57
+ over_quota: Mapped[bool] = mapped_column(Boolean, default=False)
58
+ # bookkeeping
59
+ created_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow)
60
+ approved_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
61
+ approved_by: Mapped[str | None] = mapped_column(String(320), nullable=True)
62
+ last_login: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
63
+ notes: Mapped[str] = mapped_column(Text, default="")
64
+ # native (password) login - only a salted scrypt hash is stored, never the password
65
+ password_hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
66
+ must_change_password: Mapped[bool] = mapped_column(Boolean, default=False)
67
+ password_changed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
68
+ failed_logins: Mapped[int] = mapped_column(Integer, default=0)
69
+ locked_until: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
70
+
71
+
72
+ class LoginSession(Base):
73
+ __tablename__ = "sessions"
74
+
75
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
76
+ token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
77
+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
78
+ ip: Mapped[str] = mapped_column(String(64), default="")
79
+ user_agent: Mapped[str] = mapped_column(String(300), default="")
80
+ auth_method: Mapped[str] = mapped_column(String(16), default="sso") # sso | password
81
+ created_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow)
82
+ last_seen: Mapped[datetime] = mapped_column(DateTime, default=utcnow)
83
+ expires_at: Mapped[datetime] = mapped_column(DateTime)
84
+
85
+
86
+ class AuditLog(Base):
87
+ __tablename__ = "audit"
88
+
89
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
90
+ ts: Mapped[datetime] = mapped_column(DateTime, default=utcnow, index=True)
91
+ actor: Mapped[str] = mapped_column(String(320), default="system")
92
+ action: Mapped[str] = mapped_column(String(64), index=True)
93
+ target: Mapped[str] = mapped_column(String(320), default="")
94
+ ip: Mapped[str] = mapped_column(String(64), default="")
95
+ success: Mapped[bool] = mapped_column(Boolean, default=True)
96
+ details: Mapped[str] = mapped_column(Text, default="{}")
97
+
98
+
99
+ class Setting(Base):
100
+ __tablename__ = "settings"
101
+
102
+ key: Mapped[str] = mapped_column(String(64), primary_key=True)
103
+ value: Mapped[str] = mapped_column(Text)
104
+
105
+
106
+ class SamlReplay(Base):
107
+ __tablename__ = "saml_replay"
108
+
109
+ assertion_id: Mapped[str] = mapped_column(String(200), primary_key=True)
110
+ expires_at: Mapped[datetime] = mapped_column(DateTime)
111
+
112
+
113
+ class Usage(Base):
114
+ __tablename__ = "usage"
115
+
116
+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"),
117
+ primary_key=True)
118
+ running: Mapped[bool] = mapped_column(Boolean, default=False)
119
+ cpu_pct: Mapped[float] = mapped_column(Float, default=0.0)
120
+ mem_mb: Mapped[float] = mapped_column(Float, default=0.0)
121
+ disk_mb: Mapped[float] = mapped_column(Float, default=0.0)
122
+ last_active: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
123
+ updated_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow)
124
+
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # default settings stored in DB (editable from admin portal)
128
+ DEFAULT_SETTINGS: dict[str, Any] = {
129
+ "plans": {
130
+ "small": {"cpu": 1, "mem_mb": 2048, "disk_gb": 10, "pids": 512},
131
+ "medium": {"cpu": 2, "mem_mb": 4096, "disk_gb": 20, "pids": 1024},
132
+ "large": {"cpu": 4, "mem_mb": 8192, "disk_gb": 50, "pids": 2048},
133
+ },
134
+ "default_plan": "small",
135
+ "idle_timeout_minutes": 60,
136
+ "session_hours": 8,
137
+ "idle_session_minutes": 60,
138
+ "auto_approve_domains": [],
139
+ "default_internet": True,
140
+ "backup_keep_days": 7,
141
+ "disk_warning_pct": 90,
142
+ # authentication (editable in admin portal -> Settings -> Login)
143
+ "password_login_enabled": True,
144
+ "sso_enabled": False,
145
+ "saml_idp_metadata_url": "",
146
+ "saml_email_attribute": "email",
147
+ "password_min_length": 12,
148
+ "max_failed_logins": 5,
149
+ "lockout_minutes": 15,
150
+ }
151
+
152
+ # ---------------------------------------------------------------------------
153
+ # migrations: list of (version, [sql...]). Version 1 = create_all.
154
+ MIGRATIONS: list[tuple[int, list[str]]] = [
155
+ (1, []), # initial schema created by metadata.create_all
156
+ (2, [ # native login
157
+ "ALTER TABLE users ADD COLUMN password_hash VARCHAR(255)",
158
+ "ALTER TABLE users ADD COLUMN must_change_password BOOLEAN NOT NULL DEFAULT 0",
159
+ "ALTER TABLE users ADD COLUMN password_changed_at DATETIME",
160
+ "ALTER TABLE users ADD COLUMN failed_logins INTEGER NOT NULL DEFAULT 0",
161
+ "ALTER TABLE users ADD COLUMN locked_until DATETIME",
162
+ "ALTER TABLE sessions ADD COLUMN auth_method VARCHAR(16) NOT NULL DEFAULT 'sso'",
163
+ ]),
164
+ ]
165
+ SCHEMA_VERSION = MIGRATIONS[-1][0]
166
+
167
+ _engine = None
168
+ _SessionLocal: sessionmaker | None = None
169
+
170
+
171
+ def _sqlite_pragmas(dbapi_conn, _):
172
+ cur = dbapi_conn.cursor()
173
+ cur.execute("PRAGMA journal_mode=WAL")
174
+ cur.execute("PRAGMA foreign_keys=ON")
175
+ cur.execute("PRAGMA busy_timeout=15000")
176
+ cur.close()
177
+
178
+
179
+ def get_engine():
180
+ global _engine, _SessionLocal
181
+ if _engine is None:
182
+ s = get_settings()
183
+ s.data_dir.mkdir(parents=True, exist_ok=True)
184
+ _engine = create_engine(f"sqlite:///{s.db_path}", connect_args={"check_same_thread": False})
185
+ event.listen(_engine, "connect", _sqlite_pragmas)
186
+ _SessionLocal = sessionmaker(bind=_engine, expire_on_commit=False)
187
+ return _engine
188
+
189
+
190
+ def reset_engine() -> None:
191
+ global _engine, _SessionLocal
192
+ if _engine is not None:
193
+ _engine.dispose()
194
+ _engine = None
195
+ _SessionLocal = None
196
+
197
+
198
+ @contextmanager
199
+ def session_scope() -> Iterator[Session]:
200
+ get_engine()
201
+ assert _SessionLocal is not None
202
+ db = _SessionLocal()
203
+ try:
204
+ yield db
205
+ db.commit()
206
+ except Exception:
207
+ db.rollback()
208
+ raise
209
+ finally:
210
+ db.close()
211
+
212
+
213
+ def get_db() -> Iterator[Session]:
214
+ """FastAPI dependency."""
215
+ with session_scope() as db:
216
+ yield db
217
+
218
+
219
+ def current_schema_version() -> int:
220
+ eng = get_engine()
221
+ with eng.begin() as conn:
222
+ conn.execute(text("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"))
223
+ row = conn.execute(text("SELECT version FROM schema_version")).first()
224
+ return int(row[0]) if row else 0
225
+
226
+
227
+ def migrate() -> tuple[int, int]:
228
+ """Create / upgrade schema. Returns (old_version, new_version). Safe to run repeatedly."""
229
+ eng = get_engine()
230
+ old = current_schema_version()
231
+ Base.metadata.create_all(eng)
232
+ with eng.begin() as conn:
233
+ for version, stmts in MIGRATIONS:
234
+ # fresh DB (old == 0): create_all already built the latest schema
235
+ if version <= old or old == 0:
236
+ continue
237
+ for sql in stmts:
238
+ log.info("migration v%s: %s", version, sql)
239
+ conn.execute(text(sql))
240
+ conn.execute(text("DELETE FROM schema_version"))
241
+ conn.execute(text("INSERT INTO schema_version (version) VALUES (:v)"), {"v": SCHEMA_VERSION})
242
+ s = get_settings()
243
+ # installs that configured SSO in the env file keep it working after the upgrade
244
+ first_values = dict(DEFAULT_SETTINGS)
245
+ if s.saml_idp_metadata_url or s.saml_idp_metadata_file:
246
+ first_values.update(sso_enabled=True, saml_idp_metadata_url=s.saml_idp_metadata_url)
247
+ if s.saml_email_attribute:
248
+ first_values["saml_email_attribute"] = s.saml_email_attribute
249
+ with session_scope() as db:
250
+ for key, value in first_values.items():
251
+ if db.get(Setting, key) is None:
252
+ db.add(Setting(key=key, value=json.dumps(value)))
253
+ return old, SCHEMA_VERSION
254
+
255
+
256
+ # ---------------------------------------------------------------------------
257
+ def get_setting(db: Session, key: str) -> Any:
258
+ row = db.get(Setting, key)
259
+ if row is None:
260
+ return DEFAULT_SETTINGS.get(key)
261
+ return json.loads(row.value)
262
+
263
+
264
+ def all_settings(db: Session) -> dict[str, Any]:
265
+ out = dict(DEFAULT_SETTINGS)
266
+ for row in db.scalars(select(Setting)):
267
+ out[row.key] = json.loads(row.value)
268
+ return out
269
+
270
+
271
+ def set_setting(db: Session, key: str, value: Any) -> None:
272
+ row = db.get(Setting, key)
273
+ if row is None:
274
+ db.add(Setting(key=key, value=json.dumps(value)))
275
+ else:
276
+ row.value = json.dumps(value)
277
+
278
+
279
+ def audit(db: Session, action: str, *, actor: str = "system", target: str = "", ip: str = "",
280
+ success: bool = True, **details: Any) -> None:
281
+ db.add(AuditLog(actor=actor, action=action, target=target, ip=ip, success=success,
282
+ details=json.dumps(details, default=str)))
283
+
284
+
285
+ def audit_now(action: str, **kw: Any) -> None:
286
+ """Write an audit entry in its own transaction so it survives a rollback of the
287
+ caller. Runs in a thread: it waits for the caller's write lock to be released."""
288
+ import threading
289
+
290
+ def _write():
291
+ try:
292
+ with session_scope() as db:
293
+ audit(db, action, **kw)
294
+ except Exception: # never let audit failures hide the real error
295
+ log.exception("could not write audit entry %s", action)
296
+
297
+ threading.Thread(target=_write, name="audit-writer", daemon=True).start()
codegate/errors.py ADDED
@@ -0,0 +1,122 @@
1
+ """Application errors and FastAPI exception handlers.
2
+
3
+ Every API error is returned as ``{"code": str, "message": str, "details": {}}``.
4
+ Unexpected errors are logged with an error id; users only see the id.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import uuid
10
+ from typing import Any
11
+
12
+ from fastapi import FastAPI, Request
13
+ from fastapi.exceptions import RequestValidationError
14
+ from fastapi.responses import JSONResponse
15
+ from starlette.exceptions import HTTPException as StarletteHTTPException
16
+
17
+ log = logging.getLogger("codegate.errors")
18
+
19
+
20
+ class AppError(Exception):
21
+ status_code = 400
22
+ code = "bad_request"
23
+
24
+ def __init__(self, message: str, *, code: str | None = None, status_code: int | None = None,
25
+ details: dict[str, Any] | None = None) -> None:
26
+ super().__init__(message)
27
+ self.message = message
28
+ if code:
29
+ self.code = code
30
+ if status_code:
31
+ self.status_code = status_code
32
+ self.details = details or {}
33
+
34
+
35
+ class NotFound(AppError):
36
+ status_code = 404
37
+ code = "not_found"
38
+
39
+
40
+ class Conflict(AppError):
41
+ status_code = 409
42
+ code = "conflict"
43
+
44
+
45
+ class Unauthorized(AppError):
46
+ status_code = 401
47
+ code = "unauthorized"
48
+
49
+
50
+ class Forbidden(AppError):
51
+ status_code = 403
52
+ code = "forbidden"
53
+
54
+
55
+ class ValidationFailed(AppError):
56
+ status_code = 422
57
+ code = "validation_failed"
58
+
59
+
60
+ class SystemCommandError(AppError):
61
+ """A shell / system command failed (useradd, nginx -t, setquota ...)."""
62
+ status_code = 500
63
+ code = "system_command_failed"
64
+
65
+
66
+ class DockerError(AppError):
67
+ status_code = 502
68
+ code = "docker_error"
69
+
70
+
71
+ class NginxError(AppError):
72
+ status_code = 500
73
+ code = "nginx_error"
74
+
75
+
76
+ class SSOError(AppError):
77
+ status_code = 400
78
+ code = "sso_error"
79
+
80
+
81
+ class ProvisionError(AppError):
82
+ """Provisioning failed; all completed steps were rolled back."""
83
+ status_code = 500
84
+ code = "provision_failed"
85
+
86
+
87
+ def _body(code: str, message: str, details: dict[str, Any] | None = None) -> dict[str, Any]:
88
+ return {"code": code, "message": message, "details": details or {}}
89
+
90
+
91
+ def install_handlers(app: FastAPI) -> None:
92
+ @app.exception_handler(AppError)
93
+ async def _app_error(request: Request, exc: AppError):
94
+ level = logging.ERROR if exc.status_code >= 500 else logging.INFO
95
+ log.log(level, "%s %s -> %s: %s %s", request.method, request.url.path, exc.code,
96
+ exc.message, exc.details)
97
+ return JSONResponse(_body(exc.code, exc.message, exc.details), status_code=exc.status_code)
98
+
99
+ @app.exception_handler(RequestValidationError)
100
+ async def _validation(request: Request, exc: RequestValidationError):
101
+ errors = [
102
+ {"field": ".".join(str(p) for p in e.get("loc", [])[1:]), "message": e.get("msg")}
103
+ for e in exc.errors()
104
+ ]
105
+ return JSONResponse(_body("validation_failed", "Invalid input", {"errors": errors}),
106
+ status_code=422)
107
+
108
+ @app.exception_handler(StarletteHTTPException)
109
+ async def _http(request: Request, exc: StarletteHTTPException):
110
+ code = {404: "not_found", 405: "method_not_allowed", 401: "unauthorized",
111
+ 403: "forbidden"}.get(exc.status_code, "http_error")
112
+ return JSONResponse(_body(code, str(exc.detail)), status_code=exc.status_code)
113
+
114
+ @app.exception_handler(Exception)
115
+ async def _unhandled(request: Request, exc: Exception):
116
+ error_id = uuid.uuid4().hex[:12]
117
+ log.exception("Unhandled error %s on %s %s", error_id, request.method, request.url.path)
118
+ return JSONResponse(
119
+ _body("internal_error", "Something went wrong. Contact the admin with this error id.",
120
+ {"error_id": error_id}),
121
+ status_code=500,
122
+ )
codegate/jobs.py ADDED
@@ -0,0 +1,133 @@
1
+ """Background jobs: idle shutdown, access expiry, session cleanup, usage + disk limits."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import logging
6
+ from datetime import timedelta
7
+
8
+ from sqlalchemy import delete, select
9
+
10
+ from .auth.sessions import end_user_sessions, purge_expired, touch_user_sessions
11
+ from .config import get_settings
12
+ from .db import SamlReplay, Usage, User, audit, get_setting, session_scope, utcnow
13
+ from .system import get_system
14
+ from .workspace import home_of
15
+
16
+ log = logging.getLogger("codegate.jobs")
17
+
18
+
19
+ def reap_once() -> dict:
20
+ """Idle shutdown + expiry + session purge. Safe to call any time."""
21
+ system = get_system()
22
+ stats = {"stopped_idle": [], "expired": [], "sessions_purged": 0}
23
+ with session_scope() as db:
24
+ idle_min = int(get_setting(db, "idle_timeout_minutes") or 0)
25
+ now = utcnow()
26
+ users = list(db.scalars(select(User).where(User.provisioned.is_(True))))
27
+ for u in users:
28
+ try:
29
+ # access expiry
30
+ if u.expires_at and u.expires_at <= now and u.status == "active":
31
+ u.status = "disabled"
32
+ end_user_sessions(db, u.id)
33
+ system.container_stop(u.username)
34
+ audit(db, "user.expired", target=u.email)
35
+ stats["expired"].append(u.username)
36
+ continue
37
+ usage = db.get(Usage, u.id) or Usage(user_id=u.id)
38
+ if usage not in db:
39
+ db.add(usage)
40
+ running = system.container_status(u.username) == "running"
41
+ usage.running = running
42
+ if not running:
43
+ continue
44
+ hb = system.heartbeat(home_of(u))
45
+ if hb and (usage.last_active is None or hb > usage.last_active):
46
+ usage.last_active = hb
47
+ touch_user_sessions(db, u.id)
48
+ last = usage.last_active
49
+ if idle_min > 0 and last and last + timedelta(minutes=idle_min) < now:
50
+ system.container_stop(u.username)
51
+ usage.running = False
52
+ audit(db, "workspace.idle_stop", target=u.email, idle_minutes=idle_min)
53
+ stats["stopped_idle"].append(u.username)
54
+ elif last is None:
55
+ usage.last_active = now # first sighting; start the idle clock
56
+ except Exception:
57
+ log.exception("reaper failed for %s", u.username)
58
+ stats["sessions_purged"] = purge_expired(db)
59
+ db.execute(delete(SamlReplay).where(SamlReplay.expires_at <= now))
60
+ return stats
61
+
62
+
63
+ def collect_usage_once() -> None:
64
+ """Refresh CPU/RAM/disk numbers; enforce disk limit when quotas are unavailable."""
65
+ system = get_system()
66
+ with session_scope() as db:
67
+ quota_on = system.quota_supported()
68
+ warn_pct = int(get_setting(db, "disk_warning_pct") or 90)
69
+ for u in db.scalars(select(User).where(User.provisioned.is_(True))):
70
+ try:
71
+ st = system.container_stats(u.username)
72
+ usage = db.get(Usage, u.id)
73
+ if usage is None:
74
+ usage = Usage(user_id=u.id)
75
+ db.add(usage)
76
+ usage.running = st.running
77
+ usage.cpu_pct = st.cpu_pct
78
+ usage.mem_mb = st.mem_mb
79
+ usage.disk_mb = round(system.home_usage_mb(home_of(u)), 1)
80
+ usage.updated_at = utcnow()
81
+ limit_mb = u.disk_gb * 1024
82
+ pct = usage.disk_mb / limit_mb * 100 if limit_mb else 0
83
+ over = pct >= 100
84
+ if over != u.over_quota:
85
+ u.over_quota = over
86
+ audit(db, "workspace.disk_limit", target=u.email, over=over,
87
+ used_mb=usage.disk_mb, limit_mb=limit_mb, enforced_by_quota=quota_on)
88
+ if over and not quota_on:
89
+ # soft enforcement: stop workspace; it can't start until space is freed
90
+ system.container_stop(u.username)
91
+ elif pct >= warn_pct and not over:
92
+ log.warning("user %s at %.0f%% of disk limit", u.username, pct)
93
+ except Exception:
94
+ log.exception("usage collection failed for %s", u.username)
95
+ _strip_setuid(db, system)
96
+
97
+
98
+ def _strip_setuid(db, system) -> None:
99
+ """sudo users are root in their container; don't let them leave setuid files behind."""
100
+ s = get_settings()
101
+ sudo_users = list(db.scalars(select(User).where(User.provisioned.is_(True),
102
+ User.sudo.is_(True))))
103
+ targets = [(u.email, home_of(u)) for u in sudo_users]
104
+ if any(u.shared_folder for u in sudo_users):
105
+ targets.append(("shared", s.shared_dir))
106
+ for who, path in targets:
107
+ try:
108
+ changed = system.strip_setuid(path)
109
+ except Exception:
110
+ log.exception("setuid scan failed for %s", path)
111
+ continue
112
+ if changed:
113
+ log.warning("removed setuid/setgid bits from %d file(s) in %s", len(changed), path)
114
+ audit(db, "workspace.setuid_removed", target=who, path=str(path),
115
+ files=changed[:50], count=len(changed))
116
+
117
+
118
+ async def run_background_jobs(stop: asyncio.Event) -> None:
119
+ s = get_settings()
120
+ last_usage = 0.0
121
+ loop = asyncio.get_running_loop()
122
+ while not stop.is_set():
123
+ try:
124
+ await asyncio.to_thread(reap_once)
125
+ if loop.time() - last_usage >= s.usage_interval_seconds:
126
+ await asyncio.to_thread(collect_usage_once)
127
+ last_usage = loop.time()
128
+ except Exception:
129
+ log.exception("background job error")
130
+ try:
131
+ await asyncio.wait_for(stop.wait(), timeout=s.reaper_interval_seconds)
132
+ except asyncio.TimeoutError:
133
+ pass