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.
- codegate/__init__.py +8 -0
- codegate/__main__.py +3 -0
- codegate/api/__init__.py +0 -0
- codegate/api/admin.py +457 -0
- codegate/api/deps.py +36 -0
- codegate/api/devproxy.py +132 -0
- codegate/api/public.py +371 -0
- codegate/app.py +115 -0
- codegate/auth/__init__.py +0 -0
- codegate/auth/csrf.py +43 -0
- codegate/auth/native.py +111 -0
- codegate/auth/passwords.py +88 -0
- codegate/auth/saml.py +222 -0
- codegate/auth/sessions.py +121 -0
- codegate/cli/__init__.py +0 -0
- codegate/cli/auth_cmd.py +168 -0
- codegate/cli/backup_cmd.py +114 -0
- codegate/cli/common.py +103 -0
- codegate/cli/doctor_cmd.py +136 -0
- codegate/cli/main.py +526 -0
- codegate/cli/nginx_setup.py +220 -0
- codegate/cli/setup_cmd.py +401 -0
- codegate/cli/ssh_setup.py +114 -0
- codegate/cli/upgrade_cmd.py +209 -0
- codegate/config.py +161 -0
- codegate/db.py +297 -0
- codegate/errors.py +122 -0
- codegate/jobs.py +133 -0
- codegate/pages.py +177 -0
- codegate/resources/__init__.py +20 -0
- codegate/resources/docker/Dockerfile +36 -0
- codegate/resources/nginx/codegate.conf.tmpl +51 -0
- codegate/resources/nginx/map.conf +5 -0
- codegate/resources/nginx/site.conf.tmpl +9 -0
- codegate/resources/nginx/user.conf.tmpl +19 -0
- codegate/resources/systemd/codegate-backup.service.tmpl +7 -0
- codegate/resources/systemd/codegate-backup.timer +10 -0
- codegate/resources/systemd/codegate.service.tmpl +20 -0
- codegate/static/admin/3rdpartylicenses.txt +614 -0
- codegate/static/admin/chunk-0r_p7pcB.js +672 -0
- codegate/static/admin/chunk-BoGqYCjO.js +1260 -0
- codegate/static/admin/chunk-BqiJ460N.js +1269 -0
- codegate/static/admin/chunk-BtoaIoDj.js +449 -0
- codegate/static/admin/chunk-CB4E-q63.js +255 -0
- codegate/static/admin/chunk-CMN75K3s.js +181 -0
- codegate/static/admin/chunk-CW_CPa20.js +106 -0
- codegate/static/admin/chunk-CcgsCK7w.js +393 -0
- codegate/static/admin/chunk-Cjwyuum6.js +375 -0
- codegate/static/admin/chunk-D6j6hnz3.js +1 -0
- codegate/static/admin/chunk-D9RytJgO.js +1 -0
- codegate/static/admin/chunk-DA6TldFU.js +35 -0
- codegate/static/admin/chunk-DFGdyoNb.js +1 -0
- codegate/static/admin/chunk-DXvCZ3pT.js +1 -0
- codegate/static/admin/chunk-DstgVdtz.js +27 -0
- codegate/static/admin/chunk-kPDFCwHP.js +102 -0
- codegate/static/admin/chunk-yikJ2ObQ.js +1 -0
- codegate/static/admin/favicon.ico +0 -0
- codegate/static/admin/index.html +14 -0
- codegate/static/admin/main-LWBML7JF.js +2347 -0
- codegate/static/admin/media/material-icons-JLIDJUWE.woff +0 -0
- codegate/static/admin/media/material-icons-LEZCGFVT.woff2 +0 -0
- codegate/static/admin/styles-YWRWGLKG.css +1 -0
- codegate/system/__init__.py +27 -0
- codegate/system/base.py +165 -0
- codegate/system/devdocker.py +90 -0
- codegate/system/fake.py +199 -0
- codegate/system/real.py +493 -0
- codegate/system/shell.py +40 -0
- codegate/users.py +262 -0
- codegate/workspace.py +355 -0
- inferyx_codegate-1.1.0.dist-info/METADATA +217 -0
- inferyx_codegate-1.1.0.dist-info/RECORD +74 -0
- inferyx_codegate-1.1.0.dist-info/WHEEL +4 -0
- inferyx_codegate-1.1.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Keep workspace users off the host.
|
|
2
|
+
|
|
3
|
+
Workspace users only need VS Code in their container. A host login (or even
|
|
4
|
+
`ssh -N` port forwarding) would let them reach other users' code-server ports on
|
|
5
|
+
127.0.0.1, which nginx normally guards. So:
|
|
6
|
+
|
|
7
|
+
- every Linux user CodeGate creates gets /usr/sbin/nologin and joins `login_group`
|
|
8
|
+
- a NEW sshd drop-in file denies that group (existing sshd files are not edited)
|
|
9
|
+
|
|
10
|
+
Users linked from existing host accounts are left alone.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import grp
|
|
15
|
+
import shutil
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from sqlalchemy import select
|
|
19
|
+
|
|
20
|
+
from ..config import get_settings
|
|
21
|
+
from ..system.shell import run
|
|
22
|
+
|
|
23
|
+
SSHD_MAIN = Path("/etc/ssh/sshd_config")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def dropin_text() -> str:
|
|
27
|
+
g = get_settings().login_group
|
|
28
|
+
return ("# Managed by CodeGate - DO NOT EDIT\n"
|
|
29
|
+
"# Workspace users get VS Code only: no SSH login or port forwarding on the host.\n"
|
|
30
|
+
f"DenyGroups {g}\n")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _sshd() -> str | None:
|
|
34
|
+
return shutil.which("sshd") or ("/usr/sbin/sshd" if Path("/usr/sbin/sshd").exists() else None)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _dropins_included() -> bool:
|
|
38
|
+
try:
|
|
39
|
+
text = SSHD_MAIN.read_text()
|
|
40
|
+
except OSError:
|
|
41
|
+
return False
|
|
42
|
+
d = str(get_settings().sshd_dropin.parent)
|
|
43
|
+
return any(line.strip().startswith("Include") and d in line for line in text.splitlines())
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _effective() -> bool:
|
|
47
|
+
sshd = _sshd()
|
|
48
|
+
if not sshd:
|
|
49
|
+
return True # no sshd -> nothing to block
|
|
50
|
+
out = run([sshd, "-T"], check=False).stdout.lower()
|
|
51
|
+
g = get_settings().login_group.lower()
|
|
52
|
+
return any(line.startswith("denygroups") and g in line.split()[1:] for line in out.splitlines())
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _users_to_restrict() -> list[str]:
|
|
56
|
+
from ..db import User, session_scope
|
|
57
|
+
with session_scope() as db:
|
|
58
|
+
return [u.username for u in db.scalars(select(User).where(
|
|
59
|
+
User.uid.is_not(None), User.linked_existing.is_(False)))]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _user_restricted(username: str) -> bool:
|
|
63
|
+
import pwd
|
|
64
|
+
s = get_settings()
|
|
65
|
+
try:
|
|
66
|
+
pw = pwd.getpwnam(username)
|
|
67
|
+
members = grp.getgrnam(s.login_group).gr_mem
|
|
68
|
+
except KeyError:
|
|
69
|
+
return True # no such host user -> nothing to do
|
|
70
|
+
return pw.pw_shell.endswith("nologin") and username in members
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def is_applied() -> bool:
|
|
74
|
+
s = get_settings()
|
|
75
|
+
if not s.sshd_dropin.is_file() or s.sshd_dropin.read_text() != dropin_text():
|
|
76
|
+
return False
|
|
77
|
+
return _effective() and all(_user_restricted(u) for u in _users_to_restrict())
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def apply() -> str:
|
|
81
|
+
from ..system import get_system
|
|
82
|
+
s = get_settings()
|
|
83
|
+
system = get_system()
|
|
84
|
+
users = _users_to_restrict()
|
|
85
|
+
for u in users:
|
|
86
|
+
system.restrict_host_login(u)
|
|
87
|
+
if not _sshd():
|
|
88
|
+
return f"sshd not installed; {len(users)} user(s) set to nologin"
|
|
89
|
+
if not _dropins_included():
|
|
90
|
+
raise RuntimeError(f"{SSHD_MAIN} has no 'Include {s.sshd_dropin.parent}/*.conf' line. "
|
|
91
|
+
"CodeGate does not edit it; add that line (Ubuntu has it by default) "
|
|
92
|
+
"and re-run setup")
|
|
93
|
+
try:
|
|
94
|
+
grp.getgrnam(s.login_group)
|
|
95
|
+
except KeyError:
|
|
96
|
+
run(["groupadd", "--system", s.login_group])
|
|
97
|
+
old = s.sshd_dropin.read_text() if s.sshd_dropin.exists() else None
|
|
98
|
+
s.sshd_dropin.parent.mkdir(parents=True, exist_ok=True)
|
|
99
|
+
s.sshd_dropin.write_text(dropin_text())
|
|
100
|
+
s.sshd_dropin.chmod(0o644)
|
|
101
|
+
test = run([_sshd(), "-t"], check=False)
|
|
102
|
+
if test.returncode != 0:
|
|
103
|
+
if old is None:
|
|
104
|
+
s.sshd_dropin.unlink()
|
|
105
|
+
else:
|
|
106
|
+
s.sshd_dropin.write_text(old)
|
|
107
|
+
raise RuntimeError(f"sshd -t failed (rolled back): {test.stderr[-400:]}")
|
|
108
|
+
# Ubuntu names the unit "ssh"; others "sshd"
|
|
109
|
+
if run(["systemctl", "reload", "ssh"], check=False).returncode != 0:
|
|
110
|
+
run(["systemctl", "reload", "sshd"], check=False)
|
|
111
|
+
if not _effective():
|
|
112
|
+
raise RuntimeError("DenyGroups not active in `sshd -T`; check your sshd_config ordering")
|
|
113
|
+
return f"SSH denied for group {s.login_group}; {len(users)} user(s) set to nologin"
|
|
114
|
+
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""`codegate upgrade` with automatic backup and rollback.
|
|
2
|
+
|
|
3
|
+
Flow:
|
|
4
|
+
1. backup DB/config/nginx + snapshot of the currently installed Python package
|
|
5
|
+
2. pip install the new version
|
|
6
|
+
3. run `codegate post-upgrade` with the NEW code (migrations, nginx sync,
|
|
7
|
+
image rebuild if Dockerfile changed, rolling container restart, health check)
|
|
8
|
+
4. if step 2 or 3 fails -> restore package snapshot + DB/config, restart, report
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import io
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import tarfile
|
|
16
|
+
from importlib import metadata
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import typer
|
|
20
|
+
|
|
21
|
+
from .. import LEGACY_PACKAGE_NAMES, PACKAGE_NAME, __version__
|
|
22
|
+
from ..config import get_settings
|
|
23
|
+
from ..system.shell import run
|
|
24
|
+
from .backup_cmd import create_backup, restore_backup
|
|
25
|
+
from .common import codegate_exec, console, die, require_root
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _installed_dist():
|
|
29
|
+
"""Our installed distribution (current name, or a legacy name that really is ours)."""
|
|
30
|
+
for name in (PACKAGE_NAME, *LEGACY_PACKAGE_NAMES):
|
|
31
|
+
try:
|
|
32
|
+
dist = metadata.distribution(name)
|
|
33
|
+
except metadata.PackageNotFoundError:
|
|
34
|
+
continue
|
|
35
|
+
if any(str(f).replace("\\", "/").endswith("codegate/cli/upgrade_cmd.py")
|
|
36
|
+
for f in (dist.files or [])):
|
|
37
|
+
return dist
|
|
38
|
+
raise RuntimeError(f"{PACKAGE_NAME} is not installed with pip in this environment")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _package_snapshot(dest: Path) -> Path:
|
|
42
|
+
"""Tar the installed codegate package + dist-info so we can restore it offline."""
|
|
43
|
+
dist = _installed_dist()
|
|
44
|
+
files = [Path(dist.locate_file(f)) for f in (dist.files or [])]
|
|
45
|
+
site = Path(dist.locate_file(""))
|
|
46
|
+
out = dest / f"codegate-pkg-{__version__}.tar.gz"
|
|
47
|
+
with tarfile.open(out, "w:gz") as tar:
|
|
48
|
+
for f in files:
|
|
49
|
+
if f.exists() and f.is_file():
|
|
50
|
+
try:
|
|
51
|
+
tar.add(f, arcname=str(f.resolve().relative_to(site.resolve())))
|
|
52
|
+
except ValueError:
|
|
53
|
+
tar.add(f, arcname=f"__abs__{f.resolve()}")
|
|
54
|
+
meta = str(site.resolve()).encode()
|
|
55
|
+
info = tarfile.TarInfo("SITE")
|
|
56
|
+
info.size = len(meta)
|
|
57
|
+
tar.addfile(info, io.BytesIO(meta))
|
|
58
|
+
return out
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _restore_package(snapshot: Path) -> None:
|
|
62
|
+
subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", PACKAGE_NAME,
|
|
63
|
+
*LEGACY_PACKAGE_NAMES], capture_output=True)
|
|
64
|
+
with tarfile.open(snapshot, "r:gz") as tar:
|
|
65
|
+
site = Path(tar.extractfile("SITE").read().decode())
|
|
66
|
+
for m in tar.getmembers():
|
|
67
|
+
if m.name == "SITE" or not m.isfile():
|
|
68
|
+
continue
|
|
69
|
+
target = Path(m.name[len("__abs__"):]) if m.name.startswith("__abs__") else site / m.name
|
|
70
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
71
|
+
target.write_bytes(tar.extractfile(m).read())
|
|
72
|
+
target.chmod(m.mode)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def upgrade(
|
|
76
|
+
version: str = typer.Option(None, help="Target version (default: latest)"),
|
|
77
|
+
wheel: Path = typer.Option(None, help="Upgrade from a local .whl file instead of PyPI/index"),
|
|
78
|
+
dry_run: bool = typer.Option(False, help="Show what would happen, change nothing"),
|
|
79
|
+
yes: bool = typer.Option(False, "--yes", "-y"),
|
|
80
|
+
index_url: str = typer.Option(None, help="Custom pip index URL (private repo)"),
|
|
81
|
+
):
|
|
82
|
+
"""Upgrade CodeGate safely (backup → install → migrate → health check → rollback on failure)."""
|
|
83
|
+
require_root()
|
|
84
|
+
s = get_settings()
|
|
85
|
+
pkg = f"{PACKAGE_NAME}[saml]"
|
|
86
|
+
target = f"{wheel}[saml]" if wheel else (f"{pkg}=={version}" if version else pkg)
|
|
87
|
+
console.rule(f"[bold cyan]CodeGate upgrade (current v{__version__})")
|
|
88
|
+
console.print(f"Target: [bold]{target}[/]")
|
|
89
|
+
plan = ["Backup DB, config, nginx files", "Snapshot installed package (for rollback)",
|
|
90
|
+
f"pip install --upgrade {target}", "Run DB migrations", "Re-sync nginx routes",
|
|
91
|
+
"Rebuild workspace image if Dockerfile changed + restart containers one by one",
|
|
92
|
+
"Restart service + health check", "Rollback automatically if anything fails"]
|
|
93
|
+
for i, p in enumerate(plan, 1):
|
|
94
|
+
console.print(f" {i}. {p}")
|
|
95
|
+
if dry_run:
|
|
96
|
+
console.print("[yellow]Dry run: nothing changed.[/]")
|
|
97
|
+
raise typer.Exit(0)
|
|
98
|
+
if not yes and not typer.confirm("Continue?", default=True):
|
|
99
|
+
raise typer.Exit(0)
|
|
100
|
+
|
|
101
|
+
backup = create_backup(label="pre-upgrade")
|
|
102
|
+
console.print(f" [green]✓[/] backup: {backup}")
|
|
103
|
+
snap = _package_snapshot(s.backup_dir)
|
|
104
|
+
console.print(f" [green]✓[/] package snapshot: {snap}")
|
|
105
|
+
|
|
106
|
+
old_name = _installed_dist().metadata["Name"]
|
|
107
|
+
if old_name.lower() != PACKAGE_NAME:
|
|
108
|
+
# renamed distribution: remove the old one first (both own the same files)
|
|
109
|
+
subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", old_name],
|
|
110
|
+
capture_output=True)
|
|
111
|
+
console.print(f" [green]✓[/] removed old package name '{old_name}'")
|
|
112
|
+
cmd = [sys.executable, "-m", "pip", "install", "--upgrade", target]
|
|
113
|
+
if index_url:
|
|
114
|
+
cmd += ["--index-url", index_url]
|
|
115
|
+
with console.status("installing new version…"):
|
|
116
|
+
proc = subprocess.run(cmd, capture_output=True, text=True)
|
|
117
|
+
if proc.returncode != 0:
|
|
118
|
+
console.print(f"[red]✗ pip install failed[/]\n[dim]{proc.stderr[-1500:]}[/]")
|
|
119
|
+
if old_name.lower() != PACKAGE_NAME:
|
|
120
|
+
_restore_package(snap)
|
|
121
|
+
console.print("[green]Nothing was changed (still on the old version).[/]")
|
|
122
|
+
raise typer.Exit(1)
|
|
123
|
+
new_ver = subprocess.run([codegate_exec(), "version", "--short"], capture_output=True,
|
|
124
|
+
text=True).stdout.strip()
|
|
125
|
+
if new_ver == __version__:
|
|
126
|
+
console.print(f"[green]Already on the latest version v{__version__}.[/] "
|
|
127
|
+
"Running post-upgrade checks anyway.")
|
|
128
|
+
else:
|
|
129
|
+
console.print(f" [green]✓[/] installed v{new_ver}")
|
|
130
|
+
|
|
131
|
+
post = subprocess.run([codegate_exec(), "post-upgrade", "--from-version", __version__])
|
|
132
|
+
if post.returncode == 0:
|
|
133
|
+
console.rule(f"[bold green]Upgraded to v{new_ver or __version__}")
|
|
134
|
+
return
|
|
135
|
+
|
|
136
|
+
console.print("[red]✗ post-upgrade failed - rolling back…[/]")
|
|
137
|
+
try:
|
|
138
|
+
run(["systemctl", "stop", "codegate"], check=False)
|
|
139
|
+
_restore_package(snap)
|
|
140
|
+
restore_backup(backup)
|
|
141
|
+
run(["nginx", "-t"], check=False)
|
|
142
|
+
run(["systemctl", "reload", "nginx"], check=False)
|
|
143
|
+
run(["systemctl", "start", "codegate"], check=False)
|
|
144
|
+
console.print(f"[yellow]Rolled back to v{__version__}. Backup kept at {backup}[/]")
|
|
145
|
+
except Exception as exc: # noqa: BLE001
|
|
146
|
+
die(f"Rollback failed: {exc}. Restore manually: sudo codegate restore {backup}")
|
|
147
|
+
raise typer.Exit(1)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def post_upgrade(from_version: str = typer.Option("", help="Previous version")):
|
|
151
|
+
"""(internal) Steps that must run with the NEW code after pip install."""
|
|
152
|
+
require_root()
|
|
153
|
+
try:
|
|
154
|
+
_post_upgrade(from_version)
|
|
155
|
+
except typer.Exit:
|
|
156
|
+
raise
|
|
157
|
+
except Exception as exc: # noqa: BLE001 - report cleanly, parent process rolls back
|
|
158
|
+
msg = getattr(exc, "message", str(exc))
|
|
159
|
+
details = getattr(exc, "details", {}) or {}
|
|
160
|
+
console.print(f" [red]✗ {msg}[/]")
|
|
161
|
+
if details.get("stderr"):
|
|
162
|
+
console.print(f" [dim]{details['stderr'][-600:]}[/]")
|
|
163
|
+
raise typer.Exit(1)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _post_upgrade(from_version: str) -> None:
|
|
167
|
+
from ..db import migrate, session_scope
|
|
168
|
+
from ..workspace import nginx_sync_all, rebuild
|
|
169
|
+
from .common import dockerfile_sha, read_marker, write_marker
|
|
170
|
+
from .setup_cmd import _unit_text, build_workspace_image, wait_healthy
|
|
171
|
+
from sqlalchemy import select
|
|
172
|
+
from ..db import User
|
|
173
|
+
from ..system import get_system
|
|
174
|
+
|
|
175
|
+
s = get_settings()
|
|
176
|
+
old, new = migrate()
|
|
177
|
+
console.print(f" [green]✓[/] database schema v{old} -> v{new}")
|
|
178
|
+
|
|
179
|
+
unit = Path("/etc/systemd/system/codegate.service")
|
|
180
|
+
if unit.exists() and unit.read_text() != _unit_text():
|
|
181
|
+
unit.write_text(_unit_text())
|
|
182
|
+
run(["systemctl", "daemon-reload"])
|
|
183
|
+
console.print(" [green]✓[/] systemd unit updated")
|
|
184
|
+
|
|
185
|
+
from . import nginx_setup, ssh_setup
|
|
186
|
+
if not ssh_setup.is_applied():
|
|
187
|
+
console.print(f" [green]✓[/] {ssh_setup.apply()}")
|
|
188
|
+
nginx_setup.integrate() # rewrites codegate.conf from the new templates (with rollback)
|
|
189
|
+
with session_scope() as db:
|
|
190
|
+
res = nginx_sync_all(db)
|
|
191
|
+
console.print(f" [green]✓[/] nginx routes synced ({len(res['written'])} users)")
|
|
192
|
+
|
|
193
|
+
marker = read_marker()
|
|
194
|
+
if marker.get("dockerfile_sha") != dockerfile_sha():
|
|
195
|
+
console.print(" workspace image changed → rebuilding")
|
|
196
|
+
build_workspace_image()
|
|
197
|
+
system = get_system()
|
|
198
|
+
with session_scope() as db:
|
|
199
|
+
for u in db.scalars(select(User).where(User.provisioned.is_(True))):
|
|
200
|
+
was_running = system.container_status(u.username) == "running"
|
|
201
|
+
rebuild(db, u, "upgrade")
|
|
202
|
+
if not was_running:
|
|
203
|
+
system.container_stop(u.username)
|
|
204
|
+
console.print(f" [green]✓[/] {u.username} recreated")
|
|
205
|
+
|
|
206
|
+
run(["systemctl", "restart", "codegate"])
|
|
207
|
+
console.print(f" [green]✓[/] service {wait_healthy()}")
|
|
208
|
+
write_marker(dockerfile_sha=dockerfile_sha(), previous_version=from_version)
|
|
209
|
+
_ = s
|
codegate/config.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Configuration.
|
|
2
|
+
|
|
3
|
+
All settings come from environment variables prefixed with ``CODEGATE_`` or from
|
|
4
|
+
the env file (default ``/etc/codegate/codegate.env``; override with
|
|
5
|
+
``CODEGATE_ENV_FILE``).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from functools import lru_cache
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from pydantic import Field, field_validator
|
|
14
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
15
|
+
|
|
16
|
+
DEFAULT_ENV_FILE = "/etc/codegate/codegate.env"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def env_file_path() -> Path:
|
|
20
|
+
return Path(os.environ.get("CODEGATE_ENV_FILE", DEFAULT_ENV_FILE))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Settings(BaseSettings):
|
|
24
|
+
model_config = SettingsConfigDict(env_prefix="CODEGATE_", extra="ignore")
|
|
25
|
+
|
|
26
|
+
# --- public URL -------------------------------------------------------
|
|
27
|
+
domain: str = "localhost"
|
|
28
|
+
base_path: str = "/codeapp"
|
|
29
|
+
public_scheme: str = "https"
|
|
30
|
+
|
|
31
|
+
# --- backend server ---------------------------------------------------
|
|
32
|
+
listen_host: str = "127.0.0.1"
|
|
33
|
+
listen_port: int = 8700
|
|
34
|
+
secret_key: str = ""
|
|
35
|
+
|
|
36
|
+
# --- storage ----------------------------------------------------------
|
|
37
|
+
data_dir: Path = Path("/var/lib/codegate")
|
|
38
|
+
log_dir: Path = Path("/var/log/codegate")
|
|
39
|
+
home_root: Path = Path("/home")
|
|
40
|
+
shared_dir: Path = Path("/srv/codegate/shared")
|
|
41
|
+
|
|
42
|
+
# --- SSO (IAM Identity Center, SAML 2.0) ------------------------------
|
|
43
|
+
# Normally set in the admin portal (Settings -> Login, stored in the DB). These env values
|
|
44
|
+
# are only the initial/fallback values.
|
|
45
|
+
saml_idp_metadata_url: str = ""
|
|
46
|
+
saml_idp_metadata_file: str = ""
|
|
47
|
+
saml_email_attribute: str = "email"
|
|
48
|
+
saml_sp_entity_id: str = "" # defaults to <public_url>/saml/metadata
|
|
49
|
+
|
|
50
|
+
# --- default admin email(s); also become admin on first SSO login -----
|
|
51
|
+
admin_emails: str = ""
|
|
52
|
+
|
|
53
|
+
# --- sessions ----------------------------------------------------------
|
|
54
|
+
session_hours: int = 8
|
|
55
|
+
idle_session_minutes: int = 60
|
|
56
|
+
cookie_name: str = "codegate_session"
|
|
57
|
+
|
|
58
|
+
# --- workspaces ---------------------------------------------------------
|
|
59
|
+
port_range_start: int = 9100
|
|
60
|
+
port_range_end: int = 9999
|
|
61
|
+
uid_start: int = 20000
|
|
62
|
+
workspace_image: str = "codegate-workspace:latest"
|
|
63
|
+
docker_network: str = "codegate-net"
|
|
64
|
+
docker_subnet: str = "172.30.0.0/16"
|
|
65
|
+
container_prefix: str = "codegate-"
|
|
66
|
+
shared_group: str = "codegate-shared"
|
|
67
|
+
# every Linux user CodeGate creates joins this group; sshd denies it (no host login)
|
|
68
|
+
login_group: str = "codegate-users"
|
|
69
|
+
sshd_dropin: Path = Path("/etc/ssh/sshd_config.d/10-codegate.conf")
|
|
70
|
+
|
|
71
|
+
# --- nginx ---------------------------------------------------------------
|
|
72
|
+
nginx_dir: Path = Path("/etc/nginx/codegate")
|
|
73
|
+
nginx_reload_cmd: str = "systemctl reload nginx"
|
|
74
|
+
nginx_test_cmd: str = "nginx -t"
|
|
75
|
+
|
|
76
|
+
# --- background jobs -------------------------------------------------------
|
|
77
|
+
reaper_interval_seconds: int = 60
|
|
78
|
+
usage_interval_seconds: int = 300
|
|
79
|
+
|
|
80
|
+
# --- development ---------------------------------------------------------
|
|
81
|
+
# dev_mode: simulated system layer (no docker/useradd/nginx). Login is the real login.
|
|
82
|
+
dev_mode: bool = False
|
|
83
|
+
# dev_docker (with dev_mode): run REAL code-server containers via local Docker and
|
|
84
|
+
# proxy /editor/<user>/ from the backend (stands in for nginx). Laptop only.
|
|
85
|
+
dev_docker: bool = False
|
|
86
|
+
|
|
87
|
+
@field_validator("base_path")
|
|
88
|
+
@classmethod
|
|
89
|
+
def _norm_base(cls, v: str) -> str:
|
|
90
|
+
v = "/" + v.strip("/")
|
|
91
|
+
return "" if v == "/" else v
|
|
92
|
+
|
|
93
|
+
# ---------------------------------------------------------------------
|
|
94
|
+
@property
|
|
95
|
+
def public_url(self) -> str:
|
|
96
|
+
return f"{self.public_scheme}://{self.domain}{self.base_path}"
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def sp_entity_id(self) -> str:
|
|
100
|
+
return self.saml_sp_entity_id or f"{self.public_url}/saml/metadata"
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def acs_url(self) -> str:
|
|
104
|
+
return f"{self.public_url}/saml/acs"
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def db_path(self) -> Path:
|
|
108
|
+
return self.data_dir / "codegate.db"
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def admin_email_list(self) -> list[str]:
|
|
112
|
+
return [e.strip().lower() for e in self.admin_emails.split(",") if e.strip()]
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def users_nginx_dir(self) -> Path:
|
|
116
|
+
return self.nginx_dir / "users"
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def backup_dir(self) -> Path:
|
|
120
|
+
return self.data_dir / "backups"
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def archive_dir(self) -> Path:
|
|
124
|
+
return self.data_dir / "archive"
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def etc_dir(self) -> Path:
|
|
128
|
+
"""Per-user generated passwd/group/sudoers files mounted into containers."""
|
|
129
|
+
return self.data_dir / "etc"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _load_env_file_into_environ() -> None:
|
|
133
|
+
path = env_file_path()
|
|
134
|
+
if not path.is_file():
|
|
135
|
+
return
|
|
136
|
+
try:
|
|
137
|
+
text = path.read_text()
|
|
138
|
+
except PermissionError:
|
|
139
|
+
return
|
|
140
|
+
for raw in text.splitlines():
|
|
141
|
+
line = raw.strip()
|
|
142
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
143
|
+
continue
|
|
144
|
+
key, _, value = line.partition("=")
|
|
145
|
+
key = key.strip()
|
|
146
|
+
value = value.strip().strip('"').strip("'")
|
|
147
|
+
os.environ.setdefault(key, value)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@lru_cache
|
|
151
|
+
def get_settings() -> Settings:
|
|
152
|
+
_load_env_file_into_environ()
|
|
153
|
+
return Settings()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def reset_settings_cache() -> None:
|
|
157
|
+
get_settings.cache_clear()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# keep Field importable for other modules that extend settings
|
|
161
|
+
__all__ = ["Settings", "get_settings", "reset_settings_cache", "env_file_path", "Field"]
|