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/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """CodeGate - browser VS Code with AWS SSO login and per-user Docker workspaces."""
2
+
3
+ __version__ = "1.1.0"
4
+
5
+ # pip distribution name (PyPI). The import package and the CLI command stay "codegate".
6
+ PACKAGE_NAME = "inferyx-codegate"
7
+ # earlier builds were installed from .whl files under this name
8
+ LEGACY_PACKAGE_NAMES = ("codegate",)
codegate/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli.main import app
2
+
3
+ app()
File without changes
codegate/api/admin.py ADDED
@@ -0,0 +1,457 @@
1
+ """Admin API (/api/admin/*). Admin role only; mutating calls need X-CodeGate: 1."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from datetime import datetime
6
+ from typing import Any, Literal
7
+
8
+ from fastapi import APIRouter, Depends, Query, Request
9
+ from pydantic import BaseModel, Field
10
+ from sqlalchemy import func, or_, select
11
+ from sqlalchemy.orm import Session
12
+
13
+ from .. import __version__, users, workspace
14
+ from ..auth import native, saml
15
+ from ..auth.sessions import client_ip, end_method_sessions, end_user_sessions, resolve_session
16
+ from ..config import get_settings
17
+ from ..db import (AuditLog, LoginSession, Usage, User, all_settings, audit, get_db, set_setting,
18
+ utcnow)
19
+ from ..errors import NotFound, ValidationFailed
20
+ from ..system import get_system
21
+ from .deps import admin_user
22
+
23
+ router = APIRouter(prefix="/api/admin", dependencies=[Depends(admin_user)])
24
+
25
+
26
+ # --------------------------------------------------------------- models
27
+ class UserCreate(BaseModel):
28
+ email: str
29
+ password: str | None = Field(None, max_length=256)
30
+ must_change_password: bool = True
31
+ username: str | None = None
32
+ display_name: str = ""
33
+ plan: str | None = None
34
+ is_admin: bool = False
35
+ has_workspace: bool = True
36
+ cpu: float | None = None
37
+ mem_mb: int | None = None
38
+ disk_gb: int | None = None
39
+ pids: int | None = None
40
+ sudo: bool = False
41
+ internet: bool | None = None
42
+ shared_folder: bool = False
43
+ image: str = ""
44
+ expires_at: datetime | None = None
45
+ notes: str = ""
46
+
47
+
48
+ class UserUpdate(BaseModel):
49
+ display_name: str | None = None
50
+ is_admin: bool | None = None
51
+ has_workspace: bool | None = None
52
+ plan: str | None = None
53
+ cpu: float | None = None
54
+ mem_mb: int | None = None
55
+ disk_gb: int | None = None
56
+ pids: int | None = None
57
+ sudo: bool | None = None
58
+ internet: bool | None = None
59
+ shared_folder: bool | None = None
60
+ image: str | None = None
61
+ expires_at: datetime | None = None
62
+ clear_expiry: bool = False
63
+ notes: str | None = None
64
+
65
+
66
+ class ApproveBody(BaseModel):
67
+ plan: str | None = None
68
+
69
+
70
+ class PasswordBody(BaseModel):
71
+ password: str = Field(..., max_length=256)
72
+ must_change_password: bool = True
73
+
74
+
75
+ class SsoTestBody(BaseModel):
76
+ metadata_url: str | None = Field(None, max_length=2000)
77
+
78
+
79
+ class SettingsBody(BaseModel):
80
+ plans: dict[str, dict[str, float]] | None = None
81
+ default_plan: str | None = None
82
+ idle_timeout_minutes: int | None = Field(None, ge=0, le=10080)
83
+ session_hours: int | None = Field(None, ge=1, le=720)
84
+ idle_session_minutes: int | None = Field(None, ge=0, le=10080)
85
+ auto_approve_domains: list[str] | None = None
86
+ default_internet: bool | None = None
87
+ backup_keep_days: int | None = Field(None, ge=1, le=365)
88
+ disk_warning_pct: int | None = Field(None, ge=50, le=99)
89
+ # login
90
+ password_login_enabled: bool | None = None
91
+ sso_enabled: bool | None = None
92
+ saml_idp_metadata_url: str | None = Field(None, max_length=2000)
93
+ saml_email_attribute: str | None = Field(None, min_length=1, max_length=200)
94
+ password_min_length: int | None = Field(None, ge=10, le=128)
95
+ max_failed_logins: int | None = Field(None, ge=3, le=50)
96
+ lockout_minutes: int | None = Field(None, ge=1, le=1440)
97
+
98
+
99
+ def _actor(admin: User) -> str:
100
+ return admin.email
101
+
102
+
103
+ def _with_usage(db: Session, u: User) -> dict[str, Any]:
104
+ return users.user_dict(u, db.get(Usage, u.id))
105
+
106
+
107
+ # --------------------------------------------------------------- dashboard
108
+ @router.get("/stats")
109
+ def stats(db: Session = Depends(get_db)):
110
+ counts = dict(db.execute(select(User.status, func.count()).group_by(User.status)).all())
111
+ running = db.scalar(select(func.count()).select_from(Usage).where(Usage.running.is_(True)))
112
+ sessions = db.scalar(select(func.count()).select_from(LoginSession))
113
+ allocated = db.execute(select(func.sum(User.cpu), func.sum(User.mem_mb), func.sum(User.disk_gb))
114
+ .where(User.provisioned.is_(True))).one()
115
+ return {
116
+ "users": {"total": sum(counts.values()), **{k: counts.get(k, 0) for k in
117
+ ("active", "pending", "disabled")}},
118
+ "workspaces_running": running or 0,
119
+ "active_sessions": sessions or 0,
120
+ "allocated": {"cpu": allocated[0] or 0, "mem_mb": allocated[1] or 0,
121
+ "disk_gb": allocated[2] or 0},
122
+ "host": get_system().host_stats(),
123
+ "recent": [_audit_dict(a) for a in db.scalars(
124
+ select(AuditLog).order_by(AuditLog.id.desc()).limit(8))],
125
+ }
126
+
127
+
128
+ @router.get("/system")
129
+ def system_info(db: Session = Depends(get_db)):
130
+ s = get_settings()
131
+ system = get_system()
132
+ return {
133
+ "version": __version__, "mode": system.name, "domain": s.domain, "base_path": s.base_path,
134
+ "public_url": s.public_url, "acs_url": s.acs_url, "sp_entity_id": s.sp_entity_id,
135
+ "saml_installed": saml.saml_available(),
136
+ "saml_configured": saml.sso_configured(db), "sso_active": saml.sso_active(db),
137
+ "sp_metadata_url": f"{s.public_url}/saml/metadata",
138
+ "docker_ok": system.docker_ok(), "quota_enabled": system.quota_supported(),
139
+ "workspace_image": s.workspace_image,
140
+ }
141
+
142
+
143
+ # --------------------------------------------------------------- users
144
+ @router.get("/users")
145
+ def list_users(status: Literal["pending", "active", "disabled"] | None = None,
146
+ q: str | None = None, db: Session = Depends(get_db)):
147
+ stmt = select(User).order_by(User.created_at.desc())
148
+ if status:
149
+ stmt = stmt.where(User.status == status)
150
+ if q:
151
+ like = f"%{q.lower()}%"
152
+ stmt = stmt.where(or_(User.email.like(like), User.username.like(like),
153
+ User.display_name.like(like)))
154
+ return [_with_usage(db, u) for u in db.scalars(stmt)]
155
+
156
+
157
+ @router.post("/users", status_code=201)
158
+ def create_user(body: UserCreate, admin: User = Depends(admin_user), db: Session = Depends(get_db)):
159
+ data = body.model_dump()
160
+ if data.get("password") is None:
161
+ data.pop("password")
162
+ opts = {k: data.pop(k) for k in ("cpu", "mem_mb", "disk_gb", "pids", "sudo", "internet",
163
+ "shared_folder", "image", "expires_at", "notes")}
164
+ opts = {k: v for k, v in opts.items() if v is not None}
165
+ if data.get("plan") == "custom":
166
+ data["plan"] = None # start from default plan, then custom limits override it
167
+ user = users.create_user(db, actor=_actor(admin), status="active", **data, **opts)
168
+ return _with_usage(db, user)
169
+
170
+
171
+ @router.get("/users/{ident}")
172
+ def get_user(ident: str, db: Session = Depends(get_db)):
173
+ u = users.get_user(db, ident)
174
+ d = _with_usage(db, u)
175
+ d["container_status"] = get_system().container_status(u.username) if u.provisioned else "none"
176
+ if u.provisioned and "usage" in d:
177
+ d["usage"]["running"] = d["container_status"] == "running"
178
+ d["sessions"] = [_session_dict(s, u) for s in db.scalars(
179
+ select(LoginSession).where(LoginSession.user_id == u.id))]
180
+ return d
181
+
182
+
183
+ @router.patch("/users/{ident}")
184
+ def update_user(ident: str, body: UserUpdate, admin: User = Depends(admin_user),
185
+ db: Session = Depends(get_db)):
186
+ u = users.get_user(db, ident)
187
+ data = body.model_dump(exclude_unset=True)
188
+ clear = data.pop("clear_expiry", False)
189
+ if clear:
190
+ data["expires_at"] = None
191
+ elif "expires_at" in data and data["expires_at"] is None:
192
+ data.pop("expires_at")
193
+ if u.id == admin.id and data.get("is_admin") is False:
194
+ raise ValidationFailed("You cannot remove your own admin role")
195
+ result = users.update_user(db, u, data, _actor(admin))
196
+ return {**_with_usage(db, u), "result": result}
197
+
198
+
199
+ @router.post("/users/{ident}/approve")
200
+ def approve(ident: str, body: ApproveBody, admin: User = Depends(admin_user),
201
+ db: Session = Depends(get_db)):
202
+ u = users.approve(db, users.get_user(db, ident), _actor(admin), body.plan)
203
+ return _with_usage(db, u)
204
+
205
+
206
+ @router.post("/users/{ident}/reject")
207
+ def reject(ident: str, admin: User = Depends(admin_user), db: Session = Depends(get_db)):
208
+ users.reject(db, users.get_user(db, ident), _actor(admin))
209
+ return {"ok": True}
210
+
211
+
212
+ @router.post("/users/{ident}/disable")
213
+ def disable(ident: str, admin: User = Depends(admin_user), db: Session = Depends(get_db)):
214
+ u = users.get_user(db, ident)
215
+ if u.id == admin.id:
216
+ raise ValidationFailed("You cannot disable yourself")
217
+ users.disable(db, u, _actor(admin))
218
+ return _with_usage(db, u)
219
+
220
+
221
+ @router.post("/users/{ident}/enable")
222
+ def enable(ident: str, admin: User = Depends(admin_user), db: Session = Depends(get_db)):
223
+ u = users.get_user(db, ident)
224
+ users.enable(db, u, _actor(admin))
225
+ return _with_usage(db, u)
226
+
227
+
228
+ @router.delete("/users/{ident}")
229
+ def delete_user(ident: str, keep_home: bool = True, admin: User = Depends(admin_user),
230
+ db: Session = Depends(get_db)):
231
+ u = users.get_user(db, ident)
232
+ if u.id == admin.id:
233
+ raise ValidationFailed("You cannot delete yourself")
234
+ return {"ok": True, **users.delete(db, u, _actor(admin), keep_home=keep_home)}
235
+
236
+
237
+ @router.post("/users/{ident}/container/{action}")
238
+ def container_action(ident: str, action: Literal["start", "stop", "restart", "rebuild", "provision"],
239
+ admin: User = Depends(admin_user), db: Session = Depends(get_db)):
240
+ u = users.get_user(db, ident)
241
+ system = get_system()
242
+ if action == "provision":
243
+ if u.status != "active":
244
+ raise ValidationFailed("User must be active")
245
+ workspace.provision(db, u, _actor(admin))
246
+ elif not u.provisioned:
247
+ raise ValidationFailed("Workspace is not provisioned yet", code="not_provisioned")
248
+ elif action == "start":
249
+ workspace.ensure_running(db, u)
250
+ elif action == "stop":
251
+ system.container_stop(u.username)
252
+ elif action == "restart":
253
+ system.container_restart(u.username)
254
+ elif action == "rebuild":
255
+ workspace.rebuild(db, u, _actor(admin))
256
+ audit(db, f"container.{action}", actor=_actor(admin), target=u.email)
257
+ status = system.container_status(u.username)
258
+ workspace.mark_running(db, u, status == "running")
259
+ return {"ok": True, "container_status": status}
260
+
261
+
262
+ # --------------------------------------------------------------- sessions
263
+ def _session_dict(s: LoginSession, u: User | None) -> dict[str, Any]:
264
+ return {"id": s.id, "user_id": s.user_id, "email": u.email if u else None,
265
+ "username": u.username if u else None, "ip": s.ip, "user_agent": s.user_agent,
266
+ "auth_method": s.auth_method,
267
+ "created_at": s.created_at, "last_seen": s.last_seen, "expires_at": s.expires_at}
268
+
269
+
270
+ @router.get("/sessions")
271
+ def list_sessions(db: Session = Depends(get_db)):
272
+ rows = db.execute(select(LoginSession, User).join(User, User.id == LoginSession.user_id)
273
+ .where(LoginSession.expires_at > utcnow())
274
+ .order_by(LoginSession.last_seen.desc())).all()
275
+ return [_session_dict(s, u) for s, u in rows]
276
+
277
+
278
+ @router.delete("/sessions/{sid}")
279
+ def kill_session(sid: int, request: Request, admin: User = Depends(admin_user),
280
+ db: Session = Depends(get_db)):
281
+ s = db.get(LoginSession, sid)
282
+ if s is None:
283
+ raise NotFound("Session not found")
284
+ u = db.get(User, s.user_id)
285
+ db.delete(s)
286
+ audit(db, "session.kill", actor=_actor(admin), target=u.email if u else "", ip=client_ip(request))
287
+ return {"ok": True}
288
+
289
+
290
+ @router.post("/users/{ident}/logout")
291
+ def force_logout(ident: str, disconnect: bool = True, admin: User = Depends(admin_user),
292
+ db: Session = Depends(get_db)):
293
+ u = users.get_user(db, ident)
294
+ n = users.force_logout(db, u, _actor(admin), disconnect=disconnect)
295
+ return {"ok": True, "sessions_ended": n}
296
+
297
+
298
+ # --------------------------------------------------------------- passwords
299
+ @router.post("/users/{ident}/password")
300
+ def set_user_password(ident: str, body: PasswordBody, request: Request,
301
+ admin: User = Depends(admin_user), db: Session = Depends(get_db)):
302
+ u = users.get_user(db, ident)
303
+ native.set_password(db, u, body.password, must_change=body.must_change_password)
304
+ # the old password must stop working everywhere: end the user's sessions
305
+ n = end_user_sessions(db, u.id) if u.id != admin.id else 0
306
+ audit(db, "user.password_set", actor=_actor(admin), target=u.email, ip=client_ip(request),
307
+ must_change=body.must_change_password, sessions_ended=n)
308
+ return _with_usage(db, u)
309
+
310
+
311
+ @router.delete("/users/{ident}/password")
312
+ def remove_user_password(ident: str, request: Request, admin: User = Depends(admin_user),
313
+ db: Session = Depends(get_db)):
314
+ u = users.get_user(db, ident)
315
+ if u.id == admin.id:
316
+ raise ValidationFailed("You cannot remove your own password here")
317
+ if not saml.sso_active(db):
318
+ raise ValidationFailed("SSO login is off, so this user could not log in at all. "
319
+ "Enable SSO first or set a new password instead.")
320
+ u.password_hash = None
321
+ u.must_change_password = False
322
+ n = end_user_sessions(db, u.id)
323
+ audit(db, "user.password_removed", actor=_actor(admin), target=u.email,
324
+ ip=client_ip(request), sessions_ended=n)
325
+ return _with_usage(db, u)
326
+
327
+
328
+ @router.post("/users/{ident}/unlock")
329
+ def unlock_user(ident: str, admin: User = Depends(admin_user), db: Session = Depends(get_db)):
330
+ u = users.get_user(db, ident)
331
+ u.failed_logins = 0
332
+ u.locked_until = None
333
+ audit(db, "user.unlock", actor=_actor(admin), target=u.email)
334
+ return _with_usage(db, u)
335
+
336
+
337
+ # --------------------------------------------------------------- SSO
338
+ @router.post("/sso/test")
339
+ def sso_test(body: SsoTestBody, db: Session = Depends(get_db)):
340
+ """Load the IAM Identity Center metadata (without saving) and show what was found."""
341
+ url = (body.metadata_url or saml.sso_config(db)["metadata_url"]).strip()
342
+ if not saml.saml_available():
343
+ raise ValidationFailed("SAML library is not installed on the server (sudo codegate setup)",
344
+ code="saml_not_installed")
345
+ data = saml.load_metadata(url, use_cache=False)
346
+ idp = data.get("idp", {})
347
+ return {"ok": True, "entity_id": idp.get("entityId"),
348
+ "sso_url": idp.get("singleSignOnService", {}).get("url"),
349
+ "has_certificate": bool(idp.get("x509cert") or idp.get("x509certMulti"))}
350
+
351
+
352
+ # --------------------------------------------------------------- audit
353
+ def _audit_dict(a: AuditLog) -> dict[str, Any]:
354
+ try:
355
+ details = json.loads(a.details)
356
+ except ValueError:
357
+ details = {}
358
+ return {"id": a.id, "ts": a.ts, "actor": a.actor, "action": a.action, "target": a.target,
359
+ "ip": a.ip, "success": a.success, "details": details}
360
+
361
+
362
+ @router.get("/audit")
363
+ def list_audit(limit: int = Query(100, le=1000), offset: int = 0, action: str | None = None,
364
+ q: str | None = None, db: Session = Depends(get_db)):
365
+ stmt = select(AuditLog)
366
+ if action:
367
+ stmt = stmt.where(AuditLog.action.like(f"{action}%"))
368
+ if q:
369
+ like = f"%{q.lower()}%"
370
+ stmt = stmt.where(or_(AuditLog.actor.like(like), AuditLog.target.like(like)))
371
+ total = db.scalar(select(func.count()).select_from(stmt.subquery()))
372
+ rows = db.scalars(stmt.order_by(AuditLog.id.desc()).offset(offset).limit(limit))
373
+ return {"total": total, "items": [_audit_dict(a) for a in rows]}
374
+
375
+
376
+ # --------------------------------------------------------------- settings
377
+ @router.get("/settings")
378
+ def get_settings_api(db: Session = Depends(get_db)):
379
+ return all_settings(db)
380
+
381
+
382
+ @router.put("/settings")
383
+ def put_settings(body: SettingsBody, request: Request, admin: User = Depends(admin_user),
384
+ db: Session = Depends(get_db)):
385
+ data = body.model_dump(exclude_none=True)
386
+ if "plans" in data:
387
+ for name, p in data["plans"].items():
388
+ missing = {"cpu", "mem_mb", "disk_gb"} - set(p)
389
+ if missing or not name.isidentifier():
390
+ raise ValidationFailed(f"Plan '{name}' is invalid (needs cpu, mem_mb, disk_gb)")
391
+ p.setdefault("pids", 512)
392
+ for k in ("mem_mb", "disk_gb", "pids"):
393
+ p[k] = int(p[k])
394
+ plans = data.get("plans") or all_settings(db)["plans"]
395
+ if "default_plan" in data and data["default_plan"] not in plans:
396
+ raise ValidationFailed("default_plan must be one of the plans")
397
+ current = all_settings(db)
398
+ merged = {**current, **data}
399
+ if "saml_idp_metadata_url" in data:
400
+ data["saml_idp_metadata_url"] = data["saml_idp_metadata_url"].strip()
401
+ merged["saml_idp_metadata_url"] = data["saml_idp_metadata_url"]
402
+ if data["saml_idp_metadata_url"] and not data["saml_idp_metadata_url"].startswith("https://"):
403
+ raise ValidationFailed("SSO metadata URL must start with https://")
404
+ sso_ok = bool(merged["saml_idp_metadata_url"] or get_settings().saml_idp_metadata_file)
405
+ if merged["sso_enabled"] and not sso_ok:
406
+ raise ValidationFailed("Set the SSO metadata URL before enabling SSO login")
407
+ if not merged["password_login_enabled"] and not merged["sso_enabled"]:
408
+ raise ValidationFailed("At least one login method must stay enabled")
409
+ if not merged["password_login_enabled"] and not admin_has_sso_path(db):
410
+ raise ValidationFailed("No active admin could sign in with SSO. Keep password login on "
411
+ "until an admin has signed in with SSO at least once.")
412
+ if "auto_approve_domains" in data:
413
+ data["auto_approve_domains"] = sorted({d.strip().lower().lstrip("@")
414
+ for d in data["auto_approve_domains"] if d.strip()})
415
+ for key, value in data.items():
416
+ set_setting(db, key, value)
417
+ ended = {}
418
+ if current["sso_enabled"] and not merged["sso_enabled"]:
419
+ ended["sso"] = end_method_sessions(db, "sso")
420
+ if current["password_login_enabled"] and not merged["password_login_enabled"]:
421
+ ended["password"] = end_method_sessions(db, "password", keep_id=_session_id(request, db))
422
+ if any(k.startswith("saml_") for k in data):
423
+ saml.clear_metadata_cache()
424
+ audit(db, "settings.update", actor=_actor(admin), keys=sorted(data),
425
+ sessions_ended=ended or None)
426
+ return all_settings(db)
427
+
428
+
429
+ def _session_id(request: Request, db: Session) -> int | None:
430
+ res = resolve_session(db, request, touch=False)
431
+ return res[0].id if res else None
432
+
433
+
434
+ def admin_has_sso_path(db: Session) -> bool:
435
+ """An active admin exists who has signed in with SSO before (so disabling passwords
436
+ won't lock every admin out)."""
437
+ admins = {u.email for u in db.scalars(select(User).where(User.is_admin.is_(True),
438
+ User.status == "active"))}
439
+ if not admins:
440
+ return False
441
+ hit = db.scalar(select(AuditLog).where(AuditLog.action == "auth.login",
442
+ AuditLog.target.in_(admins),
443
+ AuditLog.details.like('%"method": "sso"%')).limit(1))
444
+ return hit is not None
445
+
446
+
447
+ # --------------------------------------------------------------- maintenance
448
+ @router.post("/nginx/sync")
449
+ def nginx_sync(admin: User = Depends(admin_user), db: Session = Depends(get_db)):
450
+ result = workspace.nginx_sync_all(db)
451
+ audit(db, "nginx.sync", actor=_actor(admin), **result)
452
+ return result
453
+
454
+
455
+ @router.get("/plans")
456
+ def plans(db: Session = Depends(get_db)):
457
+ return all_settings(db)["plans"]
codegate/api/deps.py ADDED
@@ -0,0 +1,36 @@
1
+ """Request dependencies: current user, admin check, CSRF header."""
2
+ from __future__ import annotations
3
+
4
+ from fastapi import Depends, Request
5
+ from sqlalchemy.orm import Session
6
+
7
+ from ..auth.sessions import resolve_session
8
+ from ..db import User, get_db
9
+ from ..errors import Forbidden, Unauthorized
10
+
11
+ CSRF_HEADER = "x-codegate"
12
+
13
+
14
+ def current_user(request: Request, db: Session = Depends(get_db)) -> User:
15
+ res = resolve_session(db, request)
16
+ if res is None:
17
+ raise Unauthorized("Login required")
18
+ _, user = res
19
+ if user.status != "active":
20
+ raise Forbidden("Account is not active", code=f"account_{user.status}")
21
+ return user
22
+
23
+
24
+ def admin_user(request: Request, user: User = Depends(current_user)) -> User:
25
+ if user.must_change_password:
26
+ raise Forbidden("Change your password first", code="password_change_required")
27
+ if not user.is_admin:
28
+ raise Forbidden("Admin access required")
29
+ if request.method not in ("GET", "HEAD", "OPTIONS") and request.headers.get(CSRF_HEADER) != "1":
30
+ raise Forbidden("Missing X-CodeGate header", code="csrf_check_failed")
31
+ return user
32
+
33
+
34
+ def csrf(request: Request) -> None:
35
+ if request.headers.get(CSRF_HEADER) != "1":
36
+ raise Forbidden("Missing X-CodeGate header", code="csrf_check_failed")
@@ -0,0 +1,132 @@
1
+ """DEV MODE + Docker only: proxy /editor/<user>/ to the user's code-server container.
2
+
3
+ On the server nginx does this (auth_request + proxy_pass + websocket upgrade).
4
+ On a laptop there is no nginx, so the backend does the same job:
5
+ login check -> forward HTTP and websockets to 127.0.0.1:<port>.
6
+ Never registered in production.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+
13
+ import httpx
14
+ from fastapi import APIRouter, Request, WebSocket
15
+ from fastapi.responses import StreamingResponse
16
+ from starlette.background import BackgroundTask
17
+
18
+ from .. import users
19
+ from ..auth.sessions import resolve_session
20
+ from ..db import User, session_scope
21
+ from . import public
22
+
23
+ log = logging.getLogger("codegate.devproxy")
24
+ router = APIRouter()
25
+
26
+ HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers",
27
+ "transfer-encoding", "upgrade", "host", "content-length"}
28
+ _client: httpx.AsyncClient | None = None
29
+
30
+
31
+ def _http() -> httpx.AsyncClient:
32
+ global _client
33
+ if _client is None:
34
+ _client = httpx.AsyncClient(timeout=httpx.Timeout(60, read=None), follow_redirects=False)
35
+ return _client
36
+
37
+
38
+ def _allowed_port(conn, username: str) -> int | None:
39
+ """Same decision nginx auth_request makes; returns the container port if allowed."""
40
+ with session_scope() as db:
41
+ res = resolve_session(db, conn)
42
+ if res is None or not users.can_use_editor(res[1], username):
43
+ return None
44
+ user = db.get(User, res[1].id)
45
+ return user.port if user and user.provisioned else None
46
+
47
+
48
+ @router.api_route("/editor/{username}/{rest:path}",
49
+ methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
50
+ include_in_schema=False)
51
+ async def editor_http(username: str, rest: str, request: Request):
52
+ port = _allowed_port(request, username)
53
+ if port is None:
54
+ return await asyncio.to_thread(_fallback, username, rest, request)
55
+ url = f"http://127.0.0.1:{port}/{rest}"
56
+ if request.url.query:
57
+ url += "?" + request.url.query
58
+ headers = {k: v for k, v in request.headers.items() if k.lower() not in HOP}
59
+ try:
60
+ req = _http().build_request(request.method, url, headers=headers,
61
+ content=await request.body())
62
+ upstream = await _http().send(req, stream=True)
63
+ except httpx.HTTPError:
64
+ # container stopped / still booting -> same "Starting..." page nginx would show
65
+ return await asyncio.to_thread(_fallback, username, rest, request)
66
+ out_headers = [(k, v) for k, v in upstream.headers.multi_items() if k.lower() not in HOP]
67
+ resp = StreamingResponse(upstream.aiter_raw(), status_code=upstream.status_code,
68
+ background=BackgroundTask(upstream.aclose))
69
+ resp.raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1"))
70
+ for k, v in out_headers]
71
+ return resp
72
+
73
+
74
+ def _fallback(username: str, rest: str, request: Request):
75
+ with session_scope() as db:
76
+ return public.editor_fallback(username, rest, request, db)
77
+
78
+
79
+ @router.websocket("/editor/{username}/{rest:path}")
80
+ async def editor_ws(websocket: WebSocket, username: str, rest: str):
81
+ from websockets.asyncio.client import connect
82
+ from websockets.exceptions import ConnectionClosed
83
+
84
+ port = _allowed_port(websocket, username)
85
+ if port is None:
86
+ await websocket.close(code=4403)
87
+ return
88
+ url = f"ws://127.0.0.1:{port}/{rest}"
89
+ if websocket.url.query:
90
+ url += "?" + websocket.url.query
91
+ protos = [p.strip() for p in websocket.headers.get("sec-websocket-protocol", "").split(",")
92
+ if p.strip()]
93
+ try:
94
+ upstream = await connect(url, subprotocols=protos or None, max_size=None,
95
+ compression=None, open_timeout=15)
96
+ except Exception as exc: # noqa: BLE001
97
+ log.info("ws connect to %s failed: %s", url, exc)
98
+ await websocket.close(code=1011)
99
+ return
100
+ await websocket.accept(subprotocol=upstream.subprotocol)
101
+
102
+ async def browser_to_container():
103
+ while True:
104
+ msg = await websocket.receive()
105
+ if msg["type"] == "websocket.disconnect":
106
+ break
107
+ if msg.get("bytes") is not None:
108
+ await upstream.send(msg["bytes"])
109
+ elif msg.get("text") is not None:
110
+ await upstream.send(msg["text"])
111
+
112
+ async def container_to_browser():
113
+ async for data in upstream:
114
+ if isinstance(data, bytes):
115
+ await websocket.send_bytes(data)
116
+ else:
117
+ await websocket.send_text(data)
118
+
119
+ tasks = [asyncio.create_task(browser_to_container()),
120
+ asyncio.create_task(container_to_browser())]
121
+ try:
122
+ await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
123
+ except ConnectionClosed:
124
+ pass
125
+ finally:
126
+ for t in tasks:
127
+ t.cancel()
128
+ await upstream.close()
129
+ try:
130
+ await websocket.close()
131
+ except RuntimeError:
132
+ pass