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/api/public.py ADDED
@@ -0,0 +1,371 @@
1
+ """Login / SSO / logout / nginx auth check / editor fallback / user workspace API."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ from urllib.parse import urlparse
6
+
7
+ import httpx
8
+ from fastapi import APIRouter, Depends, Form, Request
9
+ from fastapi.responses import JSONResponse, RedirectResponse, Response
10
+ from sqlalchemy.orm import Session
11
+
12
+ from .. import pages, users, workspace
13
+ from ..auth import csrf, native, saml
14
+ from ..auth.passwords import verify_password
15
+ from ..auth.sessions import (clear_cookie, client_ip, create_session, end_session,
16
+ end_user_sessions, resolve_session)
17
+ from ..config import get_settings
18
+ from ..db import Usage, audit, get_db, get_setting, utcnow
19
+ from ..errors import AppError, SSOError, ValidationFailed
20
+ from ..system import get_system
21
+ from .deps import csrf as deps_csrf
22
+ from .deps import current_user
23
+
24
+ log = logging.getLogger("codegate.api")
25
+ router = APIRouter()
26
+
27
+
28
+ def _safe_next(next_url: str | None) -> str | None:
29
+ """Only allow local paths under our base path (prevents open redirects)."""
30
+ if not next_url:
31
+ return None
32
+ base = get_settings().base_path
33
+ p = urlparse(next_url)
34
+ if p.scheme or p.netloc or not next_url.startswith(base + "/") or "//" in next_url \
35
+ or "\\" in next_url:
36
+ return None
37
+ return next_url
38
+
39
+
40
+ def _redirect(url: str) -> RedirectResponse:
41
+ return RedirectResponse(url, status_code=302)
42
+
43
+
44
+ @router.get("/healthz")
45
+ def healthz():
46
+ return {"status": "ok", "time": utcnow().isoformat()}
47
+
48
+
49
+ @router.get("/")
50
+ def landing(request: Request, db: Session = Depends(get_db)):
51
+ res = resolve_session(db, request)
52
+ if res is None:
53
+ return _redirect(f"{get_settings().base_path}/login")
54
+ return _redirect(users.landing_path(res[1]))
55
+
56
+
57
+ def _login_form(request: Request, db: Session, *, next_url: str = "", error: str = "",
58
+ info: str = "", username: str = "", status: int = 200):
59
+ tok = csrf.get_or_create(request)
60
+ resp = pages.respond(pages.login_page(
61
+ csrf=tok, next_url=next_url, error=error, info=info, username=username,
62
+ password_enabled=bool(get_setting(db, "password_login_enabled")),
63
+ sso_enabled=saml.sso_active(db)), status)
64
+ csrf.set_cookie(resp, tok)
65
+ return resp
66
+
67
+
68
+ @router.get("/login")
69
+ def login(request: Request, next: str | None = None, db: Session = Depends(get_db)):
70
+ nxt = _safe_next(next)
71
+ res = resolve_session(db, request)
72
+ if res is not None:
73
+ user = res[1]
74
+ if nxt and user.status == "active" and not user.must_change_password:
75
+ return _redirect(nxt)
76
+ return _redirect(users.landing_path(user))
77
+ return _login_form(request, db, next_url=nxt or "")
78
+
79
+
80
+ @router.post("/login")
81
+ def login_submit(request: Request, username: str = Form("", max_length=320),
82
+ password: str = Form("", max_length=1024), csrf_token: str = Form("", alias="csrf"),
83
+ next: str = Form(""), db: Session = Depends(get_db)):
84
+ ip = client_ip(request)
85
+ nxt = _safe_next(next) or ""
86
+ if not csrf.valid(request, csrf_token):
87
+ return _login_form(request, db, next_url=nxt, status=400,
88
+ error="Your login form expired. Please try again.")
89
+ try:
90
+ user = native.authenticate(db, username, password, ip)
91
+ except native.LoginFailed as exc:
92
+ audit(db, "auth.login_failed", actor=(username or "")[:320].lower(),
93
+ target=exc.user.email if exc.user else "", ip=ip, success=False,
94
+ method="password", code=exc.code)
95
+ db.commit() # keep failed-attempt counters even though we return an error page
96
+ return _login_form(request, db, next_url=nxt, error=exc.message, username=username[:320],
97
+ status=429 if exc.code == "ip_rate_limited" else 401)
98
+ target = users.landing_path(user)
99
+ if nxt and user.status == "active" and not user.must_change_password \
100
+ and not nxt.rstrip("/").endswith(get_settings().base_path):
101
+ target = nxt
102
+ resp = _redirect(target)
103
+ create_session(db, user, request, resp, auth_method="password")
104
+ audit(db, "auth.login", actor=user.email, target=user.email, ip=ip, method="password",
105
+ status=user.status)
106
+ return resp
107
+
108
+
109
+ @router.get("/saml/login")
110
+ def saml_login(request: Request, next: str | None = None, db: Session = Depends(get_db)):
111
+ nxt = _safe_next(next)
112
+ if not saml.sso_active(db):
113
+ return _login_form(request, db, next_url=nxt or "", status=403,
114
+ error="AWS SSO login is not enabled.")
115
+ try:
116
+ return _redirect(saml.login_redirect_url(db, nxt or f"{get_settings().base_path}/"))
117
+ except AppError as exc:
118
+ log.error("SSO login redirect failed: %s %s", exc.message, exc.details)
119
+ return pages.respond(pages.error_page("SSO unavailable", exc.message), exc.status_code)
120
+
121
+
122
+ @router.get("/saml/metadata")
123
+ def saml_metadata():
124
+ return Response(saml.sp_metadata_xml(), media_type="application/xml")
125
+
126
+
127
+ def _finish_sso_login(db: Session, request: Request, email: str, name: str, relay: str | None):
128
+ user = users.on_sso_login(db, email, name)
129
+ if user.status == "disabled":
130
+ audit(db, "auth.login_failed", actor=email, target=email, ip=client_ip(request),
131
+ success=False, method="sso", code="account_disabled")
132
+ return pages.respond(pages.forbidden_page(email), 403)
133
+ target = users.landing_path(user)
134
+ nxt = _safe_next(relay)
135
+ if nxt and user.status == "active" and not user.must_change_password \
136
+ and not nxt.rstrip("/").endswith(get_settings().base_path):
137
+ target = nxt
138
+ resp = _redirect(target)
139
+ create_session(db, user, request, resp, auth_method="sso")
140
+ audit(db, "auth.login", actor=email, target=email, ip=client_ip(request), method="sso",
141
+ status=user.status)
142
+ return resp
143
+
144
+
145
+ @router.post("/saml/acs")
146
+ async def saml_acs(request: Request, db: Session = Depends(get_db)):
147
+ form = {k: str(v) for k, v in (await request.form()).items()}
148
+ try:
149
+ info = saml.process_acs(db, form)
150
+ except SSOError as exc:
151
+ audit(db, "auth.login_failed", ip=client_ip(request), success=False, method="sso",
152
+ code=exc.code, **exc.details)
153
+ db.commit()
154
+ return pages.respond(pages.error_page("Login failed", exc.message), exc.status_code)
155
+ return _finish_sso_login(db, request, info["email"], info["name"], form.get("RelayState"))
156
+
157
+
158
+ # --------------------------------------------------------------- logout
159
+ def _do_logout(db: Session, request: Request, response: Response) -> None:
160
+ res = resolve_session(db, request, touch=False)
161
+ if res:
162
+ audit(db, "auth.logout", actor=res[1].email, target=res[1].email, ip=client_ip(request))
163
+ end_session(db, request)
164
+ clear_cookie(response)
165
+
166
+
167
+ @router.get("/logout")
168
+ def logout_confirm(request: Request, db: Session = Depends(get_db)):
169
+ """GET never logs out (a link on another site can't end your session); it asks."""
170
+ if resolve_session(db, request, touch=False) is None:
171
+ resp = pages.respond(pages.logged_out_page())
172
+ clear_cookie(resp)
173
+ return resp
174
+ tok = csrf.get_or_create(request)
175
+ resp = pages.respond(pages.logout_confirm_page(tok))
176
+ csrf.set_cookie(resp, tok)
177
+ return resp
178
+
179
+
180
+ @router.post("/logout")
181
+ def logout(request: Request, csrf_token: str = Form("", alias="csrf"),
182
+ db: Session = Depends(get_db)):
183
+ if not csrf.valid(request, csrf_token):
184
+ return _redirect(f"{get_settings().base_path}/logout")
185
+ resp = pages.respond(pages.logged_out_page())
186
+ _do_logout(db, request, resp)
187
+ return resp
188
+
189
+
190
+ @router.post("/api/me/logout", dependencies=[Depends(deps_csrf)])
191
+ def api_logout(request: Request, db: Session = Depends(get_db)):
192
+ resp = JSONResponse({"ok": True, "login_url": f"{get_settings().base_path}/login"})
193
+ _do_logout(db, request, resp)
194
+ return resp
195
+
196
+
197
+ # --------------------------------------------------------------- account / password
198
+ def _pw_page(request: Request, db: Session, user, *, error: str = "", next_url: str = "",
199
+ status: int = 200):
200
+ tok = csrf.get_or_create(request)
201
+ resp = pages.respond(pages.change_password_page(
202
+ csrf=tok, email=user.email, forced=user.must_change_password, error=error,
203
+ min_length=int(get_setting(db, "password_min_length") or 12), next_url=next_url), status)
204
+ csrf.set_cookie(resp, tok)
205
+ return resp
206
+
207
+
208
+ @router.get("/account/password")
209
+ def account_password(request: Request, next: str | None = None, db: Session = Depends(get_db)):
210
+ s = get_settings()
211
+ res = resolve_session(db, request)
212
+ if res is None:
213
+ return _redirect(f"{s.base_path}/login?next={s.base_path}/account/password")
214
+ user = res[1]
215
+ if not user.password_hash:
216
+ return pages.respond(pages.no_password_page(user.email))
217
+ return _pw_page(request, db, user, next_url=_safe_next(next) or "")
218
+
219
+
220
+ @router.post("/account/password")
221
+ def account_password_submit(request: Request, current: str = Form("", max_length=1024),
222
+ new: str = Form("", max_length=1024),
223
+ confirm: str = Form("", max_length=1024),
224
+ csrf_token: str = Form("", alias="csrf"), next: str = Form(""),
225
+ db: Session = Depends(get_db)):
226
+ s = get_settings()
227
+ res = resolve_session(db, request)
228
+ if res is None:
229
+ return _redirect(f"{s.base_path}/login")
230
+ sess, user = res
231
+ nxt = _safe_next(next) or ""
232
+ if not user.password_hash:
233
+ return pages.respond(pages.no_password_page(user.email))
234
+ if not csrf.valid(request, csrf_token):
235
+ return _pw_page(request, db, user, error="The form expired. Please try again.",
236
+ next_url=nxt, status=400)
237
+ if not verify_password(current, user.password_hash):
238
+ audit(db, "auth.password_change_failed", actor=user.email, target=user.email,
239
+ ip=client_ip(request), success=False)
240
+ return _pw_page(request, db, user, error="Current password is wrong.", next_url=nxt,
241
+ status=400)
242
+ if new != confirm:
243
+ return _pw_page(request, db, user, error="The new passwords don't match.", next_url=nxt,
244
+ status=400)
245
+ if new == current:
246
+ return _pw_page(request, db, user, error="Choose a password different from the current one.",
247
+ next_url=nxt, status=400)
248
+ try:
249
+ native.set_password(db, user, new, must_change=False)
250
+ except ValidationFailed as exc:
251
+ return _pw_page(request, db, user, error=exc.message, next_url=nxt, status=400)
252
+ ended = end_user_sessions(db, user.id, keep_id=sess.id)
253
+ audit(db, "auth.password_changed", actor=user.email, target=user.email, ip=client_ip(request),
254
+ other_sessions_ended=ended)
255
+ resp = _redirect(nxt or users.landing_path(user))
256
+ create_session(db, user, request, resp, auth_method=sess.auth_method) # rotate the token
257
+ return resp
258
+
259
+
260
+ @router.get("/pending")
261
+ def pending(request: Request, db: Session = Depends(get_db)):
262
+ res = resolve_session(db, request)
263
+ if res is None:
264
+ return _redirect(f"{get_settings().base_path}/login")
265
+ if res[1].status != "pending":
266
+ return _redirect(users.landing_path(res[1]))
267
+ return pages.respond(pages.pending_page(res[1].email))
268
+
269
+
270
+ @router.get("/forbidden")
271
+ def forbidden(request: Request, db: Session = Depends(get_db)):
272
+ res = resolve_session(db, request)
273
+ if res and res[1].status == "active" and res[1].must_change_password:
274
+ return _redirect(f"{get_settings().base_path}/account/password") # nginx sends 403 here
275
+ return pages.respond(pages.forbidden_page(res[1].email if res else None), 403)
276
+
277
+
278
+ # --------------------------------------------------------------- nginx auth_request
279
+ @router.get("/_auth/{username}")
280
+ def auth_check(username: str, request: Request, db: Session = Depends(get_db)):
281
+ """200 = allow, 401 = login needed, 403 = not allowed. Called by nginx for every
282
+ request to /editor/<username>/ (must be fast)."""
283
+ res = resolve_session(db, request)
284
+ if res is None:
285
+ return Response(status_code=401)
286
+ user = res[1]
287
+ if not users.can_use_editor(user, username):
288
+ return Response(status_code=403)
289
+ return Response(status_code=200, headers={"X-CodeGate-User": user.username})
290
+
291
+
292
+ # --------------------------------------------------------------- editor fallback
293
+ @router.get("/editor/{username}")
294
+ def editor_noslash(username: str):
295
+ return _redirect(f"{get_settings().base_path}/editor/{username}/")
296
+
297
+
298
+ @router.get("/editor/{username}/{rest:path}")
299
+ def editor_fallback(username: str, rest: str, request: Request, db: Session = Depends(get_db)):
300
+ """Reached when nginx cannot reach the container (stopped/starting) or the user has
301
+ no nginx route yet. Shows the right page for the user's state."""
302
+ s = get_settings()
303
+ res = resolve_session(db, request)
304
+ if res is None:
305
+ return _redirect(f"{s.base_path}/login?next={s.base_path}/editor/{username}/")
306
+ user = res[1]
307
+ if user.status == "pending":
308
+ return _redirect(f"{s.base_path}/pending")
309
+ if user.must_change_password and user.username == username:
310
+ return _redirect(f"{s.base_path}/account/password?next={s.base_path}/editor/{username}/")
311
+ if not users.can_use_editor(user, username):
312
+ if user.is_admin and user.username != username:
313
+ return pages.respond(pages.forbidden_page(
314
+ user.email, "Admins cannot open other users' workspaces."), 403)
315
+ return _redirect(f"{s.base_path}/forbidden")
316
+ if rest not in ("", "/") and request.headers.get("accept", "").find("text/html") < 0:
317
+ return JSONResponse({"code": "workspace_starting", "message": "Workspace is starting"},
318
+ status_code=503)
319
+ return pages.respond(pages.starting_page(user.username))
320
+
321
+
322
+ # --------------------------------------------------------------- user API
323
+ @router.get("/api/me")
324
+ def me(user=Depends(current_user)):
325
+ return users.user_dict(user)
326
+
327
+
328
+ def _workspace_ready(user) -> bool:
329
+ system = get_system()
330
+ if system.name == "fake":
331
+ return system.container_status(user.username) == "running"
332
+ if not user.port:
333
+ return False
334
+ try:
335
+ r = httpx.get(f"http://127.0.0.1:{user.port}/healthz", timeout=2)
336
+ return r.status_code == 200
337
+ except httpx.HTTPError:
338
+ return False
339
+
340
+
341
+ @router.get("/api/me/workspace/status")
342
+ def my_workspace_status(user=Depends(current_user)):
343
+ if not user.has_workspace:
344
+ return {"status": "none", "ready": False, "message": "No workspace assigned"}
345
+ if not user.provisioned:
346
+ return {"status": "not_provisioned", "ready": False, "message": "Preparing workspace…"}
347
+ status = get_system().container_status(user.username)
348
+ if get_system().name == "fake":
349
+ return {"status": "dev", "ready": False,
350
+ "message": f"DEV MODE: workspace is '{status}'. Real VS Code opens on the server."}
351
+ ready = status == "running" and _workspace_ready(user)
352
+ msg = {"running": "Almost ready…" if not ready else "Ready", "exited": "Stopped",
353
+ "missing": "Recreating workspace…"}.get(status, status)
354
+ if user.over_quota and status != "running":
355
+ return {"status": "error", "ready": False,
356
+ "message": "Disk limit exceeded. Ask your admin to increase disk space."}
357
+ return {"status": status, "ready": ready, "message": msg}
358
+
359
+
360
+ @router.post("/api/me/workspace/start", dependencies=[Depends(deps_csrf)])
361
+ def my_workspace_start(user=Depends(current_user), db: Session = Depends(get_db)):
362
+ if not user.has_workspace:
363
+ return {"status": "none"}
364
+ try:
365
+ status = workspace.ensure_running(db, user)
366
+ except AppError as exc:
367
+ return JSONResponse({"code": exc.code, "message": exc.message, "status": "error"},
368
+ status_code=exc.status_code)
369
+ workspace.mark_running(db, user, True)
370
+ db.get(Usage, user.id).last_active = utcnow()
371
+ return {"status": status}
codegate/app.py ADDED
@@ -0,0 +1,115 @@
1
+ """FastAPI application factory."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import logging
6
+ from contextlib import asynccontextmanager
7
+ from pathlib import Path
8
+
9
+ from fastapi import APIRouter, FastAPI, Request
10
+ from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
11
+
12
+ from . import __version__
13
+ from .api import admin, public
14
+ from .config import get_settings
15
+ from .db import migrate
16
+ from .errors import install_handlers
17
+ from .jobs import run_background_jobs
18
+
19
+ log = logging.getLogger("codegate")
20
+
21
+ STATIC_ADMIN = Path(__file__).parent / "static" / "admin"
22
+
23
+
24
+ def _admin_router() -> APIRouter:
25
+ r = APIRouter()
26
+
27
+ def index(request: Request):
28
+ from .auth.sessions import resolve_session
29
+ from .db import session_scope
30
+ base = get_settings().base_path
31
+ with session_scope() as db:
32
+ res = resolve_session(db, request, touch=False)
33
+ if res is None:
34
+ return RedirectResponse(f"{base}/login?next={base}/admin/", 302)
35
+ if res[1].must_change_password:
36
+ return RedirectResponse(f"{base}/account/password?next={base}/admin/", 302)
37
+ if not res[1].is_admin:
38
+ return RedirectResponse(f"{base}/", 302)
39
+ f = STATIC_ADMIN / "index.html"
40
+ if not f.is_file():
41
+ return HTMLResponse("<h1>Admin UI not built</h1><p>The package was built without the "
42
+ "Angular admin portal (frontend/ -> npm run build).</p>", 500)
43
+ html = f.read_text().replace('<base href="/codeapp/admin/">',
44
+ f'<base href="{get_settings().base_path}/admin/">')
45
+ return HTMLResponse(html, headers={"Cache-Control": "no-store"})
46
+
47
+ @r.get("/admin", include_in_schema=False)
48
+ def admin_noslash():
49
+ return RedirectResponse(f"{get_settings().base_path}/admin/", 302)
50
+
51
+ @r.get("/admin/{path:path}", include_in_schema=False)
52
+ def admin_spa(path: str, request: Request):
53
+ # static asset (hashed js/css/fonts) or SPA route -> index.html
54
+ if path:
55
+ candidate = (STATIC_ADMIN / path).resolve()
56
+ if STATIC_ADMIN.resolve() in candidate.parents and candidate.is_file():
57
+ return FileResponse(candidate, headers={"Cache-Control": "public, max-age=31536000"})
58
+ return index(request)
59
+
60
+ return r
61
+
62
+
63
+ def create_app(*, run_jobs: bool = True) -> FastAPI:
64
+ s = get_settings()
65
+
66
+ @asynccontextmanager
67
+ async def lifespan(app: FastAPI):
68
+ old, new = migrate()
69
+ if old != new:
70
+ log.info("database migrated v%s -> v%s", old, new)
71
+ stop = asyncio.Event()
72
+ task = asyncio.create_task(run_background_jobs(stop)) if run_jobs else None
73
+ log.info("CodeGate %s started (%s) at %s", __version__, "DEV MODE" if s.dev_mode else "prod",
74
+ s.public_url)
75
+ yield
76
+ stop.set()
77
+ if task:
78
+ await task
79
+
80
+ app = FastAPI(title="CodeGate", version=__version__, lifespan=lifespan,
81
+ docs_url=f"{s.base_path}/api/docs" if s.dev_mode else None,
82
+ openapi_url=f"{s.base_path}/api/openapi.json" if s.dev_mode else None,
83
+ redoc_url=None)
84
+ install_handlers(app)
85
+
86
+ editor_prefix = f"{s.base_path}/editor/"
87
+
88
+ @app.middleware("http")
89
+ async def security_headers(request, call_next):
90
+ response = await call_next(request)
91
+ if request.url.path.startswith(editor_prefix):
92
+ return response # VS Code (proxied in dev) sets its own headers
93
+ h = response.headers
94
+ h.setdefault("X-Content-Type-Options", "nosniff")
95
+ h.setdefault("X-Frame-Options", "DENY")
96
+ h.setdefault("Referrer-Policy", "same-origin")
97
+ h.setdefault("Cross-Origin-Opener-Policy", "same-origin")
98
+ if s.public_scheme == "https":
99
+ h.setdefault("Strict-Transport-Security", "max-age=31536000")
100
+ if request.url.path.startswith(f"{s.base_path}/api/"):
101
+ h.setdefault("Cache-Control", "no-store")
102
+ return response
103
+
104
+ if s.dev_mode and s.dev_docker:
105
+ from .api import devproxy # stands in for nginx on a laptop; never in production
106
+ app.include_router(devproxy.router, prefix=s.base_path)
107
+ app.include_router(public.router, prefix=s.base_path)
108
+ app.include_router(admin.router, prefix=s.base_path)
109
+ app.include_router(_admin_router(), prefix=s.base_path)
110
+
111
+ if s.base_path:
112
+ @app.get("/", include_in_schema=False)
113
+ def root():
114
+ return RedirectResponse(f"{s.base_path}/", 302)
115
+ return app
File without changes
codegate/auth/csrf.py ADDED
@@ -0,0 +1,43 @@
1
+ """CSRF protection for the server-rendered forms (login, logout, change password).
2
+
3
+ Double-submit token: a random value in an HttpOnly SameSite=Strict cookie and the
4
+ same value in a hidden form field. Also rejects cross-origin POSTs by Origin header.
5
+ The admin API uses the X-CodeGate header instead (see api/deps.py).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hmac
10
+ import secrets
11
+
12
+ from fastapi import Request, Response
13
+
14
+ from ..config import get_settings
15
+
16
+ COOKIE = "codegate_csrf"
17
+
18
+
19
+ def get_or_create(request: Request) -> str:
20
+ tok = request.cookies.get(COOKIE)
21
+ if tok and 20 <= len(tok) <= 100:
22
+ return tok
23
+ return secrets.token_urlsafe(32)
24
+
25
+
26
+ def set_cookie(response: Response, token: str) -> None:
27
+ s = get_settings()
28
+ response.set_cookie(COOKIE, token, max_age=8 * 3600, path=s.base_path or "/", httponly=True,
29
+ secure=(s.public_scheme == "https"), samesite="strict")
30
+
31
+
32
+ def _origin_ok(request: Request) -> bool:
33
+ s = get_settings()
34
+ origin = request.headers.get("origin")
35
+ if not origin or origin == "null":
36
+ return origin is None # missing is OK (old browsers); literal "null" is not
37
+ return origin.rstrip("/") == f"{s.public_scheme}://{s.domain}"
38
+
39
+
40
+ def valid(request: Request, form_token: str | None) -> bool:
41
+ cookie = request.cookies.get(COOKIE)
42
+ return bool(cookie and form_token and _origin_ok(request)
43
+ and hmac.compare_digest(cookie.encode(), form_token.encode()))
@@ -0,0 +1,111 @@
1
+ """Native (username/password) login: verification, lockout, rate limiting."""
2
+ from __future__ import annotations
3
+
4
+ import threading
5
+ import time
6
+ from collections import defaultdict, deque
7
+ from datetime import timedelta
8
+
9
+ from sqlalchemy import select
10
+ from sqlalchemy.orm import Session
11
+
12
+ from ..db import User, get_setting, utcnow
13
+ from ..errors import ValidationFailed
14
+ from .passwords import dummy_verify, hash_password, policy_errors, verify_password
15
+
16
+ GENERIC = "Invalid username or password."
17
+
18
+ # per-IP limiter (in memory; the service is a single process)
19
+ IP_WINDOW = 15 * 60
20
+ IP_MAX_FAILS = 20
21
+ _ip_fails: dict[str, deque] = defaultdict(deque)
22
+ _lock = threading.Lock()
23
+
24
+
25
+ class LoginFailed(Exception):
26
+ def __init__(self, message: str, code: str, user: User | None = None):
27
+ super().__init__(message)
28
+ self.message, self.code, self.user = message, code, user
29
+
30
+
31
+ def ip_blocked(ip: str) -> bool:
32
+ now = time.monotonic()
33
+ with _lock:
34
+ q = _ip_fails[ip]
35
+ while q and now - q[0] > IP_WINDOW:
36
+ q.popleft()
37
+ return len(q) >= IP_MAX_FAILS
38
+
39
+
40
+ def _ip_fail(ip: str) -> None:
41
+ with _lock:
42
+ _ip_fails[ip].append(time.monotonic())
43
+
44
+
45
+ def _ip_reset(ip: str) -> None:
46
+ with _lock:
47
+ _ip_fails.pop(ip, None)
48
+
49
+
50
+ def reset_limits() -> None:
51
+ with _lock:
52
+ _ip_fails.clear()
53
+
54
+
55
+ def find_user(db: Session, identifier: str) -> User | None:
56
+ ident = (identifier or "").strip().lower()
57
+ if not ident or len(ident) > 320:
58
+ return None
59
+ return db.scalar(select(User).where((User.username == ident) | (User.email == ident)))
60
+
61
+
62
+ def authenticate(db: Session, identifier: str, password: str, ip: str) -> User:
63
+ """Return the user, or raise LoginFailed. Never says whether the account exists."""
64
+ if not get_setting(db, "password_login_enabled"):
65
+ raise LoginFailed("Password login is disabled. Use SSO.", "password_login_disabled")
66
+ if ip_blocked(ip):
67
+ raise LoginFailed("Too many failed attempts. Try again in a few minutes.", "ip_rate_limited")
68
+ user = find_user(db, identifier)
69
+ now = utcnow()
70
+ if user is None or not user.password_hash:
71
+ dummy_verify()
72
+ _ip_fail(ip)
73
+ raise LoginFailed(GENERIC, "bad_credentials", user)
74
+ if user.locked_until and user.locked_until > now:
75
+ dummy_verify()
76
+ _ip_fail(ip)
77
+ raise LoginFailed(GENERIC, "account_locked", user)
78
+ if not verify_password(password, user.password_hash):
79
+ _ip_fail(ip)
80
+ user.failed_logins = (user.failed_logins or 0) + 1
81
+ max_fails = int(get_setting(db, "max_failed_logins") or 5)
82
+ if user.failed_logins >= max_fails:
83
+ user.locked_until = now + timedelta(minutes=int(get_setting(db, "lockout_minutes") or 15))
84
+ user.failed_logins = 0
85
+ raise LoginFailed(GENERIC, "account_locked_now", user)
86
+ raise LoginFailed(GENERIC, "bad_credentials", user)
87
+ user.failed_logins = 0
88
+ user.locked_until = None
89
+ _ip_reset(ip)
90
+ if user.status == "disabled":
91
+ raise LoginFailed("Your account is disabled. Contact your admin.", "account_disabled", user)
92
+ return user
93
+
94
+
95
+ def check_policy(db: Session, user: User | None, password: str, *, username: str = "",
96
+ email: str = "") -> None:
97
+ errs = policy_errors(password, min_length=int(get_setting(db, "password_min_length") or 12),
98
+ username=user.username if user else username,
99
+ email=user.email if user else email)
100
+ if errs:
101
+ raise ValidationFailed("Password needs: " + "; ".join(errs), code="weak_password",
102
+ details={"rules": errs})
103
+
104
+
105
+ def set_password(db: Session, user: User, password: str, *, must_change: bool) -> None:
106
+ check_policy(db, user, password)
107
+ user.password_hash = hash_password(password)
108
+ user.must_change_password = must_change
109
+ user.password_changed_at = utcnow()
110
+ user.failed_logins = 0
111
+ user.locked_until = None