Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_signup.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_signup.py · 20.3 KB · 535 lines
1"""Self-service signup, email verification and password reset.
2
3This module owns three things; object_server wires the browser routes
4(/signup, /verify, /reset, /reset/confirm) to them.
5
61. One-time email tokens, in ``identity/email_tokens.tsv`` (mode 0600).
7 A token is ``secrets.token_urlsafe(32)`` and only its
8 ``object_identity.hash_token`` is stored -- the session-token pattern.
9 Each is single use and expires (verification 48 h, reset 1 h). Issuing a
10 new link for a user and purpose retires the previous one.
11 Bounded: every write drops used and expired rows, so the file holds at
12 most one live row per user and purpose.
13
142. The checks that decide whether signup and reset may run here. A
15 capability that is absent refuses rather than pretends:
16 - no way to send the email: refuse;
17 - no configured public address for the link: refuse. Never the request's
18 Host header, which would let anyone point a reset link at their own
19 domain;
20 - a policy that gives every signed-in user unscoped access: refuse signup.
21 That grant is fine for operator-invited users and wrong for strangers.
22
233. The account itself. A signup creates its own account and a user in the
24 ``pending`` status, which cannot log in or hold a session until the
25 emailed link is used (object_identity.PENDING_STATUS). The signup form
26 takes no password: a stranger could type someone else's address with a
27 password of their own, and the owner who clicked the link would then
28 have confirmed the stranger's login. Nor does it take a name, which the
29 stranger could make an impersonation. The password and the name are
30 chosen on the confirmation page, by whoever holds the mailbox
31 (``confirm_signup``).
32
33No enumeration: a signup for an address that already has an account, and a
34reset for an address that has none, answer the person at the form exactly as
35the ordinary case does. Only the mailbox's owner learns which it was.
36"""
37
38from __future__ import annotations
39
40import csv
41import hmac
42import os
43import re
44import secrets
45import threading
46import urllib.parse
47from datetime import datetime, timedelta, timezone
48from pathlib import Path
49from typing import Any, Mapping
50
51import object_credentials
52import object_email
53import object_identity
54import object_permissions
55import object_schemas
56from object_versions import DEFAULT_DATA_DIR
57
58SIGNUP_ENV = "DBBASIC_ENABLE_SIGNUP"
59PASSWORD_RESET_ENV = "DBBASIC_ENABLE_PASSWORD_RESET"
60PUBLIC_URL_ENV = "DBBASIC_PUBLIC_URL"
61
62VERIFY_EMAIL = "verify_email"
63PASSWORD_RESET = "password_reset"
64PURPOSES = frozenset({VERIFY_EMAIL, PASSWORD_RESET})
65TOKEN_TTL = {
66 VERIFY_EMAIL: timedelta(hours=48),
67 PASSWORD_RESET: timedelta(hours=1),
68}
69
70TOKENS_FILE = "email_tokens.tsv"
71TOKEN_FIELDS = ("token_hash", "purpose", "user_id", "email", "created_at", "expires_at", "used_at")
72
73MAX_EMAIL_LENGTH = 254
74MAX_DISPLAY_NAME_LENGTH = 120
75_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
76_TRUE_VALUES = {"1", "true", "yes", "on"}
77_LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
78
79_TOKENS_LOCK = threading.Lock()
80# Check-then-create for one email address is not atomic in object_identity
81# (it locks per file, per call). One process-wide lock keeps two signups for
82# the same address from both passing the "no account yet" check.
83_REGISTER_LOCK = threading.Lock()
84
85
86class SignupError(ValueError):
87 """A signup or reset form value the person has to fix (the message says what)."""
88
89
90# --------------------------------------------------------------------------
91# Whether signup and reset may run
92
93
94def env_enabled(name: str, env: Mapping[str, str] | None = None) -> bool:
95 env = os.environ if env is None else env
96 return (env.get(name) or "").strip().lower() in _TRUE_VALUES
97
98
99def public_url(env: Mapping[str, str] | None = None) -> str | None:
100 """The configured public origin for emailed links, or None.
101
102 Must be https, except on a local host (a developer's own machine)."""
103 env = os.environ if env is None else env
104 value = (env.get(PUBLIC_URL_ENV) or "").strip().rstrip("/")
105 if not value:
106 return None
107 parsed = urllib.parse.urlsplit(value)
108 if not parsed.netloc or parsed.query or parsed.fragment:
109 return None
110 if parsed.scheme == "https":
111 return value
112 if parsed.scheme == "http" and (parsed.hostname or "") in _LOCAL_HOSTS:
113 return value
114 return None
115
116
117def email_blockers(
118 *,
119 base_dir: Path | str = DEFAULT_DATA_DIR,
120 env: Mapping[str, str] | None = None,
121) -> list[str]:
122 """What stops this server from emailing a link, or [] if nothing."""
123 blockers: list[str] = []
124 if not object_email.smtp_config_from_env(os.environ if env is None else env).configured:
125 blockers.append("Outbound email is not configured: set DBBASIC_SMTP_MODE=live and DBBASIC_SMTP_HOST (or DBBASIC_SMTP_MODE=log to test).")
126 try:
127 object_schemas.get_schema(object_email.OUTBOX_COLLECTION, base_dir=base_dir)
128 except (object_schemas.SchemaNotFoundError, OSError, ValueError):
129 blockers.append("The app-email package is not installed, so there is no outbox to queue the email in.")
130 if not object_email.email_pass_enabled(base_dir=base_dir):
131 blockers.append("Outbound email is switched off (feature flag email_enabled).")
132 if public_url(env) is None:
133 blockers.append(f"{PUBLIC_URL_ENV} is not set to this server's https address, which emailed links must use.")
134 return blockers
135
136
137def unscoped_registered_rules(policy: object_permissions.PermissionPolicy) -> list[str]:
138 """Allow rules that give every signed-in user something on everything.
139
140 A rule for the ``registered`` principal with no collection, no object and
141 no row filter applies to all data and every object -- the starter policy's
142 "signed-in users can read and run objects" is one. With open signup,
143 "signed-in" means "anyone with an email address"."""
144 found = []
145 for rule in policy.rules:
146 if rule.effect != "allow" or rule.principal != "registered":
147 continue
148 if rule.collection or rule.object_id or rule.row_filter:
149 continue
150 actions = ", ".join(sorted(rule.actions))
151 found.append(f"registered: {actions}" + (f" ({rule.reason})" if rule.reason else ""))
152 return found
153
154
155def signup_blockers(
156 *,
157 policy: object_permissions.PermissionPolicy,
158 enforcement_enabled: bool,
159 password_login_enabled: bool,
160 base_dir: Path | str = DEFAULT_DATA_DIR,
161 env: Mapping[str, str] | None = None,
162) -> list[str]:
163 """Everything that keeps signup off here, or [] when it may run."""
164 blockers: list[str] = []
165 if not env_enabled(SIGNUP_ENV, env):
166 blockers.append(f"Signup is off: set {SIGNUP_ENV}=true.")
167 if not password_login_enabled:
168 blockers.append("Password login is off, so a new user could never sign in: set DBBASIC_ENABLE_PASSWORD_LOGIN=true.")
169 if not enforcement_enabled:
170 blockers.append("Permission enforcement is off, so a stranger's account would not be limited to their own data: set DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true.")
171 for rule in unscoped_registered_rules(policy):
172 blockers.append(f"The permission policy gives every signed-in user unscoped access ({rule}); scope or remove it before opening signup.")
173 return blockers + email_blockers(base_dir=base_dir, env=env)
174
175
176def reset_blockers(
177 *,
178 password_login_enabled: bool,
179 base_dir: Path | str = DEFAULT_DATA_DIR,
180 env: Mapping[str, str] | None = None,
181) -> list[str]:
182 """Everything that keeps password reset off here, or [] when it may run."""
183 blockers: list[str] = []
184 if not env_enabled(PASSWORD_RESET_ENV, env):
185 blockers.append(f"Password reset is off: set {PASSWORD_RESET_ENV}=true.")
186 if not password_login_enabled:
187 blockers.append("Password login is off: set DBBASIC_ENABLE_PASSWORD_LOGIN=true.")
188 return blockers + email_blockers(base_dir=base_dir, env=env)
189
190
191# --------------------------------------------------------------------------
192# One-time tokens
193
194
195def tokens_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
196 return Path(base_dir) / object_identity.IDENTITY_DIR / TOKENS_FILE
197
198
199def issue_token(
200 purpose: str,
201 user_id: str,
202 email: str,
203 *,
204 base_dir: Path | str = DEFAULT_DATA_DIR,
205 now: datetime | None = None,
206) -> str:
207 """Store a new single-use token and return it raw (the only time it exists raw)."""
208 if purpose not in PURPOSES:
209 raise ValueError(f"Unknown token purpose: {purpose}")
210 now = now or _now()
211 token = secrets.token_urlsafe(32)
212 row = {
213 "token_hash": object_identity.hash_token(token),
214 "purpose": purpose,
215 "user_id": user_id,
216 "email": email,
217 "created_at": _stamp(now),
218 "expires_at": _stamp(now + TOKEN_TTL[purpose]),
219 "used_at": "",
220 }
221 path = tokens_path(base_dir)
222 with _TOKENS_LOCK:
223 rows = [
224 r for r in _live_rows(_read_tokens(path), now)
225 if not (r["user_id"] == user_id and r["purpose"] == purpose)
226 ]
227 rows.append(row)
228 _write_tokens(path, rows)
229 return token
230
231
232def peek_token(
233 token: str | None,
234 purpose: str,
235 *,
236 base_dir: Path | str = DEFAULT_DATA_DIR,
237 now: datetime | None = None,
238) -> dict[str, str] | None:
239 """The live row for a raw token, without using it up; None if not live."""
240 if not token:
241 return None
242 return _find_live(_read_tokens(tokens_path(base_dir)), token, purpose, now or _now())
243
244
245def consume_token(
246 token: str | None,
247 purpose: str,
248 *,
249 base_dir: Path | str = DEFAULT_DATA_DIR,
250 now: datetime | None = None,
251) -> dict[str, str] | None:
252 """Use a raw token up and return its row; None if unknown, used, expired or another purpose."""
253 if not token:
254 return None
255 now = now or _now()
256 path = tokens_path(base_dir)
257 with _TOKENS_LOCK:
258 rows = _read_tokens(path)
259 found = _find_live(rows, token, purpose, now)
260 if found is None:
261 return None
262 found["used_at"] = _stamp(now)
263 # the used row goes too: a used token is never looked at again
264 _write_tokens(path, [r for r in _live_rows(rows, now) if r is not found])
265 return found
266
267
268def _find_live(rows: list[dict[str, str]], token: str, purpose: str, now: datetime) -> dict[str, str] | None:
269 wanted = object_identity.hash_token(token)
270 for row in rows:
271 if not hmac.compare_digest(row.get("token_hash", ""), wanted):
272 continue
273 if row.get("purpose") != purpose or row.get("used_at"):
274 return None
275 try:
276 if _parse(row["expires_at"]) <= now:
277 return None
278 except (KeyError, ValueError):
279 return None
280 return row
281 return None
282
283
284def _live_rows(rows: list[dict[str, str]], now: datetime) -> list[dict[str, str]]:
285 live = []
286 for row in rows:
287 if row.get("used_at"):
288 continue
289 try:
290 if _parse(row["expires_at"]) <= now:
291 continue
292 except (KeyError, ValueError):
293 continue
294 live.append(row)
295 return live
296
297
298def _read_tokens(path: Path) -> list[dict[str, str]]:
299 if not path.exists():
300 return []
301 with path.open(newline="") as handle:
302 return [dict(row) for row in csv.DictReader(handle, delimiter="\t") if row]
303
304
305def _write_tokens(path: Path, rows: list[dict[str, str]]) -> None:
306 path.parent.mkdir(parents=True, exist_ok=True)
307 temp = path.with_name(f".{path.name}.tmp")
308 fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
309 with os.fdopen(fd, "w", newline="") as handle:
310 writer = csv.DictWriter(handle, fieldnames=TOKEN_FIELDS, delimiter="\t", extrasaction="ignore")
311 writer.writeheader()
312 for row in rows:
313 writer.writerow(row)
314 os.chmod(temp, 0o600)
315 temp.replace(path)
316
317
318# --------------------------------------------------------------------------
319# Accounts
320
321
322def normalize_email(value: str | None) -> str:
323 email = (value or "").strip()
324 if len(email) > MAX_EMAIL_LENGTH or not _EMAIL_RE.match(email):
325 raise SignupError("Enter a valid email address.")
326 return email
327
328
329def check_password(password: str | None) -> str:
330 password = password or ""
331 if len(password) < object_credentials.MIN_PASSWORD_LENGTH:
332 raise SignupError(f"Use at least {object_credentials.MIN_PASSWORD_LENGTH} characters for the password.")
333 if len(password) > object_credentials.MAX_PASSWORD_LENGTH:
334 raise SignupError("That password is too long.")
335 return password
336
337
338def register(
339 email: str,
340 *,
341 base_dir: Path | str = DEFAULT_DATA_DIR,
342 now: datetime | None = None,
343) -> dict[str, Any]:
344 """Create a pending user, with no password and no name, in a new account, unless the address already has one.
345
346 Returns ``{"outcome": "created" | "pending" | "exists", "user": {...}}``.
347 "pending": the address signed up before and never confirmed (send the
348 link again). "exists": it has an account (tell the mailbox, not the form).
349 """
350 email = normalize_email(email)
351 with _REGISTER_LOCK:
352 existing = object_identity.find_users_by_email(email, base_dir=base_dir)
353 if existing:
354 pending = [u for u in existing if u["status"] == object_identity.PENDING_STATUS]
355 if pending and len(existing) == len(pending):
356 return {"outcome": "pending", "user": pending[0]}
357 return {"outcome": "exists", "user": existing[0]}
358 account = object_identity.create_account(
359 {"name": email, "status": object_identity.ACTIVE_STATUS},
360 base_dir=base_dir,
361 now=now,
362 )
363 user = object_identity.create_user(
364 {
365 "account_id": account["account_id"],
366 "email": email,
367 "display_name": "",
368 "status": object_identity.PENDING_STATUS,
369 "roles": [],
370 },
371 base_dir=base_dir,
372 now=now,
373 )
374 return {"outcome": "created", "user": user}
375
376
377def confirm_signup(
378 token: str | None,
379 password: str | None,
380 display_name: str | None = "",
381 *,
382 base_dir: Path | str = DEFAULT_DATA_DIR,
383 now: datetime | None = None,
384) -> dict[str, Any] | None:
385 """Use a verification link: the pending user gets this password (and name) and becomes active.
386
387 None if the link is no good, or the user is not pending any more (a link
388 must never change the password of an account that is already in use).
389 Raises SignupError for a password that won't do, before the link is used,
390 so the person can try again with the same link."""
391 password = check_password(password)
392 display_name = (display_name or "").strip()[:MAX_DISPLAY_NAME_LENGTH]
393 if peek_token(token, VERIFY_EMAIL, base_dir=base_dir, now=now) is None:
394 return None
395 row = consume_token(token, VERIFY_EMAIL, base_dir=base_dir, now=now)
396 if row is None:
397 return None
398 try:
399 user = object_identity.get_user(row["user_id"], base_dir=base_dir)
400 except (LookupError, ValueError):
401 return None
402 if user["status"] != object_identity.PENDING_STATUS:
403 return None
404 # the link was sent to one address; if the user's address has changed
405 # since, it no longer proves anything about this user
406 if (user.get("email") or "").strip().casefold() != (row.get("email") or "").strip().casefold():
407 return None
408 object_credentials.set_password(user["user_id"], password, base_dir=base_dir)
409 return object_identity.set_user_status(
410 user["user_id"], object_identity.ACTIVE_STATUS, display_name=display_name, base_dir=base_dir, now=now,
411 )
412
413
414def reset_password(
415 token: str | None,
416 password: str | None,
417 *,
418 base_dir: Path | str = DEFAULT_DATA_DIR,
419 now: datetime | None = None,
420) -> dict[str, Any] | None:
421 """Use a reset link to set a new password. None if the link is no good.
422
423 Raises SignupError for a password that won't do -- before the link is
424 used, so the person can try again with the same link. Every session the
425 user had is revoked: whoever knew the old password is signed out. A
426 pending user becomes active, since the link proved they hold the mailbox."""
427 password = check_password(password)
428 if peek_token(token, PASSWORD_RESET, base_dir=base_dir, now=now) is None:
429 return None
430 row = consume_token(token, PASSWORD_RESET, base_dir=base_dir, now=now)
431 if row is None:
432 return None
433 user = _activate_if_pending(row, base_dir=base_dir, now=now)
434 if user is None:
435 return None
436 object_credentials.set_password(user["user_id"], password, base_dir=base_dir)
437 object_identity.revoke_user_sessions(user["user_id"], base_dir=base_dir, now=now)
438 return user
439
440
441def reset_candidate(email: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> dict[str, Any] | None:
442 """The one user a reset for this address would go to, or None.
443
444 Disabled users get nothing: an operator turned them off, and a reset
445 link must not be a way back in."""
446 try:
447 email = normalize_email(email)
448 except SignupError:
449 return None
450 users = [
451 u for u in object_identity.find_users_by_email(email, base_dir=base_dir)
452 if u["status"] in (object_identity.ACTIVE_STATUS, object_identity.PENDING_STATUS)
453 ]
454 return users[0] if len(users) == 1 else None
455
456
457def _activate_if_pending(row: Mapping[str, str], *, base_dir: Path | str, now: datetime | None) -> dict[str, Any] | None:
458 try:
459 user = object_identity.get_user(row["user_id"], base_dir=base_dir)
460 except (LookupError, ValueError):
461 return None
462 # the link was sent to one address; if the user's address has changed
463 # since, it no longer proves anything about this user
464 if (user.get("email") or "").strip().casefold() != (row.get("email") or "").strip().casefold():
465 return None
466 if user["status"] == object_identity.DISABLED_STATUS:
467 return None
468 if user["status"] == object_identity.PENDING_STATUS:
469 user = object_identity.set_user_status(user["user_id"], object_identity.ACTIVE_STATUS, base_dir=base_dir, now=now)
470 return user
471
472
473# --------------------------------------------------------------------------
474# The emails
475
476
477def link(base_url: str, path: str, token: str | None = None) -> str:
478 url = base_url.rstrip("/") + path
479 if token is not None:
480 url += "?" + urllib.parse.urlencode({"token": token})
481 return url
482
483
484def verification_email(base_url: str, token: str) -> tuple[str, str]:
485 hours = int(TOKEN_TTL[VERIFY_EMAIL].total_seconds() // 3600)
486 return (
487 "Confirm your email address",
488 "Someone (hopefully you) created an account with this email address.\n\n"
489 f"To confirm it and choose your password, open this link within {hours} hours:\n\n"
490 f"{link(base_url, '/verify', token)}\n\n"
491 "If it wasn't you, ignore this email: nobody can sign in to the account without a link sent to this address.\n",
492 )
493
494
495def already_registered_email(base_url: str, reset_available: bool) -> tuple[str, str]:
496 body = (
497 "Someone (hopefully you) tried to create an account with this email address, "
498 "but it already has one.\n\n"
499 f"Sign in here: {link(base_url, '/login')}\n"
500 )
501 if reset_available:
502 body += f"Forgot your password? Reset it here: {link(base_url, '/reset')}\n"
503 body += "\nIf it wasn't you, ignore this email: nothing has changed.\n"
504 return ("You already have an account", body)
505
506
507def reset_email(base_url: str, token: str) -> tuple[str, str]:
508 minutes = int(TOKEN_TTL[PASSWORD_RESET].total_seconds() // 60)
509 return (
510 "Reset your password",
511 "Someone (hopefully you) asked to reset the password for this email address.\n\n"
512 f"To choose a new password, open this link within {minutes} minutes:\n\n"
513 f"{link(base_url, '/reset/confirm', token)}\n\n"
514 "If it wasn't you, ignore this email: your password stays as it is.\n",
515 )
516
517
518def send(to: str, subject_and_body: tuple[str, str], *, base_dir: Path | str = DEFAULT_DATA_DIR) -> str:
519 subject, body = subject_and_body
520 return object_email.enqueue(to, subject, body, source_object_id="object_signup", base_dir=base_dir)
521
522
523# --------------------------------------------------------------------------
524
525
526def _stamp(value: datetime) -> str:
527 return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
528
529
530def _parse(value: str) -> datetime:
531 return datetime.fromisoformat(value.replace("Z", "+00:00"))
532
533
534def _now() -> datetime:
535 return datetime.now(timezone.utc)