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
@@ -0,0 +1,114 @@
1
+ """Backup / restore of DB, config, nginx files (and optionally user homes)."""
2
+ from __future__ import annotations
3
+
4
+ import io
5
+ import sqlite3
6
+ import tarfile
7
+ import time
8
+ from pathlib import Path
9
+
10
+ from ..config import env_file_path, get_settings
11
+ from ..db import utcnow
12
+ from .common import console
13
+
14
+
15
+ def create_backup(include_homes: bool = False, label: str = "manual") -> Path:
16
+ s = get_settings()
17
+ s.backup_dir.mkdir(parents=True, exist_ok=True)
18
+ dest = s.backup_dir / f"codegate-{label}-{utcnow():%Y%m%d-%H%M%S}.tar.gz"
19
+ with tarfile.open(dest, "w:gz") as tar:
20
+ # consistent DB snapshot via sqlite backup API
21
+ if s.db_path.exists():
22
+ src = sqlite3.connect(s.db_path)
23
+ mem = sqlite3.connect(":memory:")
24
+ src.backup(mem)
25
+ src.close()
26
+ data = "\n".join(mem.iterdump()).encode()
27
+ mem.close()
28
+ snap = s.backup_dir / ".db-snapshot.sqlite"
29
+ if snap.exists():
30
+ snap.unlink()
31
+ conn = sqlite3.connect(snap)
32
+ conn.executescript(data.decode())
33
+ conn.close()
34
+ tar.add(snap, arcname="data/codegate.db")
35
+ snap.unlink()
36
+ for path, arc in ((env_file_path(), "etc/codegate.env"), (s.nginx_dir, "nginx"),
37
+ (s.etc_dir, "data/etc"), (s.data_dir / "installed.json",
38
+ "data/installed.json")):
39
+ if Path(path).exists():
40
+ tar.add(path, arcname=arc)
41
+ if include_homes:
42
+ from sqlalchemy import select
43
+ from ..db import User, session_scope
44
+ with session_scope() as db:
45
+ names = list(db.scalars(select(User.username).where(User.provisioned.is_(True))))
46
+ for n in names:
47
+ home = s.home_root / n
48
+ if home.exists():
49
+ tar.add(home, arcname=f"homes/{n}")
50
+ info = tarfile.TarInfo("BACKUP_INFO")
51
+ meta = f"created={utcnow().isoformat()}\nhomes={include_homes}\n".encode()
52
+ info.size = len(meta)
53
+ tar.addfile(info, io.BytesIO(meta))
54
+ dest.chmod(0o600)
55
+ return dest
56
+
57
+
58
+ def prune(keep_days: int) -> int:
59
+ s = get_settings()
60
+ cutoff = time.time() - keep_days * 86400
61
+ n = 0
62
+ for f in s.backup_dir.glob("codegate-*.tar.gz"):
63
+ if f.stat().st_mtime < cutoff and "-pre-upgrade-" not in f.name:
64
+ f.unlink()
65
+ n += 1
66
+ return n
67
+
68
+
69
+ def restore_backup(file: Path, include_homes: bool = False) -> None:
70
+ from ..db import reset_engine
71
+ reset_engine() # close pooled connections before replacing the DB file
72
+ s = get_settings()
73
+ with tarfile.open(file, "r:gz") as tar:
74
+ members = tar.getmembers()
75
+ for m in members:
76
+ if m.name.startswith("/") or ".." in Path(m.name).parts:
77
+ raise RuntimeError(f"unsafe path in backup: {m.name}")
78
+ mapping = {
79
+ "data/codegate.db": s.db_path,
80
+ "etc/codegate.env": env_file_path(),
81
+ "data/installed.json": s.data_dir / "installed.json",
82
+ }
83
+ for m in members:
84
+ if m.name in mapping and m.isfile():
85
+ target = mapping[m.name]
86
+ target.parent.mkdir(parents=True, exist_ok=True)
87
+ for suffix in ("-wal", "-shm"):
88
+ w = Path(str(target) + suffix)
89
+ if w.exists():
90
+ w.unlink()
91
+ target.write_bytes(tar.extractfile(m).read())
92
+ elif m.name.startswith("nginx/") or m.name == "nginx":
93
+ _extract(tar, m, s.nginx_dir, "nginx")
94
+ elif m.name.startswith("data/etc"):
95
+ _extract(tar, m, s.etc_dir, "data/etc")
96
+ elif include_homes and m.name.startswith("homes/"):
97
+ _extract(tar, m, s.home_root, "homes")
98
+ console.print(f"[green]✓ restored from {file}[/]")
99
+
100
+
101
+ def _extract(tar: tarfile.TarFile, m: tarfile.TarInfo, root: Path, prefix: str) -> None:
102
+ rel = Path(m.name).relative_to(prefix) if m.name != prefix else Path(".")
103
+ target = root / rel
104
+ if m.isdir():
105
+ target.mkdir(parents=True, exist_ok=True)
106
+ elif m.isfile():
107
+ target.parent.mkdir(parents=True, exist_ok=True)
108
+ target.write_bytes(tar.extractfile(m).read())
109
+ try:
110
+ import os
111
+ os.chown(target, m.uid, m.gid)
112
+ os.chmod(target, m.mode)
113
+ except OSError:
114
+ pass
codegate/cli/common.py ADDED
@@ -0,0 +1,103 @@
1
+ """Shared CLI helpers."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import shutil
8
+ import sys
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Callable
12
+
13
+ import typer
14
+ from rich.console import Console
15
+
16
+ from .. import __version__, resources
17
+ from ..config import get_settings
18
+ from ..errors import AppError
19
+
20
+ console = Console()
21
+
22
+
23
+ def require_root() -> None:
24
+ if os.geteuid() != 0 and not get_settings().dev_mode:
25
+ console.print("[red]✗ This command must be run as root:[/] sudo codegate ...")
26
+ raise typer.Exit(1)
27
+
28
+
29
+ def codegate_exec() -> str:
30
+ """Absolute path of the codegate executable (for systemd units)."""
31
+ exe = shutil.which("codegate")
32
+ if exe:
33
+ return str(Path(exe).resolve())
34
+ return f"{sys.executable} -m codegate"
35
+
36
+
37
+ def marker_file() -> Path:
38
+ return get_settings().data_dir / "installed.json"
39
+
40
+
41
+ def read_marker() -> dict:
42
+ try:
43
+ return json.loads(marker_file().read_text())
44
+ except (OSError, ValueError):
45
+ return {}
46
+
47
+
48
+ def write_marker(**extra) -> None:
49
+ from ..db import utcnow
50
+ m = read_marker()
51
+ m.update({"version": __version__, "updated_at": utcnow().isoformat(), **extra})
52
+ m.setdefault("installed_at", m["updated_at"])
53
+ marker_file().parent.mkdir(parents=True, exist_ok=True)
54
+ marker_file().write_text(json.dumps(m, indent=2))
55
+
56
+
57
+ def dockerfile_sha() -> str:
58
+ return hashlib.sha256(resources.read("docker/Dockerfile").encode()).hexdigest()[:16]
59
+
60
+
61
+ @dataclass
62
+ class Step:
63
+ name: str
64
+ check: Callable[[], bool] | None # True = already done -> skip
65
+ apply: Callable[[], object]
66
+ critical: bool = True
67
+
68
+
69
+ def run_steps(steps: list[Step], *, dry_run: bool = False) -> bool:
70
+ """Run idempotent steps; print ✓ (done) / ↷ (already ok) / ✗ (failed)."""
71
+ ok_all = True
72
+ for st in steps:
73
+ try:
74
+ if st.check is not None and st.check():
75
+ console.print(f" [cyan]↷[/] {st.name} [dim](already ok)[/]")
76
+ continue
77
+ if dry_run:
78
+ console.print(f" [yellow]•[/] {st.name} [dim](would run)[/]")
79
+ continue
80
+ with console.status(f"{st.name}…"):
81
+ result = st.apply()
82
+ note = f" [dim]({result})[/]" if isinstance(result, str) and result else ""
83
+ console.print(f" [green]✓[/] {st.name}{note}")
84
+ except (AppError, Exception) as exc: # noqa: BLE001 - report every failure clearly
85
+ ok_all = False
86
+ msg = exc.message if isinstance(exc, AppError) else str(exc)
87
+ console.print(f" [red]✗ {st.name}: {msg}[/]")
88
+ if isinstance(exc, AppError) and exc.details.get("stderr"):
89
+ console.print(f" [dim]{exc.details['stderr'][-800:]}[/]")
90
+ if st.critical:
91
+ console.print("[red]Stopped. Fix the error above and run the command again "
92
+ "(it is safe to re-run).[/]")
93
+ return False
94
+ return ok_all
95
+
96
+
97
+ def die(msg: str, code: int = 1) -> None:
98
+ console.print(f"[red]✗ {msg}[/]")
99
+ raise typer.Exit(code)
100
+
101
+
102
+ __all__ = ["console", "require_root", "codegate_exec", "read_marker", "write_marker", "Step",
103
+ "run_steps", "die", "dockerfile_sha", "__version__"]
@@ -0,0 +1,136 @@
1
+ """`codegate doctor` - health checks with fix hints."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import shutil
6
+
7
+ import typer
8
+ from rich.table import Table
9
+
10
+ from .. import __version__
11
+ from ..config import env_file_path, get_settings
12
+ from ..system.shell import ok, run
13
+ from .common import console, read_marker
14
+
15
+
16
+ def _nosuid(path) -> tuple[bool, str]:
17
+ import psutil
18
+ from ..system.real import _mount_point
19
+ mp = _mount_point(path)
20
+ for part in psutil.disk_partitions(all=True):
21
+ if part.mountpoint == mp:
22
+ return "nosuid" in part.opts.split(","), f"{mp}: {part.opts}"
23
+ return False, mp
24
+
25
+
26
+ def doctor():
27
+ """Check every component and print how to fix problems."""
28
+ s = get_settings()
29
+ rows: list[tuple[str, bool | None, str]] = []
30
+
31
+ def check(name, fn, hint="", optional=False):
32
+ try:
33
+ res = fn()
34
+ good, info = (res if isinstance(res, tuple) else (bool(res), ""))
35
+ except Exception as exc: # noqa: BLE001
36
+ good, info = False, str(exc)[:120]
37
+ if not good and optional:
38
+ good = None # warning only
39
+ rows.append((name, good, info if good else (info + (" → " + hint if hint else "")).strip()))
40
+
41
+ check("Running as root", lambda: os.geteuid() == 0, "use sudo")
42
+ check("Config file", lambda: (env_file_path().is_file(), str(env_file_path())),
43
+ "run: sudo codegate setup")
44
+ check("Domain set", lambda: (s.domain not in ("", "localhost"), s.domain),
45
+ "set CODEGATE_DOMAIN")
46
+ def _admin_pw():
47
+ from ..db import session_scope
48
+ from .auth_cmd import admin_with_password_exists
49
+ with session_scope() as db:
50
+ return admin_with_password_exists(db), "admin with password login"
51
+ check("Default admin", _admin_pw, "sudo codegate setup (or: sudo codegate user passwd <admin>)")
52
+ m = read_marker()
53
+ check("Installed version", lambda: (bool(m), f"marker v{m.get('version', '-')}, package v{__version__}"),
54
+ "run: sudo codegate setup")
55
+
56
+ from ..auth import saml
57
+ check("SAML library", saml.saml_available, "sudo codegate setup (installs python3-saml)")
58
+ from ..db import get_setting, session_scope
59
+ with session_scope() as db:
60
+ sso_on = bool(get_setting(db, "sso_enabled"))
61
+ cfg = saml.sso_config(db)
62
+ check("AWS SSO login", lambda: (True, "on" if sso_on else "off (optional)"))
63
+ if sso_on:
64
+ check("SSO metadata loads",
65
+ lambda: (bool(saml.load_metadata(cfg["metadata_url"], cfg["metadata_file"])),
66
+ "IdP metadata OK"),
67
+ "check the URL in admin portal → Settings → Login")
68
+
69
+ check("Docker running", lambda: ok(["docker", "info"]), "sudo systemctl start docker")
70
+ check("Docker network", lambda: ok(["docker", "network", "inspect", s.docker_network]),
71
+ "sudo codegate setup")
72
+ check("Workspace image", lambda: ok(["docker", "image", "inspect", s.workspace_image]),
73
+ "sudo codegate image build")
74
+ check("nginx installed", lambda: shutil.which("nginx") is not None, "apt install nginx")
75
+ check("nginx config test", lambda: run(["nginx", "-t"], check=False).returncode == 0,
76
+ "sudo nginx -t (see the error)")
77
+ from . import nginx_setup
78
+ check("nginx integration", nginx_setup.is_integrated,
79
+ nginx_setup.manual_include_hint() or "sudo codegate setup")
80
+ check("HTTPS (443)", nginx_setup.has_ssl, "sudo certbot --nginx -d " + s.domain)
81
+ from . import ssh_setup
82
+ check("Host SSH blocked for workspace users", ssh_setup.is_applied, "sudo codegate setup")
83
+ check("/home mounted nosuid", lambda: _nosuid(s.home_root),
84
+ "optional extra hardening for sudo users: add nosuid to the /home mount in /etc/fstab",
85
+ optional=True)
86
+ from ..system import get_system
87
+ check("Disk quotas on /home", lambda: (get_system().quota_supported(), "hard limits"),
88
+ "not enabled: disk limit is soft (workspace stops when over). See README", optional=True)
89
+ check("Service active", lambda: ok(["systemctl", "is-active", "--quiet", "codegate"]),
90
+ "sudo codegate start ; sudo codegate logs")
91
+
92
+ def health():
93
+ import httpx
94
+ r = httpx.get(f"http://{s.listen_host}:{s.listen_port}{s.base_path}/healthz", timeout=3)
95
+ return r.status_code == 200, f"HTTP {r.status_code}"
96
+ check("Backend health", health, "sudo codegate logs")
97
+
98
+ def db_check():
99
+ from ..db import SCHEMA_VERSION, current_schema_version
100
+ v = current_schema_version()
101
+ return v == SCHEMA_VERSION, f"schema v{v} (expected v{SCHEMA_VERSION})"
102
+ check("Database", db_check, "sudo codegate migrate")
103
+
104
+ def consistency():
105
+ from sqlalchemy import select
106
+ from ..db import User, session_scope
107
+ problems = []
108
+ system = get_system()
109
+ with session_scope() as db:
110
+ for u in db.scalars(select(User).where(User.provisioned.is_(True))):
111
+ if not (s.users_nginx_dir / f"{u.username}.conf").exists():
112
+ problems.append(f"{u.username}: nginx route missing")
113
+ if system.container_status(u.username) == "missing":
114
+ problems.append(f"{u.username}: container missing")
115
+ return not problems, "; ".join(problems[:5]) or "all workspaces consistent"
116
+ check("Workspaces", consistency, "sudo codegate nginx sync / codegate user rebuild <user>")
117
+
118
+ du = shutil.disk_usage(str(s.home_root))
119
+ free_pct = du.free / du.total * 100
120
+ check("Free disk", lambda: (free_pct > 10, f"{free_pct:.0f}% free on {s.home_root}"),
121
+ "free up space / add disk")
122
+
123
+ t = Table(title=f"CodeGate doctor (v{__version__})")
124
+ t.add_column("Check")
125
+ t.add_column("", justify="center")
126
+ t.add_column("Details / fix")
127
+ bad = 0
128
+ for name, good, info in rows:
129
+ bad += 1 if good is False else 0
130
+ mark = "[green]✓[/]" if good else "[yellow]![/]" if good is None else "[red]✗[/]"
131
+ t.add_row(name, mark, info)
132
+ console.print(t)
133
+ if bad:
134
+ console.print(f"[yellow]{bad} problem(s) found.[/]")
135
+ raise typer.Exit(1)
136
+ console.print("[green]Everything looks good.[/]")