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,220 @@
|
|
|
1
|
+
"""Integrate CodeGate into nginx without breaking existing sites.
|
|
2
|
+
|
|
3
|
+
- writes /etc/nginx/conf.d/codegate-map.conf (websocket map, http context)
|
|
4
|
+
- writes /etc/nginx/codegate/codegate.conf (locations for /codeapp)
|
|
5
|
+
- if no server block for the domain exists, creates /etc/nginx/sites-available/codegate
|
|
6
|
+
- existing nginx files are NEVER modified: if a server block for the domain already
|
|
7
|
+
exists, the admin adds `include /etc/nginx/codegate/codegate.conf;` to it by hand
|
|
8
|
+
(setup and doctor print the exact line and file).
|
|
9
|
+
Every change is backed up and rolled back if `nginx -t` fails.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
import shutil
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from .. import resources
|
|
18
|
+
from ..config import get_settings
|
|
19
|
+
from ..db import utcnow
|
|
20
|
+
from ..errors import NginxError
|
|
21
|
+
from ..system.shell import run
|
|
22
|
+
|
|
23
|
+
NGINX_ROOT = Path("/etc/nginx")
|
|
24
|
+
MAP_FILE = NGINX_ROOT / "conf.d" / "codegate-map.conf"
|
|
25
|
+
SITE_FILE = NGINX_ROOT / "sites-available" / "codegate"
|
|
26
|
+
SITE_LINK = NGINX_ROOT / "sites-enabled" / "codegate"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main_conf_path() -> Path:
|
|
30
|
+
return get_settings().nginx_dir / "codegate.conf"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def include_line() -> str:
|
|
34
|
+
return f"include {main_conf_path()};"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _candidate_files() -> list[Path]:
|
|
38
|
+
files: list[Path] = []
|
|
39
|
+
for d in ("sites-enabled", "conf.d"):
|
|
40
|
+
p = NGINX_ROOT / d
|
|
41
|
+
if p.is_dir():
|
|
42
|
+
files += [f.resolve() for f in sorted(p.iterdir()) if f.is_file() or f.is_symlink()]
|
|
43
|
+
nginx_conf = NGINX_ROOT / "nginx.conf"
|
|
44
|
+
if nginx_conf.is_file():
|
|
45
|
+
files.append(nginx_conf)
|
|
46
|
+
seen, out = set(), []
|
|
47
|
+
for f in files:
|
|
48
|
+
if f not in seen and f.exists() and f != MAP_FILE.resolve():
|
|
49
|
+
seen.add(f)
|
|
50
|
+
out.append(f)
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _server_blocks(text: str):
|
|
55
|
+
"""Yield (start, end) index of each `server { ... }` block (brace matching)."""
|
|
56
|
+
for m in re.finditer(r"(^|\n)\s*server\s*\{", text):
|
|
57
|
+
i = m.end()
|
|
58
|
+
depth = 1
|
|
59
|
+
while i < len(text) and depth:
|
|
60
|
+
if text[i] == "{":
|
|
61
|
+
depth += 1
|
|
62
|
+
elif text[i] == "}":
|
|
63
|
+
depth -= 1
|
|
64
|
+
i += 1
|
|
65
|
+
yield m.start(), i
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def find_server_block(domain: str) -> tuple[Path, int, int, bool] | None:
|
|
69
|
+
"""Find the server block serving `domain`. Prefers the 443/ssl one.
|
|
70
|
+
Returns (file, start, end, is_ssl)."""
|
|
71
|
+
best = None
|
|
72
|
+
for f in _candidate_files():
|
|
73
|
+
try:
|
|
74
|
+
text = f.read_text()
|
|
75
|
+
except OSError:
|
|
76
|
+
continue
|
|
77
|
+
for start, end in _server_blocks(text):
|
|
78
|
+
block = text[start:end]
|
|
79
|
+
names = re.findall(r"server_name\s+([^;]+);", block)
|
|
80
|
+
if not any(domain in n.split() for n in names):
|
|
81
|
+
continue
|
|
82
|
+
is_ssl = bool(re.search(r"listen\s+[^;]*443", block))
|
|
83
|
+
# skip pure "return 301 https" redirect blocks when an ssl block exists
|
|
84
|
+
if best is None or (is_ssl and not best[3]):
|
|
85
|
+
best = (f, start, end, is_ssl)
|
|
86
|
+
return best
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _is_own_site(path: Path) -> bool:
|
|
90
|
+
return path == SITE_FILE.resolve()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def manual_include_target() -> Path | None:
|
|
94
|
+
"""The existing (not CodeGate-owned) nginx file whose server block still needs the
|
|
95
|
+
include line. CodeGate never edits that file; the admin adds the line by hand."""
|
|
96
|
+
s = get_settings()
|
|
97
|
+
found = find_server_block(s.domain)
|
|
98
|
+
if not found or _is_own_site(found[0]):
|
|
99
|
+
return None
|
|
100
|
+
f, start, end, _ = found
|
|
101
|
+
return None if include_line() in f.read_text()[start:end] else f
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def manual_include_hint() -> str:
|
|
105
|
+
f = manual_include_target()
|
|
106
|
+
if f is None:
|
|
107
|
+
return ""
|
|
108
|
+
return (f"Add this line inside the server {{ }} block for {get_settings().domain} in {f}:\n"
|
|
109
|
+
f" {include_line()}\n"
|
|
110
|
+
f" then run: sudo nginx -t && sudo systemctl reload nginx")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def is_integrated() -> bool:
|
|
114
|
+
s = get_settings()
|
|
115
|
+
found = find_server_block(s.domain)
|
|
116
|
+
if not found or not main_conf_path().exists() or not MAP_FILE.exists():
|
|
117
|
+
return False
|
|
118
|
+
f, start, end, _ = found
|
|
119
|
+
return include_line() in f.read_text()[start:end]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class NginxTxn:
|
|
123
|
+
"""Backup files; restore them all if anything fails."""
|
|
124
|
+
|
|
125
|
+
def __init__(self) -> None:
|
|
126
|
+
self.backups: dict[Path, bytes | None] = {}
|
|
127
|
+
self.stamp = f"{utcnow():%Y%m%d%H%M%S}"
|
|
128
|
+
|
|
129
|
+
def touch(self, path: Path) -> None:
|
|
130
|
+
if path not in self.backups:
|
|
131
|
+
self.backups[path] = path.read_bytes() if path.exists() else None
|
|
132
|
+
if path.exists():
|
|
133
|
+
shutil.copy2(path, f"{path}.codegate-bak-{self.stamp}")
|
|
134
|
+
|
|
135
|
+
def write(self, path: Path, content: str) -> None:
|
|
136
|
+
self.touch(path)
|
|
137
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
138
|
+
path.write_text(content)
|
|
139
|
+
|
|
140
|
+
def rollback(self) -> None:
|
|
141
|
+
for path, data in self.backups.items():
|
|
142
|
+
if data is None:
|
|
143
|
+
if path.exists() or path.is_symlink():
|
|
144
|
+
path.unlink()
|
|
145
|
+
else:
|
|
146
|
+
path.write_bytes(data)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def integrate(create_site_if_missing: bool = True) -> str:
|
|
150
|
+
"""Write CodeGate's own nginx files. Existing nginx files are never modified:
|
|
151
|
+
if a server block for the domain already exists, the admin adds one include line."""
|
|
152
|
+
s = get_settings()
|
|
153
|
+
txn = NginxTxn()
|
|
154
|
+
try:
|
|
155
|
+
txn.write(MAP_FILE, resources.read("nginx/map.conf"))
|
|
156
|
+
txn.write(main_conf_path(), resources.render(
|
|
157
|
+
"nginx/codegate.conf.tmpl", domain=s.domain, base=s.base_path,
|
|
158
|
+
backend=f"{s.listen_host}:{s.listen_port}", users_dir=s.users_nginx_dir))
|
|
159
|
+
s.users_nginx_dir.mkdir(parents=True, exist_ok=True)
|
|
160
|
+
|
|
161
|
+
found = find_server_block(s.domain)
|
|
162
|
+
if found and _is_own_site(found[0]):
|
|
163
|
+
what = f"CodeGate site {SITE_FILE}"
|
|
164
|
+
elif found:
|
|
165
|
+
what = (f"included in {found[0]}" if manual_include_target() is None
|
|
166
|
+
else "ACTION NEEDED: " + manual_include_hint())
|
|
167
|
+
elif create_site_if_missing:
|
|
168
|
+
txn.write(SITE_FILE, resources.render("nginx/site.conf.tmpl", domain=s.domain,
|
|
169
|
+
nginx_dir=s.nginx_dir))
|
|
170
|
+
txn.touch(SITE_LINK)
|
|
171
|
+
if not SITE_LINK.exists():
|
|
172
|
+
SITE_LINK.symlink_to(SITE_FILE)
|
|
173
|
+
what = f"new site {SITE_FILE}"
|
|
174
|
+
else:
|
|
175
|
+
raise NginxError(f"No nginx server block found for {s.domain}")
|
|
176
|
+
|
|
177
|
+
test = run(s.nginx_test_cmd, check=False)
|
|
178
|
+
if test.returncode != 0:
|
|
179
|
+
raise NginxError("nginx -t failed after CodeGate changes (rolled back)",
|
|
180
|
+
details={"stderr": test.stderr[-1500:]})
|
|
181
|
+
run(s.nginx_reload_cmd)
|
|
182
|
+
return what
|
|
183
|
+
except Exception:
|
|
184
|
+
txn.rollback()
|
|
185
|
+
raise
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def certbot_allowed() -> bool:
|
|
189
|
+
"""certbot --nginx edits the server block, so only run it on CodeGate's own site."""
|
|
190
|
+
found = find_server_block(get_settings().domain)
|
|
191
|
+
return found is None or _is_own_site(found[0])
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def has_ssl() -> bool:
|
|
195
|
+
found = find_server_block(get_settings().domain)
|
|
196
|
+
return bool(found and found[3])
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def remove() -> None:
|
|
200
|
+
"""Undo integration (used by `codegate uninstall`). Deletes only CodeGate's own files."""
|
|
201
|
+
s = get_settings()
|
|
202
|
+
users = [f for f in _candidate_files()
|
|
203
|
+
if not _is_own_site(f) and include_line() in f.read_text()]
|
|
204
|
+
if users:
|
|
205
|
+
raise NginxError("CodeGate's nginx files are still included by "
|
|
206
|
+
+ ", ".join(str(f) for f in users)
|
|
207
|
+
+ f". Remove the line '{include_line()}' there, reload nginx, "
|
|
208
|
+
"then run uninstall again.")
|
|
209
|
+
txn = NginxTxn()
|
|
210
|
+
try:
|
|
211
|
+
for p in (SITE_LINK, SITE_FILE, MAP_FILE, main_conf_path()):
|
|
212
|
+
if p.exists() or p.is_symlink():
|
|
213
|
+
txn.touch(p)
|
|
214
|
+
p.unlink()
|
|
215
|
+
if run(s.nginx_test_cmd, check=False).returncode != 0:
|
|
216
|
+
raise NginxError("nginx -t failed while removing CodeGate (rolled back)")
|
|
217
|
+
run(s.nginx_reload_cmd)
|
|
218
|
+
except Exception:
|
|
219
|
+
txn.rollback()
|
|
220
|
+
raise
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
"""`codegate setup` - idempotent installer for Ubuntu 24.04.
|
|
2
|
+
|
|
3
|
+
Every step checks first and skips what is already in place, so it is safe to
|
|
4
|
+
run again (repair mode). Existing Docker / nginx sites / code-server / Linux
|
|
5
|
+
users are detected and reused, never overwritten.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import platform
|
|
11
|
+
import secrets
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import typer
|
|
18
|
+
from rich.prompt import Confirm, Prompt
|
|
19
|
+
from rich.table import Table
|
|
20
|
+
|
|
21
|
+
from .. import __version__, resources
|
|
22
|
+
from ..config import env_file_path, get_settings, reset_settings_cache
|
|
23
|
+
from ..system.shell import ok, run
|
|
24
|
+
from . import nginx_setup, ssh_setup
|
|
25
|
+
from .common import (Step, codegate_exec, console, die, dockerfile_sha, read_marker, require_root,
|
|
26
|
+
run_steps, write_marker)
|
|
27
|
+
|
|
28
|
+
APT_PACKAGES = {
|
|
29
|
+
# command/package to test -> apt package
|
|
30
|
+
"nginx": "nginx",
|
|
31
|
+
"setquota": "quota",
|
|
32
|
+
"iptables": "iptables",
|
|
33
|
+
"pkg-config": "pkg-config",
|
|
34
|
+
"certbot": "certbot python3-certbot-nginx",
|
|
35
|
+
}
|
|
36
|
+
LIB_PACKAGES = ["libxml2-dev", "libxmlsec1-dev", "libxmlsec1-openssl"]
|
|
37
|
+
|
|
38
|
+
ENV_KEYS = [
|
|
39
|
+
("CODEGATE_DOMAIN", "Domain (e.g. code.example.com)", None),
|
|
40
|
+
("CODEGATE_BASE_PATH", "Base path", "/codeapp"),
|
|
41
|
+
("CODEGATE_ADMIN_EMAILS", "Default admin email", None),
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# ------------------------------------------------------------------ helpers
|
|
46
|
+
def _dpkg_installed(pkg: str) -> bool:
|
|
47
|
+
return ok(["dpkg", "-s", pkg])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _apt_install(pkgs: list[str]) -> str:
|
|
51
|
+
env = {**os.environ, "DEBIAN_FRONTEND": "noninteractive"}
|
|
52
|
+
subprocess.run(["apt-get", "update", "-q"], check=True, env=env, capture_output=True)
|
|
53
|
+
proc = subprocess.run(["apt-get", "install", "-y", "-q", *pkgs], env=env, capture_output=True,
|
|
54
|
+
text=True)
|
|
55
|
+
if proc.returncode != 0:
|
|
56
|
+
raise RuntimeError(f"apt-get install failed: {proc.stderr[-800:]}")
|
|
57
|
+
return " ".join(pkgs)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _read_env() -> dict[str, str]:
|
|
61
|
+
path = env_file_path()
|
|
62
|
+
data: dict[str, str] = {}
|
|
63
|
+
if path.is_file():
|
|
64
|
+
for line in path.read_text().splitlines():
|
|
65
|
+
if "=" in line and not line.strip().startswith("#"):
|
|
66
|
+
k, _, v = line.partition("=")
|
|
67
|
+
data[k.strip()] = v.strip().strip('"')
|
|
68
|
+
return data
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _write_env(data: dict[str, str]) -> None:
|
|
72
|
+
path = env_file_path()
|
|
73
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
lines = ["# CodeGate configuration (edit, then: sudo codegate restart)"]
|
|
75
|
+
lines += [f'{k}="{v}"' for k, v in data.items()]
|
|
76
|
+
tmp = path.with_suffix(".tmp")
|
|
77
|
+
tmp.write_text("\n".join(lines) + "\n")
|
|
78
|
+
os.chmod(tmp, 0o600)
|
|
79
|
+
os.replace(tmp, path)
|
|
80
|
+
for k, v in data.items():
|
|
81
|
+
os.environ[k] = v
|
|
82
|
+
reset_settings_cache()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _detect_code_server() -> list[str]:
|
|
86
|
+
found = []
|
|
87
|
+
try:
|
|
88
|
+
proc = run(["systemctl", "list-units", "--all", "--no-legend", "--plain", "code-server*"],
|
|
89
|
+
check=False)
|
|
90
|
+
except Exception: # noqa: BLE001 - no systemd
|
|
91
|
+
return found
|
|
92
|
+
for line in proc.stdout.splitlines():
|
|
93
|
+
if line.strip():
|
|
94
|
+
found.append(line.split()[0])
|
|
95
|
+
return found
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ------------------------------------------------------------------ command
|
|
99
|
+
def setup(
|
|
100
|
+
domain: str = typer.Option(None, help="Public domain, e.g. code.example.com"),
|
|
101
|
+
admin_email: str = typer.Option(None, help="Default admin email (password login)"),
|
|
102
|
+
admin_password_file: Path = typer.Option(
|
|
103
|
+
None, help="Read the default admin password from this file (non-interactive). "
|
|
104
|
+
"Without it, -y generates one and prints it once"),
|
|
105
|
+
metadata_url: str = typer.Option(None, help="AWS SSO metadata URL (optional; also "
|
|
106
|
+
"configurable later in the admin portal)"),
|
|
107
|
+
base_path: str = typer.Option(None, help="URL base path (default /codeapp)"),
|
|
108
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Non-interactive: accept defaults"),
|
|
109
|
+
skip_ssl: bool = typer.Option(False, help="Do not run certbot"),
|
|
110
|
+
skip_image: bool = typer.Option(False, help="Do not build the workspace Docker image"),
|
|
111
|
+
rebuild_image: bool = typer.Option(False, help="Rebuild the workspace image even if present"),
|
|
112
|
+
existing_code_server: str = typer.Option(
|
|
113
|
+
None, help="What to do with an existing code-server service: keep | stop | disable"),
|
|
114
|
+
):
|
|
115
|
+
"""Install or repair CodeGate on this server (safe to re-run)."""
|
|
116
|
+
require_root()
|
|
117
|
+
console.rule(f"[bold cyan]CodeGate setup v{__version__}")
|
|
118
|
+
|
|
119
|
+
marker = read_marker()
|
|
120
|
+
if marker:
|
|
121
|
+
inst = marker.get("version", "?")
|
|
122
|
+
if inst == __version__:
|
|
123
|
+
console.print(f"[green]CodeGate v{inst} is already installed.[/] Re-checking every "
|
|
124
|
+
"component (repair mode)…")
|
|
125
|
+
else:
|
|
126
|
+
console.print(f"[yellow]Installed version is v{inst}, package is v{__version__}.[/]")
|
|
127
|
+
if not yes and Confirm.ask("Run [bold]codegate upgrade[/] instead?", default=True):
|
|
128
|
+
console.print("Run: [bold]sudo codegate upgrade[/]")
|
|
129
|
+
raise typer.Exit(0)
|
|
130
|
+
|
|
131
|
+
# ---------------- preflight
|
|
132
|
+
if platform.system() != "Linux":
|
|
133
|
+
die("CodeGate runs on Linux (Ubuntu 24.04).")
|
|
134
|
+
try:
|
|
135
|
+
osr = Path("/etc/os-release").read_text()
|
|
136
|
+
if "ubuntu" not in osr.lower():
|
|
137
|
+
console.print("[yellow]! Not Ubuntu - continuing, but only Ubuntu 24.04 is tested.[/]")
|
|
138
|
+
except OSError:
|
|
139
|
+
pass
|
|
140
|
+
|
|
141
|
+
# ---------------- configuration (env file)
|
|
142
|
+
console.print("\n[bold]1. Configuration[/]")
|
|
143
|
+
env = _read_env()
|
|
144
|
+
given = {"CODEGATE_DOMAIN": domain, "CODEGATE_ADMIN_EMAILS": admin_email,
|
|
145
|
+
"CODEGATE_BASE_PATH": base_path}
|
|
146
|
+
for key, label, default in ENV_KEYS:
|
|
147
|
+
if given.get(key):
|
|
148
|
+
env[key] = given[key]
|
|
149
|
+
elif key in env and env[key] != "":
|
|
150
|
+
console.print(f" [cyan]↷[/] {key} = {env[key]} [dim](existing)[/]")
|
|
151
|
+
elif yes:
|
|
152
|
+
if default is None:
|
|
153
|
+
die(f"--{key.replace('CODEGATE_', '').lower().replace('_', '-')} is required with --yes")
|
|
154
|
+
env[key] = default
|
|
155
|
+
else:
|
|
156
|
+
while True:
|
|
157
|
+
val = Prompt.ask(f" {label}", default=default) or ""
|
|
158
|
+
if val or default is not None:
|
|
159
|
+
env[key] = val
|
|
160
|
+
break
|
|
161
|
+
env.setdefault("CODEGATE_SECRET_KEY", secrets.token_urlsafe(48))
|
|
162
|
+
env.setdefault("CODEGATE_PUBLIC_SCHEME", "https")
|
|
163
|
+
_write_env(env)
|
|
164
|
+
console.print(f" [green]✓[/] saved {env_file_path()}")
|
|
165
|
+
s = get_settings()
|
|
166
|
+
|
|
167
|
+
# ---------------- existing code-server
|
|
168
|
+
units = _detect_code_server()
|
|
169
|
+
action = existing_code_server
|
|
170
|
+
if units:
|
|
171
|
+
console.print(f"\n[yellow]Existing code-server found:[/] {', '.join(units)}")
|
|
172
|
+
if not action:
|
|
173
|
+
action = "keep" if yes else Prompt.ask(
|
|
174
|
+
" keep it running, stop it, or disable it (stop + no autostart)?",
|
|
175
|
+
choices=["keep", "stop", "disable"], default="keep")
|
|
176
|
+
|
|
177
|
+
# ---------------- steps
|
|
178
|
+
docker_present = shutil.which("docker") is not None
|
|
179
|
+
|
|
180
|
+
def apt_missing() -> list[str]:
|
|
181
|
+
miss = [pkg for cmd, pkg in APT_PACKAGES.items() if not shutil.which(cmd)]
|
|
182
|
+
miss += [p for p in LIB_PACKAGES if not _dpkg_installed(p)]
|
|
183
|
+
if not docker_present:
|
|
184
|
+
miss.append("docker.io")
|
|
185
|
+
return [p for item in miss for p in item.split()]
|
|
186
|
+
|
|
187
|
+
def saml_ok() -> bool:
|
|
188
|
+
from ..auth.saml import saml_available
|
|
189
|
+
return saml_available()
|
|
190
|
+
|
|
191
|
+
def install_saml():
|
|
192
|
+
proc = subprocess.run([sys.executable, "-m", "pip", "install", "python3-saml>=1.16"],
|
|
193
|
+
capture_output=True, text=True)
|
|
194
|
+
if proc.returncode != 0:
|
|
195
|
+
raise RuntimeError(proc.stderr[-800:])
|
|
196
|
+
return "python3-saml"
|
|
197
|
+
|
|
198
|
+
def dirs_ok() -> bool:
|
|
199
|
+
return all(p.exists() for p in (s.data_dir, s.log_dir, s.nginx_dir, s.users_nginx_dir,
|
|
200
|
+
s.etc_dir, s.backup_dir, s.archive_dir))
|
|
201
|
+
|
|
202
|
+
def make_dirs():
|
|
203
|
+
for p in (s.data_dir, s.log_dir, s.nginx_dir, s.users_nginx_dir, s.etc_dir, s.backup_dir,
|
|
204
|
+
s.archive_dir):
|
|
205
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
206
|
+
os.chmod(s.data_dir, 0o700)
|
|
207
|
+
|
|
208
|
+
def docker_running() -> bool:
|
|
209
|
+
return ok(["docker", "info"])
|
|
210
|
+
|
|
211
|
+
def start_docker():
|
|
212
|
+
run(["systemctl", "enable", "--now", "docker"])
|
|
213
|
+
|
|
214
|
+
def network_ok() -> bool:
|
|
215
|
+
return ok(["docker", "network", "inspect", s.docker_network])
|
|
216
|
+
|
|
217
|
+
def make_network():
|
|
218
|
+
from ..system import get_system
|
|
219
|
+
get_system().ensure_network()
|
|
220
|
+
|
|
221
|
+
def image_ok() -> bool:
|
|
222
|
+
if rebuild_image:
|
|
223
|
+
return False
|
|
224
|
+
proc = run(["docker", "image", "inspect", "-f",
|
|
225
|
+
'{{ index .Config.Labels "codegate.dockerfile_sha" }}', s.workspace_image],
|
|
226
|
+
check=False)
|
|
227
|
+
return proc.returncode == 0 # present (upgrade handles changed Dockerfile)
|
|
228
|
+
|
|
229
|
+
def build_image():
|
|
230
|
+
return build_workspace_image()
|
|
231
|
+
|
|
232
|
+
def code_server_action():
|
|
233
|
+
for u in units:
|
|
234
|
+
if action in ("stop", "disable"):
|
|
235
|
+
run(["systemctl", "stop", u], check=False)
|
|
236
|
+
if action == "disable":
|
|
237
|
+
run(["systemctl", "disable", u], check=False)
|
|
238
|
+
return f"{action}: {', '.join(units)}"
|
|
239
|
+
|
|
240
|
+
def migrate_db():
|
|
241
|
+
from ..db import migrate
|
|
242
|
+
old, new = migrate()
|
|
243
|
+
return f"schema v{old} -> v{new}" if old != new else f"schema v{new}"
|
|
244
|
+
|
|
245
|
+
def admins_ok() -> bool:
|
|
246
|
+
from ..db import session_scope
|
|
247
|
+
from .auth_cmd import admin_with_password_exists
|
|
248
|
+
with session_scope() as db:
|
|
249
|
+
return admin_with_password_exists(db)
|
|
250
|
+
|
|
251
|
+
def add_admins():
|
|
252
|
+
from .auth_cmd import ensure_default_admin
|
|
253
|
+
pw = None
|
|
254
|
+
if admin_password_file:
|
|
255
|
+
pw = admin_password_file.read_text().strip()
|
|
256
|
+
return ensure_default_admin(s.admin_email_list[0], pw, interactive=not yes)
|
|
257
|
+
|
|
258
|
+
def sso_ok() -> bool:
|
|
259
|
+
from ..db import get_setting, session_scope
|
|
260
|
+
if not metadata_url:
|
|
261
|
+
return True
|
|
262
|
+
with session_scope() as db:
|
|
263
|
+
return get_setting(db, "saml_idp_metadata_url") == metadata_url
|
|
264
|
+
|
|
265
|
+
def set_sso():
|
|
266
|
+
from ..db import session_scope, set_setting
|
|
267
|
+
with session_scope() as db:
|
|
268
|
+
set_setting(db, "saml_idp_metadata_url", metadata_url)
|
|
269
|
+
set_setting(db, "sso_enabled", True)
|
|
270
|
+
return "AWS SSO enabled"
|
|
271
|
+
|
|
272
|
+
def unit_ok() -> bool:
|
|
273
|
+
p = Path("/etc/systemd/system/codegate.service")
|
|
274
|
+
return p.exists() and p.read_text() == _unit_text()
|
|
275
|
+
|
|
276
|
+
def install_unit():
|
|
277
|
+
Path("/etc/systemd/system/codegate.service").write_text(_unit_text())
|
|
278
|
+
Path("/etc/systemd/system/codegate-backup.service").write_text(resources.render(
|
|
279
|
+
"systemd/codegate-backup.service.tmpl", env_file=env_file_path(), exec=codegate_exec()))
|
|
280
|
+
Path("/etc/systemd/system/codegate-backup.timer").write_text(
|
|
281
|
+
resources.read("systemd/codegate-backup.timer"))
|
|
282
|
+
run(["systemctl", "daemon-reload"])
|
|
283
|
+
run(["systemctl", "enable", "codegate", "codegate-backup.timer"])
|
|
284
|
+
run(["systemctl", "start", "codegate-backup.timer"], check=False)
|
|
285
|
+
|
|
286
|
+
def restart_service():
|
|
287
|
+
run(["systemctl", "restart", "codegate"])
|
|
288
|
+
return wait_healthy()
|
|
289
|
+
|
|
290
|
+
def ssl_ok() -> bool:
|
|
291
|
+
return skip_ssl or nginx_setup.has_ssl()
|
|
292
|
+
|
|
293
|
+
def run_certbot():
|
|
294
|
+
if not nginx_setup.certbot_allowed():
|
|
295
|
+
raise RuntimeError(f"existing server block for {s.domain} has no HTTPS. CodeGate does "
|
|
296
|
+
"not edit existing nginx files; add SSL yourself, e.g. "
|
|
297
|
+
f"sudo certbot --nginx -d {s.domain}")
|
|
298
|
+
email = None if yes else Prompt.ask(" Email for Let's Encrypt notices", default="")
|
|
299
|
+
cmd = ["certbot", "--nginx", "-d", s.domain, "--non-interactive", "--agree-tos",
|
|
300
|
+
"--redirect"]
|
|
301
|
+
cmd += ["-m", email] if email else ["--register-unsafely-without-email"]
|
|
302
|
+
run(cmd, timeout=300)
|
|
303
|
+
return "certificate issued"
|
|
304
|
+
|
|
305
|
+
steps = [
|
|
306
|
+
Step("System packages", lambda: not apt_missing(), lambda: _apt_install(apt_missing())),
|
|
307
|
+
Step("SAML library (python3-saml)", saml_ok, install_saml),
|
|
308
|
+
Step("Directories", dirs_ok, make_dirs),
|
|
309
|
+
Step("Docker service", docker_running, start_docker),
|
|
310
|
+
Step("Docker network", network_ok, make_network),
|
|
311
|
+
Step("Workspace image", (lambda: True) if skip_image else image_ok, build_image,
|
|
312
|
+
critical=False),
|
|
313
|
+
Step("Existing code-server", (lambda: not units or action == "keep"), code_server_action,
|
|
314
|
+
critical=False),
|
|
315
|
+
Step("Database", None, migrate_db),
|
|
316
|
+
Step("Default admin (password login)", admins_ok, add_admins),
|
|
317
|
+
Step("AWS SSO", sso_ok, set_sso, critical=False),
|
|
318
|
+
Step("Block host SSH for workspace users", ssh_setup.is_applied, ssh_setup.apply),
|
|
319
|
+
Step("Nginx integration", nginx_setup.is_integrated, nginx_setup.integrate),
|
|
320
|
+
Step("SSL certificate", ssl_ok, run_certbot, critical=False),
|
|
321
|
+
Step("systemd service + daily backup", unit_ok, install_unit),
|
|
322
|
+
Step("Start CodeGate", None, restart_service),
|
|
323
|
+
]
|
|
324
|
+
console.print("\n[bold]2. Components[/]")
|
|
325
|
+
if not run_steps(steps):
|
|
326
|
+
raise typer.Exit(1)
|
|
327
|
+
|
|
328
|
+
write_marker(dockerfile_sha=dockerfile_sha())
|
|
329
|
+
_print_summary()
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _unit_text() -> str:
|
|
333
|
+
s = get_settings()
|
|
334
|
+
return resources.render("systemd/codegate.service.tmpl", env_file=env_file_path(),
|
|
335
|
+
exec=codegate_exec(), log_dir=s.log_dir)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def wait_healthy(timeout: int = 40) -> str:
|
|
339
|
+
import time
|
|
340
|
+
import httpx
|
|
341
|
+
s = get_settings()
|
|
342
|
+
url = f"http://{s.listen_host}:{s.listen_port}{s.base_path}/healthz"
|
|
343
|
+
deadline = time.time() + timeout
|
|
344
|
+
last = ""
|
|
345
|
+
while time.time() < deadline:
|
|
346
|
+
try:
|
|
347
|
+
r = httpx.get(url, timeout=3)
|
|
348
|
+
if r.status_code == 200:
|
|
349
|
+
return "healthy"
|
|
350
|
+
last = f"HTTP {r.status_code}"
|
|
351
|
+
except httpx.HTTPError as exc:
|
|
352
|
+
last = str(exc)
|
|
353
|
+
time.sleep(2)
|
|
354
|
+
raise RuntimeError(f"service not healthy at {url}: {last}. See: sudo codegate logs")
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def build_workspace_image(no_cache: bool = False) -> str:
|
|
358
|
+
import tempfile
|
|
359
|
+
s = get_settings()
|
|
360
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
361
|
+
Path(tmp, "Dockerfile").write_text(resources.read("docker/Dockerfile"))
|
|
362
|
+
cmd = ["docker", "build", "-t", s.workspace_image, "--label",
|
|
363
|
+
f"codegate.dockerfile_sha={dockerfile_sha()}", tmp]
|
|
364
|
+
if no_cache:
|
|
365
|
+
cmd.insert(2, "--no-cache")
|
|
366
|
+
console.print(" [dim]building workspace image (first time takes a few minutes)…[/]")
|
|
367
|
+
proc = subprocess.run(cmd, text=True, capture_output=True)
|
|
368
|
+
if proc.returncode != 0:
|
|
369
|
+
raise RuntimeError(f"docker build failed:\n{proc.stdout[-1500:]}{proc.stderr[-1500:]}")
|
|
370
|
+
return s.workspace_image
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _print_summary() -> None:
|
|
374
|
+
s = get_settings()
|
|
375
|
+
console.rule("[bold green]CodeGate is ready")
|
|
376
|
+
t = Table(show_header=False, box=None)
|
|
377
|
+
t.add_row("Login URL", f"[bold]{s.public_url}/[/]")
|
|
378
|
+
t.add_row("Admin portal", f"{s.public_url}/admin/")
|
|
379
|
+
t.add_row("User VS Code", f"{s.public_url}/editor/<username>/")
|
|
380
|
+
console.print(t)
|
|
381
|
+
console.print("\n[bold]AWS IAM Identity Center → Applications → Add application → "
|
|
382
|
+
"'I have an application I want to set up' → SAML 2.0[/]")
|
|
383
|
+
t = Table(show_header=False, box=None)
|
|
384
|
+
t.add_row("Application ACS URL", s.acs_url)
|
|
385
|
+
t.add_row("Application SAML audience", s.sp_entity_id)
|
|
386
|
+
t.add_row("Attribute: Subject", "${user:email} format: emailAddress")
|
|
387
|
+
t.add_row("Attribute: email", "${user:email} format: unspecified")
|
|
388
|
+
t.add_row("Attribute: name", "${user:name} format: unspecified (optional)")
|
|
389
|
+
console.print(t)
|
|
390
|
+
console.print("\nSign in with the default admin's email and password. AWS SSO is optional: "
|
|
391
|
+
"set it up in the admin portal → Settings → Login.")
|
|
392
|
+
from ..system import get_system
|
|
393
|
+
if not get_system().quota_supported():
|
|
394
|
+
console.print("\n[yellow]! Disk quotas are not enabled on /home.[/] Disk limits will be "
|
|
395
|
+
"monitored (workspace stops when over limit) instead of hard-enforced.\n"
|
|
396
|
+
" To hard-enforce, see README → 'Enable disk quotas'.")
|
|
397
|
+
hint = nginx_setup.manual_include_hint()
|
|
398
|
+
if hint:
|
|
399
|
+
console.print("\n[bold yellow]! ACTION NEEDED (nginx):[/] CodeGate did not edit your "
|
|
400
|
+
"existing nginx config.\n " + hint)
|
|
401
|
+
console.print("\nCheck everything any time with: [bold]sudo codegate doctor[/]")
|