diff --git a/Dockerfile b/Dockerfile index 72d4bde..825b235 100644 --- a/Dockerfile +++ b/Dockerfile @@ -23,13 +23,31 @@ RUN pip install --upgrade pip && \ # Install Firefox (and its system libraries) for Playwright gas price snapshots. # Firefox, not Chromium: cbc.ca's CDN blocks headless Chromium (ERR_HTTP2_PROTOCOL_ERROR). -RUN playwright install --with-deps firefox +# A shared path (not /root/.cache) so the unprivileged app user can launch it. +ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright +RUN playwright install --with-deps firefox && chmod -R a+rX /ms-playwright + +# The app runs as an unprivileged user, not root: a bug that lets someone run +# code in the container then can't read root-only files, install packages or +# change the image. Its uid/gid should match the host user that owns the +# mounted folders (./logs, the AdGuard rules repo, the SSH key folder), so set +# APP_UID / APP_GID in .env to `id -u` / `id -g` if they aren't 1000. +ARG APP_UID=1000 +ARG APP_GID=1000 +# safe.directory: the rules repo is bind-mounted from the host, so tell git it +# is expected at that path. +RUN groupadd --non-unique --gid ${APP_GID} app \ + && useradd --non-unique --create-home --uid ${APP_UID} --gid ${APP_GID} app \ + && git config --system --add safe.directory /app/adguard_rules # Copy the project files -COPY . . +COPY --chown=app:app . . # Create logs directory -RUN mkdir -p logs +RUN mkdir -p logs && chown app:app /app /app/logs + +USER app +ENV HOME=/home/app # Expose the port the app runs on EXPOSE 8000 diff --git a/README.md b/README.md index 5afbd74..ca7f7a8 100644 --- a/README.md +++ b/README.md @@ -56,8 +56,14 @@ pip install -e . (both the SQLAlchemy ones and the raw-SQL ones), so it is the shortest path: ```bash psql -d safefamily < scripts/schema.sql +python scripts/migrate.py ``` -Regenerate it from a live database with `python scripts/db_export.py schema`. +`migrate.py` is required, not optional: it adds what is newer than the +`schema.sql` snapshot (for example `users.is_approved`, which every login reads, +and the `lotto_photos` table). It is safe to re-run, so run it after every +update too. + +Regenerate `schema.sql` from a live database with `python scripts/db_export.py schema`. If you would rather build it piecemeal: - SQLAlchemy models expect tables for users and notes. @@ -113,9 +119,31 @@ data instead. ### 3. Key Mounts and Overrides - **Logs**: Backend logs are mirrored to the local `./logs` directory. -- **SSH Keys**: Local `~/.ssh` is mounted read-only to `/root/.ssh` in the `app` container to support Git operations. +- **SSH Keys**: `SSH_KEY_DIR` (default `~/.ssh`) is mounted read-only to `/home/app/.ssh` in the `app` container to support Git operations. Prefer a folder that holds only a deploy key for the rules repository; see [Running as a non-root user](#running-as-a-non-root-user). - **AdGuard Rules**: The directory specified by `HOST_ADGUARD_RULE_PATH` in your `.env` is mounted to allow rule manipulation. +#### Running as a non-root user +The `app` container runs as the unprivileged user `app`, not root. Files it +touches on the host must belong to the same uid/gid: + +```bash +# .env — only needed when `id -u` / `id -g` are not 1000 +APP_UID=1000 +APP_GID=1000 +# A folder with just the rules repo's deploy key, instead of all of ~/.ssh +SSH_KEY_DIR=/home/you/.ssh-safefamily +``` + +- `./logs` and the `HOST_ADGUARD_RULE_PATH` repo must be writable by that user + (`sudo chown -R $(id -u):$(id -g) logs` if an older root-run container + created them). +- Rebuild after changing the uid: `docker-compose up -d --build app`. +- To use a dedicated deploy key: `ssh-keygen -t ed25519 -f ~/.ssh-safefamily/id_ed25519`, + add the `.pub` as a **deploy key with write access** on the rules repository + only, and copy your `known_hosts` into the same folder. A leaked deploy key + can push to that one repository and nothing else. +- Commands that need root inside the container: `docker exec -u root safefamily_app ...`. + ### 4. Useful Commands - **Start / Stop (daily use)**: `docker compose start` / `docker compose stop` - **View Logs**: `docker-compose logs -f app` @@ -344,10 +372,20 @@ Example `DB_PARAMS`: ``` Accounts: -- `ALLOW_REGISTRATION`: new accounts are refused unless this is `True`. That - covers the register form, `POST /auth/register`, and first-time Google/GitHub - sign-in. Existing accounts can always log in. Set it to `True` only while - adding a family member, then remove it and restart the app. +- Sign-up is open, but a new account is **unapproved**: it gets its own todo + list, notes and draft blog posts, and nothing else. Approve family members + under **MGMT → Accounts**. Only approved accounts (and the admin) can use the + rule buttons that change the network filter, trigger email/Discord + notifications, or publish public blog posts. +- `ALLOW_REGISTRATION`: set to `False` to refuse new accounts entirely (register + form, `POST /auth/register`, and first-time Google/GitHub sign-in). Default + `True`. +- Google/GitHub sign-in only uses an email the provider has verified, and only + matches an existing account by email if that account was itself created by + Google/GitHub sign-in. An account made with the register form is reached with + its password only. +- Usernames are unique. A Google/GitHub display name that is already taken gets + a suffix (`Alex-2`). Notesync: - `NOTESYNC_API_KEY` diff --git a/config/settings.py b/config/settings.py index dc5e5ad..eb2a399 100644 --- a/config/settings.py +++ b/config/settings.py @@ -114,10 +114,11 @@ class Settings: "APP_MOTTO", ) - # New accounts (form, API and first-time Google/GitHub sign-in) are refused - # unless this is "True". Existing accounts can always log in. Turn it on - # only while adding a family member, then off again. - ALLOW_REGISTRATION = os.environ.get("ALLOW_REGISTRATION", "False") == "True" + # Sign-up is open by default: a new account only gets its own todo list, + # notes and draft posts until the admin approves it on the MGMT page (see + # User.is_approved). Set this to "False" to refuse new accounts entirely + # (form, API and first-time Google/GitHub sign-in). + ALLOW_REGISTRATION = os.environ.get("ALLOW_REGISTRATION", "True") == "True" # Countdown page settings (date in YYYY-MM-DD) COUNTDOWN_DATE = os.environ.get("COUNTDOWN_DATE", "") diff --git a/docker-compose.yml b/docker-compose.yml index 033ce48..db60778 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -15,7 +15,12 @@ services: - ./deploy/init_db:/docker-entrypoint-initdb.d app: - build: . + build: + context: . + args: + # Match the host user that owns ./logs, the rules repo and the SSH keys. + APP_UID: ${APP_UID:-1000} + APP_GID: ${APP_GID:-1000} container_name: safefamily_app restart: always depends_on: @@ -25,8 +30,10 @@ services: - ./logs:/app/logs # Mount your local AdGuard repo directory - ${HOST_ADGUARD_RULE_PATH}:/app/adguard_rules - # Mount SSH keys for git push operations - - ~/.ssh:/root/.ssh:ro + # SSH key for pushing the rules repo, read-only, for the unprivileged app + # user. Point SSH_KEY_DIR at a folder holding ONLY a deploy key for that + # one repo (plus known_hosts/config) instead of your whole ~/.ssh. + - ${SSH_KEY_DIR:-~/.ssh}:/home/app/.ssh:ro environment: - PYTHONUNBUFFERED=1 - GUNICORN_WORKERS=4 diff --git a/scripts/migrate.py b/scripts/migrate.py index 9f92e74..0a150ee 100644 --- a/scripts/migrate.py +++ b/scripts/migrate.py @@ -12,6 +12,28 @@ from src.safe_family.core.extensions import get_db_connection MIGRATIONS = [ + # Admin approval for accounts (see User.is_approved). Accounts that exist + # when this first runs stay approved; accounts created afterwards start + # unapproved. Both statements are safe to re-run. + """ + ALTER TABLE users ADD COLUMN IF NOT EXISTS is_approved BOOLEAN NOT NULL DEFAULT TRUE + """, + """ + ALTER TABLE users ALTER COLUMN is_approved SET DEFAULT FALSE + """, + # The todo lists are keyed by username, so usernames must be unique. Skipped + # (with a notice) while duplicates exist: rename them, then re-run. + """ + DO $$ + BEGIN + IF EXISTS (SELECT 1 FROM users GROUP BY username HAVING count(*) > 1) THEN + RAISE NOTICE 'users.username has duplicates: unique index NOT created'; + ELSE + CREATE UNIQUE INDEX IF NOT EXISTS uq_users_username ON users (username); + END IF; + END; + $$ + """, # Speeds up per-user history scans (week strip / activity heatmap on /todo) # and the existing per-day lookups. """ diff --git a/src/safe_family/core/auth.py b/src/safe_family/core/auth.py index fcbb138..adf5796 100644 --- a/src/safe_family/core/auth.py +++ b/src/safe_family/core/auth.py @@ -46,6 +46,79 @@ OAUTH_STATE_TTL_SECONDS = 600 MIN_PASSWORD_LENGTH = 8 REGISTRATION_CLOSED = "Registration is closed. Ask the admin to add you." +NOT_APPROVED = "Your account is waiting for the admin's approval, so this is not available yet." +EMAIL_TAKEN = ( + "An account with this email already exists. Log in with your username and " + "password instead." +) +EMAIL_UNVERIFIED = "Your email address is not verified with this provider, so it can't be used to sign in." + + +def is_family(user: User | None) -> bool: + """Return True for the admin and for accounts the admin has approved. + + Sign-up is open, so being logged in proves nothing about who you are. + Anything that affects the household (the network filter, notifications, + public posts) must check this, not just login. + """ + return user is not None and (user.role == "admin" or bool(getattr(user, "is_approved", False))) + + +def family_required(view_func: Callable) -> Callable: + """Require a logged-in, admin-approved account for a view.""" + + @wraps(view_func) + def wrapped(*args: object, **kwargs: object) -> object: + if not is_family(get_current_username()): + flash(NOT_APPROVED, "warning") + return redirect("/") + return view_func(*args, **kwargs) + + return login_required(wrapped) + + +def unique_username(wanted: str) -> str: + """Return ``wanted``, or ``wanted-2``, ``wanted-3``... if it is taken. + + Todo lists are keyed by username, so two accounts must never share one. + Google/GitHub display names are not unique ("Alex"), hence the suffix. + """ + base = (wanted or "").strip() or "user" + candidate, n = base, 1 + while User.get_user_by_username(username=candidate) is not None: + n += 1 + candidate = f"{base}-{n}" + return candidate + + +def _created_by_oauth(user: User) -> bool: + """Return True for accounts first created by a Google/GitHub sign-in. + + Those get the provider's numeric account id as their id; password sign-ups + get a UUID. Only provider-created accounts have an email the provider + verified, so only they may be matched by email. + """ + return str(user.id).isdigit() + + +def find_oauth_user(provider_id: str, email: str, *, email_verified: bool) -> tuple[User | None, str | None]: + """Find the account for a Google/GitHub sign-in: (user, refusal message). + + The provider's own account id always matches. An email only matches when + the provider verified it AND the existing account was itself created by a + provider. An email typed into the sign-up form was never verified, so + letting a later Google/GitHub login land in such an account would hand it + to whoever registered first with someone else's address. + """ + user = User.query.filter_by(id=provider_id).first() + if user is not None: + return user, None + existing = User.query.filter_by(email=email).first() + if existing is None: + return None, None + if email_verified and _created_by_oauth(existing): + return existing, None + return None, EMAIL_TAKEN def require_api_key(view_func: Callable) -> Callable: @@ -293,6 +366,8 @@ def session_login(): session["refresh_token"] = tokens.get("refresh_token") flash("Login successful!", "success") + if not is_family(get_current_username()): + flash(NOT_APPROVED, "info") return redirect("/") @@ -641,29 +716,24 @@ def github_callback(): # noqa: C901, PLR0911, PLR0912, PLR0915 - refactor backl if emails_response.status_code == HTTP_OK: emails = emails_response.json() - email = user_info.get("email") - if not email and emails: - primary_verified = [ - entry for entry in emails if entry.get("primary") and entry.get("verified") - ] - verified = [entry for entry in emails if entry.get("verified")] - selection = ( - primary_verified[0] - if primary_verified - else verified[0] - if verified - else emails[0] - ) - email = selection.get("email") - if not email: + # Only an address GitHub has verified identifies the person. An + # unverified one can be typed in by anyone, so it is never used. + verified = [entry for entry in emails if entry.get("verified") and entry.get("email")] + primary = [entry for entry in verified if entry.get("primary")] + email_verified = bool(verified) + if verified: + email = (primary or verified)[0]["email"] + else: + # GitHub's own per-account placeholder: nobody else can hold it. login_name = user_info.get("login", "github_user") email = f"{login_name}@users.noreply.github.com" github_id = str(user_info.get("id")) name = user_info.get("name") or user_info.get("login") or email.split("@")[0] - user = User.query.filter_by(id=github_id).first() - if not user: - user = User.query.filter_by(email=email).first() + user, refusal = find_oauth_user(github_id, email, email_verified=email_verified) + if refusal: + flash(refusal, "warning") + return redirect("/auth/login-ui") if not user and not settings.ALLOW_REGISTRATION: flash(REGISTRATION_CLOSED, "warning") @@ -672,7 +742,7 @@ def github_callback(): # noqa: C901, PLR0911, PLR0912, PLR0915 - refactor backl if not user: new_user = User( id=github_id, - username=name, + username=unique_username(name), email=email, ) new_user.set_password(secrets.token_urlsafe(48)) @@ -688,11 +758,13 @@ def github_callback(): # noqa: C901, PLR0911, PLR0912, PLR0915 - refactor backl session["access_token"] = create_access_token(identity=user.id) session["refresh_token"] = create_refresh_token(identity=user.id) flash("Login successful!", "success") + if not is_family(get_current_username()): + flash(NOT_APPROVED, "info") return redirect("/") @auth_bp.get("/google/callback") -def google_callback(): +def google_callback(): # noqa: PLR0911 - one early return per refusal """Handle the Google OAuth callback and create the session.""" state = request.args.get("state") state_payload = _read_oauth_state(state) @@ -721,10 +793,14 @@ def google_callback(): ) google_id = id_info["sub"] email = id_info["email"] - name = id_info.get("name", "") - user = User.query.filter_by(id=google_id).first() - if not user: - user = User.query.filter_by(email=email).first() + name = id_info.get("name", "") or email.split("@")[0] + if not id_info.get("email_verified"): + flash(EMAIL_UNVERIFIED, "warning") + return redirect("/auth/login-ui") + user, refusal = find_oauth_user(google_id, email, email_verified=True) + if refusal: + flash(refusal, "warning") + return redirect("/auth/login-ui") if not user and not settings.ALLOW_REGISTRATION: flash(REGISTRATION_CLOSED, "warning") @@ -733,7 +809,7 @@ def google_callback(): if not user: new_user = User( id=google_id, - username=name, + username=unique_username(name), email=email, ) new_user.set_password(secrets.token_urlsafe(48)) @@ -749,6 +825,8 @@ def google_callback(): session["access_token"] = create_access_token(identity=user.id) session["refresh_token"] = create_refresh_token(identity=user.id) flash("Login successful!", "success") + if not is_family(get_current_username()): + flash(NOT_APPROVED, "info") return redirect("/") diff --git a/src/safe_family/core/models.py b/src/safe_family/core/models.py index 7af80a8..b12d198 100644 --- a/src/safe_family/core/models.py +++ b/src/safe_family/core/models.py @@ -13,11 +13,15 @@ class User(db.Model): __tablename__ = "users" - id = db.Column(db.String(), primary_key=True, default=(uuid.uuid4)) + id = db.Column(db.String(), primary_key=True, default=lambda: str(uuid.uuid4())) username = db.Column(db.String(), nullable=False) email = db.Column(db.String(), unique=True, nullable=False) password_hash = db.Column(db.String(256), nullable=False) role = db.Column(db.String(20)) + # Anyone may sign up, but only accounts the admin has approved count as + # family: they may change the shared network filter, send notifications and + # publish public posts. New accounts start unapproved. + is_approved = db.Column(db.Boolean(), nullable=False, default=False) created_at = db.Column(db.DateTime, default=lambda: datetime.now(UTC)) updated_at = db.Column( db.DateTime, diff --git a/src/safe_family/templates/rules/suspicious_view.html b/src/safe_family/templates/rules/suspicious_view.html index 10d4a8b..01c53c8 100644 --- a/src/safe_family/templates/rules/suspicious_view.html +++ b/src/safe_family/templates/rules/suspicious_view.html @@ -7,6 +7,33 @@ 🎟️ Lotto ticket counter Collect and label display photos, export training data, upload predictions. +
Anyone can sign up, but only accounts you approve count as family: they can use + the rule buttons, send notifications and publish public posts. Unapproved accounts only get their own + todo list, notes and draft posts.
+| User | Status | Action | |
|---|---|---|---|
| {{ account.username }} | +{{ account.email }} | +{{ 'Family' if account.is_approved else 'Waiting' }} | ++ + | +