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,88 @@
1
+ """Password hashing and policy.
2
+
3
+ Passwords are never stored or logged. The DB keeps only a salted scrypt hash:
4
+ ``scrypt$<n>$<r>$<p>$<salt b64>$<hash b64>``. Verification is constant-time.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ import hashlib
10
+ import hmac
11
+ import secrets
12
+ import string
13
+ import unicodedata
14
+
15
+ N, R, P, DKLEN = 2 ** 15, 8, 1, 32
16
+ MAXMEM = 64 * 1024 * 1024
17
+ MAX_LEN = 256
18
+
19
+
20
+ def _norm(password: str) -> bytes:
21
+ return unicodedata.normalize("NFKC", password).encode("utf-8")
22
+
23
+
24
+ def _b64(b: bytes) -> str:
25
+ return base64.b64encode(b).decode()
26
+
27
+
28
+ def hash_password(password: str) -> str:
29
+ salt = secrets.token_bytes(16)
30
+ dk = hashlib.scrypt(_norm(password), salt=salt, n=N, r=R, p=P, dklen=DKLEN, maxmem=MAXMEM)
31
+ return f"scrypt${N}${R}${P}${_b64(salt)}${_b64(dk)}"
32
+
33
+
34
+ def verify_password(password: str, stored: str | None) -> bool:
35
+ if not stored or len(password) > MAX_LEN:
36
+ dummy_verify()
37
+ return False
38
+ try:
39
+ algo, n, r, p, salt, dk = stored.split("$")
40
+ if algo != "scrypt":
41
+ return False
42
+ expected = base64.b64decode(dk)
43
+ got = hashlib.scrypt(_norm(password), salt=base64.b64decode(salt), n=int(n), r=int(r),
44
+ p=int(p), dklen=len(expected), maxmem=MAXMEM)
45
+ except (ValueError, TypeError):
46
+ return False
47
+ return hmac.compare_digest(got, expected)
48
+
49
+
50
+ _DUMMY = None
51
+
52
+
53
+ def dummy_verify() -> None:
54
+ """Spend the same time as a real check (unknown user) so timing doesn't reveal accounts."""
55
+ global _DUMMY
56
+ if _DUMMY is None:
57
+ _DUMMY = hash_password(secrets.token_urlsafe(16))
58
+ _, n, r, p, salt, dk = _DUMMY.split("$")
59
+ hashlib.scrypt(b"x", salt=base64.b64decode(salt), n=int(n), r=int(r), p=int(p),
60
+ dklen=DKLEN, maxmem=MAXMEM)
61
+
62
+
63
+ def policy_errors(password: str, *, min_length: int = 12, username: str = "",
64
+ email: str = "") -> list[str]:
65
+ errs = []
66
+ if len(password) < min_length:
67
+ errs.append(f"at least {min_length} characters")
68
+ if len(password) > MAX_LEN:
69
+ errs.append(f"at most {MAX_LEN} characters")
70
+ classes = sum([any(c.islower() for c in password), any(c.isupper() for c in password),
71
+ any(c.isdigit() for c in password),
72
+ any(not c.isalnum() for c in password)])
73
+ if classes < 3:
74
+ errs.append("3 of: lowercase, uppercase, digit, symbol")
75
+ low = password.lower()
76
+ for word in (username, email.split("@")[0] if email else ""):
77
+ if word and len(word) >= 3 and word.lower() in low:
78
+ errs.append("must not contain your username or email")
79
+ break
80
+ return errs
81
+
82
+
83
+ def generate_password(length: int = 20) -> str:
84
+ alphabet = string.ascii_letters + string.digits + "-_.!@#%"
85
+ while True:
86
+ pw = "".join(secrets.choice(alphabet) for _ in range(length))
87
+ if not policy_errors(pw, min_length=length):
88
+ return pw
codegate/auth/saml.py ADDED
@@ -0,0 +1,222 @@
1
+ """SAML 2.0 service provider for AWS IAM Identity Center.
2
+
3
+ Uses python3-saml (OneLogin). Install with ``pip install "inferyx-codegate[saml]"``
4
+ (needs ``libxmlsec1-dev pkg-config``; ``codegate setup`` installs them).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import time
10
+ from datetime import timedelta
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from sqlalchemy.orm import Session
15
+
16
+ from ..config import get_settings
17
+ from ..db import SamlReplay, utcnow
18
+ from ..errors import SSOError
19
+
20
+ log = logging.getLogger("codegate.saml")
21
+
22
+ _METADATA_CACHE: dict[str, Any] = {"data": None, "ts": 0.0, "key": None}
23
+ METADATA_TTL = 3600
24
+
25
+
26
+ def saml_available() -> bool:
27
+ try:
28
+ import onelogin.saml2.auth # noqa: F401
29
+ return True
30
+ except Exception:
31
+ return False
32
+
33
+
34
+ def _require_lib():
35
+ if not saml_available():
36
+ raise SSOError(
37
+ "SAML library not installed. Run: sudo codegate setup (or pip install 'inferyx-codegate[saml]')",
38
+ code="saml_not_installed", status_code=500)
39
+
40
+
41
+ def sso_config(db: Session) -> dict[str, str]:
42
+ """SSO settings: admin portal (DB) first, env file as fallback."""
43
+ from ..db import get_setting
44
+ s = get_settings()
45
+ return {
46
+ "metadata_url": (get_setting(db, "saml_idp_metadata_url") or s.saml_idp_metadata_url).strip(),
47
+ "metadata_file": s.saml_idp_metadata_file,
48
+ "email_attribute": get_setting(db, "saml_email_attribute") or s.saml_email_attribute,
49
+ }
50
+
51
+
52
+ def sso_configured(db: Session) -> bool:
53
+ c = sso_config(db)
54
+ return bool(c["metadata_url"] or c["metadata_file"])
55
+
56
+
57
+ def sso_active(db: Session) -> bool:
58
+ from ..db import get_setting
59
+ return bool(get_setting(db, "sso_enabled")) and sso_configured(db)
60
+
61
+
62
+ def clear_metadata_cache() -> None:
63
+ _METADATA_CACHE.update(data=None, ts=0.0, key=None)
64
+
65
+
66
+ def load_metadata(url: str = "", file: str = "", *, use_cache: bool = True) -> dict[str, Any]:
67
+ _require_lib()
68
+ from onelogin.saml2.idp_metadata_parser import OneLogin_Saml2_IdPMetadataParser as P
69
+
70
+ s = get_settings()
71
+ now = time.time()
72
+ key = url or file
73
+ if (use_cache and _METADATA_CACHE["data"] and _METADATA_CACHE.get("key") == key
74
+ and now - _METADATA_CACHE["ts"] < METADATA_TTL):
75
+ return _METADATA_CACHE["data"]
76
+ import hashlib
77
+ cache_file = s.data_dir / f"idp-metadata-{hashlib.sha256(key.encode()).hexdigest()[:16]}.xml"
78
+ try:
79
+ if file:
80
+ xml = Path(file).read_text()
81
+ elif url:
82
+ if not url.startswith("https://"):
83
+ raise SSOError("SSO metadata URL must start with https://", code="sso_bad_url")
84
+ import httpx
85
+ r = httpx.get(url, timeout=10, follow_redirects=True)
86
+ r.raise_for_status()
87
+ xml = r.text
88
+ else:
89
+ raise SSOError("SSO is not configured: set the metadata URL in Settings → Login",
90
+ code="sso_not_configured", status_code=500)
91
+ data = P.parse(xml)
92
+ if not data.get("idp", {}).get("singleSignOnService", {}).get("url"):
93
+ raise SSOError("The metadata has no SAML sign-in URL", code="sso_bad_metadata")
94
+ if use_cache and url:
95
+ try:
96
+ cache_file.write_text(xml)
97
+ except OSError:
98
+ pass
99
+ except SSOError:
100
+ raise
101
+ except Exception as exc: # network / parse error -> cached copy (same URL only)
102
+ if use_cache and url and cache_file.is_file():
103
+ log.warning("IdP metadata fetch failed (%s); using cached copy", exc)
104
+ data = P.parse(cache_file.read_text())
105
+ else:
106
+ raise SSOError(f"Cannot load IdP metadata: {exc}", code="sso_metadata_unreachable",
107
+ status_code=502) from exc
108
+ if use_cache:
109
+ _METADATA_CACHE.update(data=data, ts=now, key=key)
110
+ return data
111
+
112
+
113
+ def _idp_settings(db: Session) -> dict[str, Any]:
114
+ c = sso_config(db)
115
+ return load_metadata(c["metadata_url"], c["metadata_file"])
116
+
117
+
118
+ def saml_settings(db: Session) -> dict[str, Any]:
119
+ s = get_settings()
120
+ idp = _idp_settings(db)
121
+ settings = {
122
+ "strict": True,
123
+ "debug": False,
124
+ "sp": {
125
+ "entityId": s.sp_entity_id,
126
+ "assertionConsumerService": {
127
+ "url": s.acs_url,
128
+ "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
129
+ },
130
+ "NameIDFormat": "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
131
+ },
132
+ "security": {
133
+ "wantAssertionsSigned": False, # IAM Identity Center signs the Response
134
+ "wantMessagesSigned": False,
135
+ "rejectDeprecatedAlgorithm": True,
136
+ },
137
+ }
138
+ settings["idp"] = idp["idp"]
139
+ return settings
140
+
141
+
142
+ def _request_data(form: dict[str, str] | None, query: dict[str, str], path: str) -> dict[str, Any]:
143
+ s = get_settings()
144
+ return {
145
+ "https": "on" if s.public_scheme == "https" else "off",
146
+ "http_host": s.domain,
147
+ "server_port": 443 if s.public_scheme == "https" else 80,
148
+ "script_name": path,
149
+ "get_data": dict(query),
150
+ "post_data": dict(form or {}),
151
+ }
152
+
153
+
154
+ def login_redirect_url(db: Session, relay_state: str) -> str:
155
+ _require_lib()
156
+ from onelogin.saml2.auth import OneLogin_Saml2_Auth
157
+ s = get_settings()
158
+ auth = OneLogin_Saml2_Auth(_request_data(None, {}, f"{s.base_path}/saml/login"),
159
+ saml_settings(db))
160
+ return auth.login(return_to=relay_state)
161
+
162
+
163
+ def process_acs(db: Session, form: dict[str, str]) -> dict[str, Any]:
164
+ """Validate the SAML response. Returns {'email', 'name', 'attributes'}."""
165
+ _require_lib()
166
+ from onelogin.saml2.auth import OneLogin_Saml2_Auth
167
+ s = get_settings()
168
+ if not sso_active(db):
169
+ raise SSOError("SSO login is disabled", code="sso_disabled", status_code=403)
170
+ auth = OneLogin_Saml2_Auth(_request_data(form, {}, f"{s.base_path}/saml/acs"),
171
+ saml_settings(db))
172
+ auth.process_response()
173
+ errors = auth.get_errors()
174
+ if errors:
175
+ raise SSOError("SSO login failed", code="sso_invalid_response",
176
+ details={"errors": errors, "reason": auth.get_last_error_reason()})
177
+ if not auth.is_authenticated():
178
+ raise SSOError("SSO login not authenticated", code="sso_not_authenticated")
179
+
180
+ # replay protection
181
+ assertion_id = auth.get_last_assertion_id() or auth.get_last_message_id()
182
+ if assertion_id:
183
+ now = utcnow()
184
+ if db.get(SamlReplay, assertion_id) is not None:
185
+ raise SSOError("This login response was already used", code="sso_replay")
186
+ db.add(SamlReplay(assertion_id=assertion_id, expires_at=now + timedelta(hours=12)))
187
+
188
+ attrs = auth.get_attributes() or {}
189
+ email = ""
190
+ for key in (sso_config(db)["email_attribute"], "email", "Email",
191
+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"):
192
+ vals = attrs.get(key)
193
+ if vals:
194
+ email = vals[0]
195
+ break
196
+ if not email:
197
+ email = auth.get_nameid() or ""
198
+ email = email.strip().lower()
199
+ if "@" not in email:
200
+ raise SSOError("SSO response has no email. Map 'email' attribute / NameID in the AWS app.",
201
+ code="sso_no_email")
202
+ name = ""
203
+ for key in ("name", "displayName", "given_name"):
204
+ if attrs.get(key):
205
+ name = attrs[key][0]
206
+ break
207
+ return {"email": email, "name": name, "attributes": attrs}
208
+
209
+
210
+ def sp_metadata_xml() -> str:
211
+ s = get_settings()
212
+ # Build minimal SP metadata without requiring IdP metadata to be loaded.
213
+ return f"""<?xml version="1.0"?>
214
+ <md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" entityID="{s.sp_entity_id}">
215
+ <md:SPSSODescriptor AuthnRequestsSigned="false" WantAssertionsSigned="false"
216
+ protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
217
+ <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
218
+ <md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
219
+ Location="{s.acs_url}" index="1"/>
220
+ </md:SPSSODescriptor>
221
+ </md:EntityDescriptor>
222
+ """
@@ -0,0 +1,121 @@
1
+ """Server-side login sessions.
2
+
3
+ The browser only holds a random token (HttpOnly, Secure cookie scoped to the
4
+ base path). The DB stores its SHA-256 hash, so a DB leak does not leak sessions.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import secrets
10
+ from datetime import timedelta
11
+
12
+ from fastapi import Request, Response
13
+ from sqlalchemy import delete, select
14
+ from sqlalchemy.orm import Session
15
+
16
+ from ..config import get_settings
17
+ from ..db import LoginSession, User, get_setting, utcnow
18
+
19
+ # throttle last_seen writes from nginx auth_request (called on every request)
20
+ TOUCH_EVERY = timedelta(seconds=60)
21
+
22
+
23
+ def _hash(token: str) -> str:
24
+ return hashlib.sha256(token.encode()).hexdigest()
25
+
26
+
27
+ def client_ip(request: Request) -> str:
28
+ fwd = request.headers.get("x-real-ip") or request.headers.get("x-forwarded-for", "")
29
+ if fwd:
30
+ return fwd.split(",")[0].strip()[:64]
31
+ return request.client.host if request.client else ""
32
+
33
+
34
+ def create_session(db: Session, user: User, request: Request, response: Response,
35
+ auth_method: str = "sso") -> str:
36
+ """Always a NEW random token (old cookie session, if any, is ended first)."""
37
+ s = get_settings()
38
+ end_session(db, request)
39
+ hours = int(get_setting(db, "session_hours") or s.session_hours)
40
+ token = secrets.token_urlsafe(32)
41
+ now = utcnow()
42
+ db.add(LoginSession(token_hash=_hash(token), user_id=user.id, ip=client_ip(request),
43
+ user_agent=request.headers.get("user-agent", "")[:300],
44
+ auth_method=auth_method, created_at=now,
45
+ last_seen=now, expires_at=now + timedelta(hours=hours)))
46
+ user.last_login = now
47
+ response.set_cookie(
48
+ s.cookie_name, token, max_age=hours * 3600, path=s.base_path or "/",
49
+ httponly=True, secure=(s.public_scheme == "https"), samesite="lax",
50
+ )
51
+ return token
52
+
53
+
54
+ def clear_cookie(response: Response) -> None:
55
+ s = get_settings()
56
+ response.delete_cookie(s.cookie_name, path=s.base_path or "/")
57
+
58
+
59
+ def resolve_session(db: Session, request: Request, *, touch: bool = True
60
+ ) -> tuple[LoginSession, User] | None:
61
+ """Return (session, user) for a valid, non-expired session cookie, else None."""
62
+ s = get_settings()
63
+ token = request.cookies.get(s.cookie_name)
64
+ if not token:
65
+ return None
66
+ sess = db.scalar(select(LoginSession).where(LoginSession.token_hash == _hash(token)))
67
+ if sess is None:
68
+ return None
69
+ now = utcnow()
70
+ idle_min = int(get_setting(db, "idle_session_minutes") or s.idle_session_minutes)
71
+ if sess.expires_at <= now or (idle_min > 0 and sess.last_seen + timedelta(minutes=idle_min) <= now):
72
+ db.delete(sess)
73
+ return None
74
+ user = db.get(User, sess.user_id)
75
+ if user is None:
76
+ db.delete(sess)
77
+ return None
78
+ if touch and now - sess.last_seen >= TOUCH_EVERY:
79
+ sess.last_seen = now
80
+ return sess, user
81
+
82
+
83
+ def end_session(db: Session, request: Request) -> None:
84
+ token = request.cookies.get(get_settings().cookie_name)
85
+ if token:
86
+ db.execute(delete(LoginSession).where(LoginSession.token_hash == _hash(token)))
87
+
88
+
89
+ def end_user_sessions(db: Session, user_id: int, *, keep_id: int | None = None) -> int:
90
+ q = delete(LoginSession).where(LoginSession.user_id == user_id)
91
+ if keep_id is not None:
92
+ q = q.where(LoginSession.id != keep_id)
93
+ return db.execute(q).rowcount or 0
94
+
95
+
96
+ def end_method_sessions(db: Session, method: str, *, keep_id: int | None = None) -> int:
97
+ q = delete(LoginSession).where(LoginSession.auth_method == method)
98
+ if keep_id is not None:
99
+ q = q.where(LoginSession.id != keep_id)
100
+ return db.execute(q).rowcount or 0
101
+
102
+
103
+ def purge_expired(db: Session) -> int:
104
+ s = get_settings()
105
+ now = utcnow()
106
+ idle_min = int(get_setting(db, "idle_session_minutes") or s.idle_session_minutes)
107
+ q = delete(LoginSession).where(LoginSession.expires_at <= now)
108
+ n = db.execute(q).rowcount or 0
109
+ if idle_min > 0:
110
+ n += db.execute(delete(LoginSession).where(
111
+ LoginSession.last_seen <= now - timedelta(minutes=idle_min))).rowcount or 0
112
+ return n
113
+
114
+
115
+ def touch_user_sessions(db: Session, user_id: int) -> None:
116
+ """Keep sessions alive while the user is active inside VS Code (websocket traffic
117
+ does not hit auth_request, so the reaper calls this from the code-server heartbeat)."""
118
+ now = utcnow()
119
+ for sess in db.scalars(select(LoginSession).where(LoginSession.user_id == user_id)):
120
+ if sess.expires_at > now:
121
+ sess.last_seen = now
File without changes
@@ -0,0 +1,168 @@
1
+ """Login-related CLI: default admin, password reset, login methods (recovery path when
2
+ nobody can sign in through the web)."""
3
+ from __future__ import annotations
4
+
5
+ import getpass
6
+
7
+ import typer
8
+ from sqlalchemy import select
9
+
10
+ from .common import console, die, require_root
11
+
12
+ auth_app = typer.Typer(help="Login methods (password / AWS SSO).", no_args_is_help=True)
13
+
14
+
15
+ def _db():
16
+ from ..db import migrate, session_scope
17
+ migrate()
18
+ return session_scope()
19
+
20
+
21
+ def prompt_new_password(db, user=None, *, email: str = "") -> str:
22
+ from ..auth.native import check_policy
23
+ from ..errors import ValidationFailed
24
+ while True:
25
+ pw = getpass.getpass(" New password: ")
26
+ if pw != getpass.getpass(" Repeat password: "):
27
+ console.print(" [red]Passwords don't match[/]")
28
+ continue
29
+ try:
30
+ check_policy(db, user, pw, email=email, username=email.split("@")[0])
31
+ return pw
32
+ except ValidationFailed as exc:
33
+ console.print(f" [red]{exc.message}[/]")
34
+
35
+
36
+ def admin_with_password_exists(db) -> bool:
37
+ from ..db import User
38
+ return db.scalar(select(User.id).where(User.is_admin.is_(True), User.status == "active",
39
+ User.password_hash.is_not(None)).limit(1)) is not None
40
+
41
+
42
+ def ensure_default_admin(email: str, password: str | None, *, interactive: bool,
43
+ actor: str = "setup") -> str:
44
+ """Create (or upgrade) the first admin with a password. Returns a message; when the
45
+ password was generated it is included ONCE so the operator can copy it."""
46
+ from ..auth.native import set_password
47
+ from ..auth.passwords import generate_password
48
+ from ..db import User, audit
49
+ from ..users import create_user
50
+ email = email.strip().lower()
51
+ generated = None
52
+ with _db() as db:
53
+ if password is None:
54
+ if interactive:
55
+ console.print(f" Choose a password for the default admin [bold]{email}[/]")
56
+ password = prompt_new_password(db, email=email)
57
+ else:
58
+ password = generated = generate_password()
59
+ u = db.scalar(select(User).where(User.email == email))
60
+ if u is None:
61
+ u = create_user(db, email=email, actor=actor, is_admin=True, has_workspace=False,
62
+ provision=False, password=password,
63
+ must_change_password=generated is not None)
64
+ else:
65
+ u.is_admin = True
66
+ u.status = "active"
67
+ set_password(db, u, password, must_change=generated is not None)
68
+ audit(db, "admin.default_created", actor=actor, target=email,
69
+ generated_password=generated is not None)
70
+ login = u.username
71
+ msg = f"admin '{login}' / {email}"
72
+ if generated:
73
+ msg += (f"\n [bold yellow]Temporary password (shown once): {generated}[/]"
74
+ "\n It must be changed at first login.")
75
+ return msg
76
+
77
+
78
+ # ------------------------------------------------------------------ commands
79
+ def user_passwd(ident: str = typer.Argument(..., help="username or email"),
80
+ generate: bool = typer.Option(False, help="Generate a random temporary password"),
81
+ temporary: bool = typer.Option(True, help="User must change it at next login")):
82
+ """Set or reset a user's password (ends their sessions)."""
83
+ require_root()
84
+ from ..auth.native import set_password
85
+ from ..auth.passwords import generate_password
86
+ from ..auth.sessions import end_user_sessions
87
+ from ..db import audit
88
+ from ..users import get_user
89
+ with _db() as db:
90
+ u = get_user(db, ident)
91
+ pw = generate_password() if generate else prompt_new_password(db, u)
92
+ set_password(db, u, pw, must_change=temporary)
93
+ n = end_user_sessions(db, u.id)
94
+ audit(db, "user.password_set", actor="cli", target=u.email, must_change=temporary,
95
+ sessions_ended=n)
96
+ console.print(f"[green]✓ password set for {u.email}[/] ({n} session(s) ended)")
97
+ if generate:
98
+ console.print(f" Temporary password (shown once): [bold]{pw}[/]")
99
+
100
+
101
+ def user_unlock(ident: str = typer.Argument(..., help="username or email")):
102
+ """Clear a lockout after too many failed logins."""
103
+ require_root()
104
+ from ..db import audit
105
+ from ..users import get_user
106
+ with _db() as db:
107
+ u = get_user(db, ident)
108
+ u.failed_logins, u.locked_until = 0, None
109
+ audit(db, "user.unlock", actor="cli", target=u.email)
110
+ console.print(f"[green]✓ {ident} unlocked[/]")
111
+
112
+
113
+ @auth_app.command("show")
114
+ def auth_show():
115
+ """Show which login methods are enabled."""
116
+ from ..auth import saml
117
+ from ..db import get_setting
118
+ with _db() as db:
119
+ console.print(f"password login : {'on' if get_setting(db, 'password_login_enabled') else 'off'}")
120
+ console.print(f"AWS SSO login : {'on' if get_setting(db, 'sso_enabled') else 'off'}"
121
+ f" (metadata: {saml.sso_config(db)['metadata_url'] or 'not set'})")
122
+
123
+
124
+ def _set_method(method: str, on: bool) -> None:
125
+ require_root()
126
+ from ..auth import saml
127
+ from ..auth.sessions import end_method_sessions
128
+ from ..db import audit, get_setting, set_setting
129
+ key = {"password": "password_login_enabled", "sso": "sso_enabled"}.get(method)
130
+ if key is None:
131
+ die("method must be 'password' or 'sso'")
132
+ with _db() as db:
133
+ other = "sso_enabled" if key == "password_login_enabled" else "password_login_enabled"
134
+ if not on and not get_setting(db, other):
135
+ die("At least one login method must stay enabled")
136
+ if on and method == "sso" and not saml.sso_configured(db):
137
+ die("Set the SSO metadata URL first: sudo codegate auth sso-url <url>")
138
+ set_setting(db, key, on)
139
+ n = 0 if on else end_method_sessions(db, "sso" if method == "sso" else "password")
140
+ audit(db, "settings.update", actor="cli", keys=[key], value=on, sessions_ended=n)
141
+ console.print(f"[green]✓ {method} login {'enabled' if on else 'disabled'}[/]")
142
+
143
+
144
+ @auth_app.command("enable")
145
+ def auth_enable(method: str = typer.Argument(..., help="password | sso")):
146
+ """Enable a login method."""
147
+ _set_method(method, True)
148
+
149
+
150
+ @auth_app.command("disable")
151
+ def auth_disable(method: str = typer.Argument(..., help="password | sso")):
152
+ """Disable a login method (ends sessions that used it)."""
153
+ _set_method(method, False)
154
+
155
+
156
+ @auth_app.command("sso-url")
157
+ def auth_sso_url(url: str = typer.Argument(..., help="IAM Identity Center SAML metadata URL")):
158
+ """Set the AWS SSO metadata URL (same as Settings → Login in the admin portal)."""
159
+ require_root()
160
+ from ..auth import saml
161
+ from ..db import audit, set_setting
162
+ if not url.startswith("https://"):
163
+ die("URL must start with https://")
164
+ with _db() as db:
165
+ set_setting(db, "saml_idp_metadata_url", url)
166
+ audit(db, "settings.update", actor="cli", keys=["saml_idp_metadata_url"])
167
+ saml.clear_metadata_cache()
168
+ console.print("[green]✓ saved.[/] Enable it with: sudo codegate auth enable sso")