From e30e6fdc10d7abeeb4bf1711a96a6900c24d216b Mon Sep 17 00:00:00 2001 From: Angel Rocha Date: Mon, 5 Oct 2026 12:51:22 -0700 Subject: [PATCH 1/3] Account creation --- .env.example | 5 - AGENTS.md | 27 +-- README.md | 29 ++-- compose.yml | 2 - docs/decisions/001-fixed-demo-sign-in.md | 2 +- docs/decisions/002-internal-email-accounts.md | 38 +++++ ...shboard-visual-prototype-implementation.md | 3 + docs/plans/proposed-schema-erd.md | 19 ++- docs/specs/dashboard-visual-prototype.md | 43 +++-- docs/specs/internal-team-accounts.md | 62 +++++++ schema.sql | 12 +- src/accounts/__init__.py | 1 + src/accounts/apps.py | 8 + src/accounts/forms.py | 89 ++++++++++ src/accounts/migrations/0001_initial.py | 108 ++++++++++++ src/accounts/migrations/__init__.py | 1 + src/accounts/models.py | 74 +++++++++ src/accounts/templates/accounts/register.html | 37 +++++ src/accounts/templates/accounts/sign_in.html | 34 ++++ src/accounts/urls.py | 11 ++ src/accounts/views.py | 50 ++++++ src/dashboard/__init__.py | 2 +- src/dashboard/static/dashboard/styles.css | 3 + .../templates/dashboard/preview.html | 27 +-- src/dashboard/views.py | 45 +---- src/skillstreak/settings/base.py | 17 +- src/skillstreak/urls.py | 7 +- tests/application/test_accounts.py | 156 ++++++++++++++++++ tests/application/test_dashboard.py | 79 +++------ 29 files changed, 794 insertions(+), 197 deletions(-) create mode 100644 docs/decisions/002-internal-email-accounts.md create mode 100644 docs/specs/internal-team-accounts.md create mode 100644 src/accounts/__init__.py create mode 100644 src/accounts/apps.py create mode 100644 src/accounts/forms.py create mode 100644 src/accounts/migrations/0001_initial.py create mode 100644 src/accounts/migrations/__init__.py create mode 100644 src/accounts/models.py create mode 100644 src/accounts/templates/accounts/register.html create mode 100644 src/accounts/templates/accounts/sign_in.html create mode 100644 src/accounts/urls.py create mode 100644 src/accounts/views.py create mode 100644 tests/application/test_accounts.py diff --git a/.env.example b/.env.example index d17f6e1..cb4f6e9 100644 --- a/.env.example +++ b/.env.example @@ -10,8 +10,3 @@ DJANGO_SECRET_KEY=replace-with-a-local-development-only-value DJANGO_DEBUG=true ALLOWED_HOSTS=localhost,127.0.0.1 DATABASE_URL=postgresql://skillstreak:change-me-for-local-development@db:5432/skillstreak - -# Fixed local MVP sign-in. Choose both values in your untracked .env file. -# Do not commit the real values or use this demo sign-in in production. -DEMO_LOGIN_EMAIL=demo@example.com -DEMO_LOGIN_PASSWORD=choose-a-password diff --git a/AGENTS.md b/AGENTS.md index 21c3547..fb536d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,13 +2,13 @@ ## Status and source of truth -This repository is at the infrastructure-foundation stage. Read +This repository is at the first-account-slice stage. Read `infrastructure_plan.md` before changing tooling, Docker, CI, dependency, or delivery decisions. The currently implemented configuration follows that plan: Python 3.14, Django 5.2 LTS, pip-tools, local PostgreSQL in Compose, and planned Google Cloud Run delivery through Artifact Registry. The first product slice is -a local, fixed-demo sign-in and visual dashboard; database-backed product -behavior does not exist yet. +internal `@csuchico.edu` account registration and a visual dashboard; +user-owned skill/progress behavior does not exist yet. ## Repository map @@ -19,13 +19,14 @@ behavior does not exist yet. - `tests/infrastructure/`: configuration harness tests only. - `.github/workflows/`: `pr-checks.yml` and guarded `release.yml`. - `.agents/skills/`: repository-provided skills. -- `src/dashboard/`: Django fixed-demo sign-in and dashboard; it has no product - data persistence. -- `docs/specs/dashboard-visual-prototype.md`: approved MVP sign-in scope. -- `docs/decisions/001-fixed-demo-sign-in.md`: rationale for the temporary - sign-in design. -- Database-backed product apps, API endpoints, migration files, real accounts, - and browser tests: **not created yet**. +- `src/accounts/`: email-only internal team accounts and first user migration. +- `src/dashboard/`: authenticated static dashboard; it has no user-owned + product data persistence. +- `docs/specs/internal-team-accounts.md`: approved account scope. +- `docs/decisions/002-internal-email-accounts.md`: account-authentication + rationale. +- Database-backed skills/progress apps, API endpoints, and browser tests: + **not created yet**. ## Required reading and skill routing @@ -42,9 +43,9 @@ apply. ## Boundaries -- During infrastructure work, do not create Django apps, pages, routes, models, - domain schemas, authentication flows, business logic, product fixtures, or - production data. +- During infrastructure work, do not create unrelated Django apps, pages, + routes, models, domain schemas, authentication flows, business logic, product + fixtures, or production data. - Do not change a plan decision without updating `infrastructure_plan.md` through the planning workflow. - Never commit secrets, `.env` files, credentials, generated reports, local diff --git a/README.md b/README.md index 3da7913..2714149 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,11 @@ # SkillStreak -SkillStreak is planned as a public, multi-account Django web application with -PostgreSQL. This repository currently contains its development, quality, Docker, -delivery foundation, a minimal Django source framework, liveness route, and a -local fixed-demo dashboard sign-in at `/`. No database-backed product schema, -real account system, API, or production deployment exists yet. +SkillStreak is planned as a multi-account Django web application with PostgreSQL. +This repository currently contains its development, quality, Docker, delivery +foundation, a minimal Django source framework, liveness route, internal +`@csuchico.edu` account registration/sign-in, and a static sample dashboard at +`/`. No user-owned skill/progress schema, API, or production deployment exists +yet. ## Repository map @@ -17,8 +18,8 @@ real account system, API, or production deployment exists yet. | `tests/application/`, `tests/infrastructure/` | Django framework and infrastructure tests | Ready | | `docs/specs/`, `docs/plans/` | Reviewed specifications and implementation plans | Bootstrap work documented | | `.github/workflows/` | Pull-request checks and guarded Cloud Run release workflow | Ready | -| `src/`, `manage.py` | Django project framework, liveness endpoint, and fixed-demo dashboard | Ready; no database-backed product behavior | -| `docs/specs/dashboard-visual-prototype.md` | Approved fixed-demo MVP scope | Current | +| `src/`, `manage.py` | Django framework, liveness endpoint, team accounts, and sample dashboard | Ready; no user-owned product behavior | +| `docs/specs/internal-team-accounts.md` | Approved internal-account scope | Current | | `.agents/skills/` | Repository-specific agent guidance | Available | ## Getting Started @@ -45,11 +46,15 @@ real account system, API, or production deployment exists yet. ``` The application listens on `http://localhost:8000` by default. Set - `APP_PORT` in `.env` to choose another host port. The root page provides a - fixed-demo sign-in. Set `DEMO_LOGIN_EMAIL` and `DEMO_LOGIN_PASSWORD` in your - untracked `.env` file before starting it; only that pair can access the - sample dashboard. This temporary sign-in is for local MVP validation, not - production accounts. Verify its liveness endpoint from another terminal: + `APP_PORT` in `.env` to choose another host port. Run migrations before + registering an internal `@csuchico.edu` account and accessing the sample + dashboard: + + ```sh + docker compose exec web python manage.py migrate + ``` + + Verify its liveness endpoint from another terminal: ```sh curl --fail http://localhost:8000/healthz diff --git a/compose.yml b/compose.yml index 86f78b5..1205b44 100644 --- a/compose.yml +++ b/compose.yml @@ -13,8 +13,6 @@ services: DJANGO_DEBUG: ${DJANGO_DEBUG:-true} DJANGO_SECRET_KEY: ${DJANGO_SECRET_KEY:-replace-with-a-local-development-only-value} DJANGO_SETTINGS_MODULE: skillstreak.settings.local - DEMO_LOGIN_EMAIL: ${DEMO_LOGIN_EMAIL:-} - DEMO_LOGIN_PASSWORD: ${DEMO_LOGIN_PASSWORD:-} networks: [application] ports: - "${APP_PORT:-8000}:8000" diff --git a/docs/decisions/001-fixed-demo-sign-in.md b/docs/decisions/001-fixed-demo-sign-in.md index 5c52f59..b6628aa 100644 --- a/docs/decisions/001-fixed-demo-sign-in.md +++ b/docs/decisions/001-fixed-demo-sign-in.md @@ -2,7 +2,7 @@ ## Status -Accepted — 2026-09-30 +Superseded by [ADR-002](002-internal-email-accounts.md) — 2026-10-05 ## Context diff --git a/docs/decisions/002-internal-email-accounts.md b/docs/decisions/002-internal-email-accounts.md new file mode 100644 index 0000000..078097e --- /dev/null +++ b/docs/decisions/002-internal-email-accounts.md @@ -0,0 +1,38 @@ +# ADR-002: Use email-only internal team accounts + +## Status + +Accepted — 2026-10-05 + +Supersedes [ADR-001](001-fixed-demo-sign-in.md). + +## Context + +The fixed demo credential was appropriate for the first visual prototype but +cannot provide separate, durable accounts for the project team. The team needs +self-service registration and normal returning-user sign-in without adding an +outbound email provider or public-account lifecycle. + +## Decision + +Use a custom Django user model from the first project migration. Its normalized +`@csuchico.edu` email address is the unique login identifier; there is no +username. Store Django authentication sessions in PostgreSQL, retain the +existing fourteen-day session age, and use Django's built-in password validators +and password hashing. + +Registration creates a usable account immediately. It verifies the domain only, +not mailbox ownership. Sign-in, duplicate registration, and redirect behavior +avoid disclosure beyond generic failure messages and the dashboard always +redirects unauthenticated visitors to the sign-in page. + +## Consequences + +- The custom user model must remain configured before the first applied shared + migration; a database already migrated with `auth.User` requires a separately + reviewed migration project. +- No email verification means email addresses are not trusted recovery or + notification channels. Password reset/change, email change, invitations, and + account deletion are intentionally deferred. +- The demo environment credentials and signed-cookie authorization marker are + removed. Existing demo cookies cannot authorize the dashboard. diff --git a/docs/plans/dashboard-visual-prototype-implementation.md b/docs/plans/dashboard-visual-prototype-implementation.md index d34b781..558c1d1 100644 --- a/docs/plans/dashboard-visual-prototype-implementation.md +++ b/docs/plans/dashboard-visual-prototype-implementation.md @@ -1,5 +1,8 @@ # Implementation Plan: Dashboard Visual Prototype +> Historical — authentication portions superseded by +> [Internal Team Accounts](../specs/internal-team-accounts.md). + ## Overview Replace the client-only dashboard preview with an approved, fixed-demo diff --git a/docs/plans/proposed-schema-erd.md b/docs/plans/proposed-schema-erd.md index fc35887..3d12c92 100644 --- a/docs/plans/proposed-schema-erd.md +++ b/docs/plans/proposed-schema-erd.md @@ -11,11 +11,11 @@ metrics at all, one daily metric, or several repeated measurements. ```mermaid erDiagram - AUTH_USER ||--o| USER_PREFERENCE : has - AUTH_USER ||--o{ SKILL : creates + ACCOUNTS_USER ||--o| USER_PREFERENCE : has + ACCOUNTS_USER ||--o{ SKILL : creates SKILL o|--o{ SKILL : categorizes SKILL ||--o{ METRIC_DEFINITION : declares - AUTH_USER ||--o{ USER_SKILL : tracks + ACCOUNTS_USER ||--o{ USER_SKILL : tracks SKILL ||--o{ USER_SKILL : is_selected_for USER_SKILL ||--o{ DAILY_COMPLETION : has USER_SKILL ||--o{ USER_SKILL_SCHEDULE : configures @@ -24,9 +24,9 @@ erDiagram DAILY_COMPLETION ||--o{ METRIC_MEASUREMENT : contains METRIC_DEFINITION ||--o{ METRIC_MEASUREMENT : describes - AUTH_USER { + ACCOUNTS_USER { bigint id PK - string username + string email UK } USER_PREFERENCE { @@ -111,11 +111,12 @@ erDiagram ## Entities and rules -### `AUTH_USER` +### `ACCOUNTS_USER` -The Django-configured user model. Django models must refer to it through -`settings.AUTH_USER_MODEL`, never by a hard-coded table name. The entity is -shown here only to make ownership clear. +The email-only Django-configured user model. Its normalized `@csuchico.edu` +email address is unique and is the authentication identifier. Django models +must refer to it through `settings.AUTH_USER_MODEL`, never by a hard-coded +table name. The entity is shown here only to make ownership clear. ### `USER_PREFERENCE` diff --git a/docs/specs/dashboard-visual-prototype.md b/docs/specs/dashboard-visual-prototype.md index cc92833..8ac24c7 100644 --- a/docs/specs/dashboard-visual-prototype.md +++ b/docs/specs/dashboard-visual-prototype.md @@ -2,9 +2,9 @@ ## Status -Approved — the MVP uses a fixed, environment-configured demo sign-in with a -server-side session. It is not an account-registration or password-management -feature. +Superseded for authentication by +[Internal Team Accounts](internal-team-accounts.md). The static dashboard +visual scope remains current. ## Objective @@ -15,10 +15,7 @@ responsive dashboard with illustrative skill data and streak history. ## Scope - A server-rendered home page at `/`. -- A POST-only sign-in form that accepts exactly one fixed demo identity from - `DEMO_LOGIN_EMAIL` and `DEMO_LOGIN_PASSWORD` environment variables. -- A signed, HTTP-only Django session that persists the verified state across - page loads for up to 14 days, or until the visitor logs out. +- An authenticated project-team session supplied by the internal-account flow. - A desktop sidebar, dashboard header, skill summaries, and calendar-like streak-history display inspired by the wireframe. - A predefined, filler skill library represented by static example entries. @@ -27,8 +24,8 @@ responsive dashboard with illustrative skill data and streak history. ## Out of Scope -- Django accounts, registration, password recovery, user models, migrations, - database reads/writes, and API endpoints. +- Password recovery, user-owned dashboard data, database-backed skills, and API + endpoints. - Skill detail, add-skill, social, friends, chat, settings, and messages pages. - Any claim that the illustrative progress data belongs to a real user. @@ -44,30 +41,30 @@ docker run --rm --volume "$PWD:/app" --workdir /app skillstreak-dashboard-test r ## Structure `dashboard` is a small Django app responsible for the server-rendered MVP. -Its template and CSS are colocated in the app. It compares form values against -runtime configuration with a constant-time comparison and stores only a -boolean demo-session marker in Django's signed-cookie session backend. +Its template and CSS are colocated in the app. Access is controlled by Django +authentication; illustrative dashboard values remain static example entries. ## Testing Strategy -Focused Django client tests verify successful sign-in, failed sign-in, session -persistence, logout, and dashboard content. Browser testing will verify the -desktop interaction and layout when a browser-control service is available. +Focused Django client tests verify authenticated dashboard access, logout, and +dashboard content. Account-flow tests cover registration and sign-in. Browser +testing will verify the desktop interaction and layout when a browser-control +service is available. ## Boundaries -- Always: use CSRF-protected POST forms, generic failure messages, signed +- Always: use CSRF-protected POST forms, generic failure messages, secure HTTP-only SameSite cookies, semantic HTML, and keyboard-operable controls. -- Ask first: add real accounts, database persistence, dependencies, or a - production demo-login policy. -- Never: commit the demo credential, log submitted values, or expose whether - either login field was individually correct. +- Ask first: add user-owned data, password recovery, email verification, or + outbound email. +- Never: log submitted passwords or expose whether either sign-in field was + individually correct. ## Success Criteria -- `/` returns a sign-in prompt when no valid demo session exists. +- `/` redirects to sign-in when no authenticated session exists. - Invalid sign-in attempts remain blocked with one generic error message. -- A successful sign-in reaches the dashboard and remains signed in for up to - 14 days; a POST logout clears the session immediately. +- An authenticated account reaches the dashboard and remains signed in for up + to 14 days; a POST logout clears the session immediately. - The dashboard presents filler Jogging and Reading streak history on desktop; narrow layouts remain usable. diff --git a/docs/specs/internal-team-accounts.md b/docs/specs/internal-team-accounts.md new file mode 100644 index 0000000..d8db81e --- /dev/null +++ b/docs/specs/internal-team-accounts.md @@ -0,0 +1,62 @@ +# Spec: Internal Team Accounts + +## Status + +Approved — 2026-10-05. + +## Objective + +Let SkillStreak project-team members create and use their own accounts. A +member registers with an email address at `@csuchico.edu` and a password, is +signed in immediately, and can later sign in and out using the same email and +password to reach the existing sample dashboard. + +## Scope + +- Email-only Django user accounts; no username field is collected or exposed. +- Self-service registration restricted to normalized `@csuchico.edu` email + addresses. +- Django-managed password hashing and built-in password validators. +- Server-side database sessions, CSRF-protected registration/sign-in/sign-out, + and an authenticated dashboard route. +- Case-insensitive email storage and lookup by trimming and Unicode-casefolding + the supplied email before storage or authentication. + +## Out of Scope + +- Public registration, invitation workflows, email verification, outbound email, + password reset/change, email changes, account deletion, and user-owned skill + or progress data. +- Proof that the person registering controls the supplied email address. Domain + restriction is an accepted internal-prototype boundary, not verification. + +## Commands + +```sh +docker compose up --build +docker compose exec web python manage.py migrate +docker compose exec web pytest +docker compose exec web ruff format --check . +docker compose exec web ruff check . +``` + +## Boundaries + +- Always: validate form input on the server, use Django password hashing and + validation, use CSRF-protected POST forms, and return generic invalid-login + and duplicate-registration errors. +- Ask first: add an outbound-email provider, password recovery, user-data + persistence, role management, invitations, or rate limiting. +- Never: commit credentials, log passwords, reveal which sign-in field failed, + or redirect to an arbitrary caller-supplied URL. + +## Success Criteria + +- An anonymous visitor is redirected from `/` to `/sign-in`. +- A `@csuchico.edu` member can register, is signed in immediately, and reaches + the sample dashboard. +- An outside-domain email, duplicate email, invalid password, mismatched + password, or invalid sign-in never creates an authenticated session. +- A returning member can sign in and sign out using email and password. +- The session is server-side and the dashboard displays the signed-in email, + not demo identity content. diff --git a/schema.sql b/schema.sql index c9af985..e53cddf 100644 --- a/schema.sql +++ b/schema.sql @@ -6,8 +6,8 @@ -- to a production database. -- -- Preconditions: --- * Django's configured user table is the default auth_user table. --- * auth_user.id is an integer primary key. +-- * Django's configured user table is accounts_user. +-- * accounts_user.id is a bigint primary key. -- If a custom Django user model is adopted, generate the foreign keys from -- settings.AUTH_USER_MODEL in Django migrations instead of editing this file. @@ -17,15 +17,15 @@ CREATE EXTENSION IF NOT EXISTS btree_gist; CREATE TABLE user_preferences ( id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, - user_id integer NOT NULL UNIQUE - REFERENCES auth_user (id) ON DELETE CASCADE, + user_id bigint NOT NULL UNIQUE + REFERENCES accounts_user (id) ON DELETE CASCADE, timezone varchar(63) NOT NULL DEFAULT 'UTC' ); CREATE TABLE skills ( id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, parent_id bigint REFERENCES skills (id) ON DELETE RESTRICT, - created_by_id integer REFERENCES auth_user (id) ON DELETE SET NULL, + created_by_id bigint REFERENCES accounts_user (id) ON DELETE SET NULL, slug varchar(64) NOT NULL UNIQUE, name varchar(100) NOT NULL, description text NOT NULL DEFAULT '', @@ -71,7 +71,7 @@ CREATE TABLE metric_definitions ( CREATE TABLE user_skills ( id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, - user_id integer NOT NULL REFERENCES auth_user (id) ON DELETE CASCADE, + user_id bigint NOT NULL REFERENCES accounts_user (id) ON DELETE CASCADE, skill_id bigint NOT NULL REFERENCES skills (id) ON DELETE RESTRICT, started_on date NOT NULL, is_active boolean NOT NULL DEFAULT true, diff --git a/src/accounts/__init__.py b/src/accounts/__init__.py new file mode 100644 index 0000000..357c1fd --- /dev/null +++ b/src/accounts/__init__.py @@ -0,0 +1 @@ +"""Internal team account application.""" diff --git a/src/accounts/apps.py b/src/accounts/apps.py new file mode 100644 index 0000000..43f1469 --- /dev/null +++ b/src/accounts/apps.py @@ -0,0 +1,8 @@ +from django.apps import AppConfig + + +class AccountsConfig(AppConfig): + """Configure the internal team account application.""" + + default_auto_field = "django.db.models.BigAutoField" + name = "accounts" diff --git a/src/accounts/forms.py b/src/accounts/forms.py new file mode 100644 index 0000000..8b30348 --- /dev/null +++ b/src/accounts/forms.py @@ -0,0 +1,89 @@ +"""Forms for creating and authenticating internal team accounts.""" + +from django import forms +from django.contrib.auth import authenticate, password_validation +from django.core.exceptions import ValidationError + +from .models import User, is_team_email, normalize_email + +ACCOUNT_CREATION_ERROR = "We couldn't create an account with those details." + + +class RegistrationForm(forms.Form): + """Validate a new self-service account without exposing duplicate emails.""" + + email = forms.EmailField( + widget=forms.EmailInput(attrs={"autocomplete": "email", "autofocus": True}) + ) + password1 = forms.CharField( + label="Password", + widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), + ) + password2 = forms.CharField( + label="Confirm password", + widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), + ) + + def clean_email(self) -> str: + email = normalize_email(self.cleaned_data["email"]) + if not is_team_email(email): + raise ValidationError("Use your @csuchico.edu email address.") + if User.objects.filter(email=email).exists(): + raise ValidationError(ACCOUNT_CREATION_ERROR) + return email + + def clean(self) -> dict[str, str]: + cleaned_data = super().clean() + password1 = cleaned_data.get("password1") + password2 = cleaned_data.get("password2") + + if password1 and password2 and password1 != password2: + self.add_error("password2", "The two password fields didn't match.") + elif password1: + user = User(email=cleaned_data.get("email", "")) + try: + password_validation.validate_password(password1, user) + except ValidationError as error: + self.add_error("password1", error) + + return cleaned_data + + def save(self) -> User: + """Create the validated account with Django-managed password hashing.""" + return User.objects.create_user( + email=self.cleaned_data["email"], password=self.cleaned_data["password1"] + ) + + +class SignInForm(forms.Form): + """Authenticate a registered team member by email and password.""" + + email = forms.EmailField( + widget=forms.EmailInput(attrs={"autocomplete": "email", "autofocus": True}) + ) + password = forms.CharField( + widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}) + ) + + def __init__(self, request=None, *args, **kwargs) -> None: + self.request = request + self.user_cache: User | None = None + super().__init__(*args, **kwargs) + + def clean(self) -> dict[str, str]: + cleaned_data = super().clean() + email = cleaned_data.get("email") + password = cleaned_data.get("password") + + if email and password: + self.user_cache = authenticate( + self.request, email=normalize_email(email), password=password + ) + if self.user_cache is None: + raise ValidationError("The email or password is incorrect.") + + return cleaned_data + + def get_user(self) -> User | None: + """Return the authenticated user after successful form validation.""" + return self.user_cache diff --git a/src/accounts/migrations/0001_initial.py b/src/accounts/migrations/0001_initial.py new file mode 100644 index 0000000..cea6911 --- /dev/null +++ b/src/accounts/migrations/0001_initial.py @@ -0,0 +1,108 @@ +# Generated manually for the initial custom user model. + +import django.utils.timezone +from django.db import migrations, models + +import accounts.models + + +class Migration(migrations.Migration): + initial = True + + dependencies = [ + ("auth", "0012_alter_user_first_name_max_length"), + ] + + operations = [ + migrations.CreateModel( + name="User", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, primary_key=True, serialize=False, verbose_name="ID" + ), + ), + ("password", models.CharField(max_length=128, verbose_name="password")), + ( + "last_login", + models.DateTimeField(blank=True, null=True, verbose_name="last login"), + ), + ( + "is_superuser", + models.BooleanField( + default=False, + help_text=( + "Designates that this user has all permissions without explicitly " + "assigning them." + ), + verbose_name="superuser status", + ), + ), + ( + "first_name", + models.CharField(blank=True, max_length=150, verbose_name="first name"), + ), + ( + "last_name", + models.CharField(blank=True, max_length=150, verbose_name="last name"), + ), + ( + "is_staff", + models.BooleanField( + default=False, + help_text="Designates whether the user can log into this admin site.", + verbose_name="staff status", + ), + ), + ( + "is_active", + models.BooleanField( + default=True, + help_text=( + "Designates whether this user should be treated as active. " + "Unselect this instead of deleting accounts." + ), + verbose_name="active", + ), + ), + ( + "date_joined", + models.DateTimeField( + default=django.utils.timezone.now, verbose_name="date joined" + ), + ), + ( + "email", + models.EmailField(max_length=254, unique=True, verbose_name="email address"), + ), + ( + "groups", + models.ManyToManyField( + blank=True, + help_text=( + "The groups this user belongs to. A user will get all permissions " + "granted to each of their groups." + ), + related_name="user_set", + related_query_name="user", + to="auth.group", + verbose_name="groups", + ), + ), + ( + "user_permissions", + models.ManyToManyField( + blank=True, + help_text="Specific permissions for this user.", + related_name="user_set", + related_query_name="user", + to="auth.permission", + verbose_name="user permissions", + ), + ), + ], + options={"verbose_name": "user", "verbose_name_plural": "users"}, + managers=[("objects", accounts.models.UserManager())], + ), + ] diff --git a/src/accounts/migrations/__init__.py b/src/accounts/migrations/__init__.py new file mode 100644 index 0000000..fcc2542 --- /dev/null +++ b/src/accounts/migrations/__init__.py @@ -0,0 +1 @@ +"""Account schema migrations.""" diff --git a/src/accounts/models.py b/src/accounts/models.py new file mode 100644 index 0000000..fdd08ed --- /dev/null +++ b/src/accounts/models.py @@ -0,0 +1,74 @@ +"""Email-only account model for SkillStreak team members.""" + +from django.contrib.auth.base_user import BaseUserManager +from django.contrib.auth.models import AbstractUser +from django.core.exceptions import ValidationError +from django.db import models + +TEAM_EMAIL_DOMAIN = "csuchico.edu" + + +def normalize_email(email: str) -> str: + """Return the canonical email stored and used for authentication.""" + return email.strip().casefold() + + +def is_team_email(email: str) -> bool: + """Return whether an email belongs to the approved project-team domain.""" + local_part, separator, domain = normalize_email(email).rpartition("@") + return bool(local_part and separator and domain == TEAM_EMAIL_DOMAIN) + + +class UserManager(BaseUserManager): + """Create users whose email address is their only login identifier.""" + + use_in_migrations = True + + def _create_user(self, email: str, password: str | None, **extra_fields): + if not email: + raise ValueError("The email address must be set.") + if not is_team_email(email): + raise ValueError("Use a @csuchico.edu email address.") + + user = self.model(email=normalize_email(email), **extra_fields) + user.set_password(password) + user.save(using=self._db) + return user + + def create_user(self, email: str, password: str | None = None, **extra_fields): + extra_fields.setdefault("is_staff", False) + extra_fields.setdefault("is_superuser", False) + return self._create_user(email, password, **extra_fields) + + def create_superuser(self, email: str, password: str | None = None, **extra_fields): + extra_fields.setdefault("is_staff", True) + extra_fields.setdefault("is_superuser", True) + + if extra_fields.get("is_staff") is not True: + raise ValueError("Superuser must have is_staff=True.") + if extra_fields.get("is_superuser") is not True: + raise ValueError("Superuser must have is_superuser=True.") + + return self._create_user(email, password, **extra_fields) + + +class User(AbstractUser): + """A user authenticated by their normalized Chico State email address.""" + + username = None + email = models.EmailField("email address", unique=True) + + USERNAME_FIELD = "email" + REQUIRED_FIELDS: list[str] = [] + + objects = UserManager() + + def clean(self) -> None: + super().clean() + self.email = normalize_email(self.email) + if not is_team_email(self.email): + raise ValidationError({"email": "Use your @csuchico.edu email address."}) + + def save(self, *args, **kwargs) -> None: + self.email = normalize_email(self.email) + super().save(*args, **kwargs) diff --git a/src/accounts/templates/accounts/register.html b/src/accounts/templates/accounts/register.html new file mode 100644 index 0000000..5d3dcdb --- /dev/null +++ b/src/accounts/templates/accounts/register.html @@ -0,0 +1,37 @@ +{% load static %} + + + + + + Create an account | SkillStreak + + + +
+ +
+ + diff --git a/src/accounts/templates/accounts/sign_in.html b/src/accounts/templates/accounts/sign_in.html new file mode 100644 index 0000000..e809dc2 --- /dev/null +++ b/src/accounts/templates/accounts/sign_in.html @@ -0,0 +1,34 @@ +{% load static %} + + + + + + Sign in | SkillStreak + + + +
+ +
+ + diff --git a/src/accounts/urls.py b/src/accounts/urls.py new file mode 100644 index 0000000..37d02e4 --- /dev/null +++ b/src/accounts/urls.py @@ -0,0 +1,11 @@ +"""Routes for internal team account access.""" + +from django.urls import path + +from . import views + +urlpatterns = [ + path("register", views.register, name="account-register"), + path("sign-in", views.sign_in, name="account-sign-in"), + path("logout", views.sign_out, name="account-sign-out"), +] diff --git a/src/accounts/views.py b/src/accounts/views.py new file mode 100644 index 0000000..b4fef1f --- /dev/null +++ b/src/accounts/views.py @@ -0,0 +1,50 @@ +"""Browser views for team registration, sign-in, and sign-out.""" + +from django.contrib.auth import login, logout +from django.db import IntegrityError, transaction +from django.http import HttpRequest, HttpResponse +from django.shortcuts import redirect, render +from django.views.decorators.http import require_http_methods, require_POST + +from .forms import ACCOUNT_CREATION_ERROR, RegistrationForm, SignInForm + + +@require_http_methods(["GET", "POST"]) +def register(request: HttpRequest) -> HttpResponse: + """Create and authenticate an internal team account.""" + if request.user.is_authenticated: + return redirect("dashboard-preview") + + form = RegistrationForm(request.POST or None) + if request.method == "POST" and form.is_valid(): + try: + with transaction.atomic(): + user = form.save() + except IntegrityError: + form.add_error(None, ACCOUNT_CREATION_ERROR) + else: + login(request, user) + return redirect("dashboard-preview") + + return render(request, "accounts/register.html", {"form": form}) + + +@require_http_methods(["GET", "POST"]) +def sign_in(request: HttpRequest) -> HttpResponse: + """Authenticate a registered team member and create a server-side session.""" + if request.user.is_authenticated: + return redirect("dashboard-preview") + + form = SignInForm(request, request.POST or None) + if request.method == "POST" and form.is_valid(): + login(request, form.get_user()) + return redirect("dashboard-preview") + + return render(request, "accounts/sign_in.html", {"form": form}) + + +@require_POST +def sign_out(request: HttpRequest) -> HttpResponse: + """End the authenticated session and return to sign-in.""" + logout(request) + return redirect("account-sign-in") diff --git a/src/dashboard/__init__.py b/src/dashboard/__init__.py index 319c78c..c84a986 100644 --- a/src/dashboard/__init__.py +++ b/src/dashboard/__init__.py @@ -1 +1 @@ -"""Fixed-demo sign-in and dashboard application.""" +"""Authenticated static dashboard application.""" diff --git a/src/dashboard/static/dashboard/styles.css b/src/dashboard/static/dashboard/styles.css index be9b8d7..8f46202 100644 --- a/src/dashboard/static/dashboard/styles.css +++ b/src/dashboard/static/dashboard/styles.css @@ -64,10 +64,13 @@ h3 { margin-bottom: .18rem; font-size: 1.1rem; } .login-copy, .prototype-note { color: var(--muted); line-height: 1.6; } .prototype-note { font-size: .875rem; text-align: center; } +.prototype-note a { color: var(--moss-dark); font-weight: 750; } .form-error { border-left: .25rem solid #ae3c3c; background: #f9e3e1; margin: 1.5rem 0 0; padding: .75rem; color: #762a2a; font-size: .875rem; } .preview-form { display: grid; gap: .55rem; margin-top: 2rem; } .preview-form label { margin-top: .75rem; font-size: .875rem; font-weight: 700; } +.preview-form .errorlist { margin: 0; padding-left: 1rem; color: #762a2a; font-size: .8rem; } +.field-error { margin: 0; color: #762a2a; font-size: .8rem; } .preview-form input { width: 100%; diff --git a/src/dashboard/templates/dashboard/preview.html b/src/dashboard/templates/dashboard/preview.html index c6e9623..5e71001 100644 --- a/src/dashboard/templates/dashboard/preview.html +++ b/src/dashboard/templates/dashboard/preview.html @@ -9,7 +9,6 @@
- {% if authenticated %}
- {% else %} - - {% endif %}
diff --git a/src/dashboard/views.py b/src/dashboard/views.py index 8cb1261..613cce2 100644 --- a/src/dashboard/views.py +++ b/src/dashboard/views.py @@ -1,44 +1,11 @@ -"""Views for the fixed-demo dashboard MVP.""" +"""Views for the authenticated sample dashboard.""" -from hmac import compare_digest - -from django.conf import settings +from django.contrib.auth.decorators import login_required from django.http import HttpRequest, HttpResponse -from django.shortcuts import redirect, render -from django.views.decorators.http import require_POST - -DEMO_SESSION_KEY = "demo_signed_in" +from django.shortcuts import render +@login_required def preview(request: HttpRequest) -> HttpResponse: - """Render the sign-in form or the static dashboard for a verified session.""" - return render( - request, - "dashboard/preview.html", - {"authenticated": request.session.get(DEMO_SESSION_KEY, False)}, - ) - - -@require_POST -def sign_in(request: HttpRequest) -> HttpResponse: - """Allow only the runtime-configured demo identity to create a session.""" - submitted_email = request.POST.get("email", "") - submitted_password = request.POST.get("password", "") - credentials_configured = bool(settings.DEMO_LOGIN_EMAIL and settings.DEMO_LOGIN_PASSWORD) - credentials_match = compare_digest( - submitted_email, settings.DEMO_LOGIN_EMAIL - ) and compare_digest(submitted_password, settings.DEMO_LOGIN_PASSWORD) - - if credentials_configured and credentials_match: - request.session.cycle_key() - request.session[DEMO_SESSION_KEY] = True - return redirect("dashboard-preview") - - return render(request, "dashboard/preview.html", {"authenticated": False, "login_failed": True}) - - -@require_POST -def sign_out(request: HttpRequest) -> HttpResponse: - """Remove the demo session and return the visitor to sign-in.""" - request.session.flush() - return redirect("dashboard-preview") + """Render the static dashboard for the authenticated user.""" + return render(request, "dashboard/preview.html") diff --git a/src/skillstreak/settings/base.py b/src/skillstreak/settings/base.py index ea98d69..e656111 100644 --- a/src/skillstreak/settings/base.py +++ b/src/skillstreak/settings/base.py @@ -9,6 +9,7 @@ BASE_DIR = Path(__file__).resolve().parents[3] INSTALLED_APPS = [ + "accounts.apps.AccountsConfig", "dashboard.apps.DashboardConfig", "django.contrib.auth", "django.contrib.contenttypes", @@ -55,16 +56,20 @@ STATIC_URL = "static/" DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" -DEMO_LOGIN_EMAIL = os.getenv("DEMO_LOGIN_EMAIL", "") -DEMO_LOGIN_PASSWORD = os.getenv("DEMO_LOGIN_PASSWORD", "") - -# The MVP has no account table. A signed cookie safely stores the small, -# non-sensitive demo-session marker without introducing database persistence. -SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" +AUTH_USER_MODEL = "accounts.User" +LOGIN_URL = "account-sign-in" +SESSION_ENGINE = "django.contrib.sessions.backends.db" SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SAMESITE = "Lax" SESSION_COOKIE_AGE = 60 * 60 * 24 * 14 +AUTH_PASSWORD_VALIDATORS = [ + {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"}, + {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, + {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, + {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, +] + def database_configuration(database_url: str) -> dict[str, dict[str, str | int]]: """Convert a PostgreSQL URL into Django's database configuration.""" diff --git a/src/skillstreak/urls.py b/src/skillstreak/urls.py index 1f613a7..e1cd087 100644 --- a/src/skillstreak/urls.py +++ b/src/skillstreak/urls.py @@ -1,14 +1,13 @@ """Top-level URL configuration for project-level endpoints.""" -from django.urls import path +from django.urls import include, path -from dashboard.views import preview, sign_in, sign_out +from dashboard.views import preview from .health import health_check urlpatterns = [ + path("", include("accounts.urls")), path("", preview, name="dashboard-preview"), - path("sign-in", sign_in, name="dashboard-sign-in"), - path("logout", sign_out, name="dashboard-sign-out"), path("healthz", health_check, name="health-check"), ] diff --git a/tests/application/test_accounts.py b/tests/application/test_accounts.py new file mode 100644 index 0000000..99df92d --- /dev/null +++ b/tests/application/test_accounts.py @@ -0,0 +1,156 @@ +"""Tests for internal team account registration and authentication.""" + +from html import unescape + +import pytest +from django.conf import settings +from django.contrib.auth import get_user_model +from django.test import Client + + +@pytest.mark.django_db +def test_csuchico_team_member_can_register_and_reach_the_dashboard(client) -> None: + response = client.post( + "/register", + { + "email": "Learner@CSUCHICO.EDU", + "password1": "Secure skillstreak password 2026!", + "password2": "Secure skillstreak password 2026!", + }, + ) + + assert response.status_code == 302 + assert response.url == "/" + assert get_user_model().objects.filter(email="learner@csuchico.edu").exists() + assert "Your skills" in client.get("/").content.decode() + + +@pytest.mark.django_db +def test_registration_rejects_an_email_outside_the_team_domain(client) -> None: + response = client.post( + "/register", + { + "email": "learner@example.com", + "password1": "Secure skillstreak password 2026!", + "password2": "Secure skillstreak password 2026!", + }, + ) + + assert response.status_code == 200 + assert "@csuchico.edu" in response.content.decode() + assert get_user_model().objects.count() == 0 + + +@pytest.mark.django_db +def test_user_manager_rejects_an_account_outside_the_team_domain() -> None: + with pytest.raises(ValueError, match="@csuchico.edu"): + get_user_model().objects.create_user( + email="learner@example.com", password="Secure skillstreak password 2026!" + ) + + +@pytest.mark.django_db +def test_registration_rejects_a_case_variant_of_an_existing_email(client) -> None: + user_model = get_user_model() + user_model.objects.create_user( + email="learner@csuchico.edu", password="Secure skillstreak password 2026!" + ) + + response = client.post( + "/register", + { + "email": "LEARNER@csuchico.edu", + "password1": "Another secure password 2026!", + "password2": "Another secure password 2026!", + }, + ) + + assert response.status_code == 200 + assert "We couldn't create an account with those details." in unescape( + response.content.decode() + ) + assert user_model.objects.count() == 1 + + +@pytest.mark.django_db +def test_registration_rejects_mismatched_passwords(client) -> None: + response = client.post( + "/register", + { + "email": "learner@csuchico.edu", + "password1": "Secure skillstreak password 2026!", + "password2": "Different secure password 2026!", + }, + ) + + assert response.status_code == 200 + assert "The two password fields didn't match." in unescape(response.content.decode()) + + +@pytest.mark.django_db +def test_registration_rejects_a_request_without_a_csrf_token() -> None: + csrf_client = Client(enforce_csrf_checks=True) + + response = csrf_client.post( + "/register", + { + "email": "learner@csuchico.edu", + "password1": "Secure skillstreak password 2026!", + "password2": "Secure skillstreak password 2026!", + }, + ) + + assert response.status_code == 403 + + +@pytest.mark.django_db +def test_existing_team_member_can_sign_in_with_email_and_password(client) -> None: + get_user_model().objects.create_user( + email="learner@csuchico.edu", password="Secure skillstreak password 2026!" + ) + + response = client.post( + "/sign-in", + {"email": "LEARNER@CSUCHICO.EDU", "password": "Secure skillstreak password 2026!"}, + ) + + assert response.status_code == 302 + assert response.url == "/" + assert "Your skills" in client.get("/").content.decode() + + +@pytest.mark.django_db +def test_sign_in_rejects_invalid_credentials_without_disclosing_which_value_failed(client) -> None: + response = client.post( + "/sign-in", {"email": "learner@csuchico.edu", "password": "incorrect-password"} + ) + + assert response.status_code == 200 + assert "The email or password is incorrect." in response.content.decode() + + +@pytest.mark.django_db +def test_dashboard_redirects_anonymous_visitors_to_sign_in(client) -> None: + response = client.get("/") + + assert response.status_code == 302 + assert response.url == "/sign-in?next=/" + + +def test_authentication_uses_server_side_database_sessions() -> None: + assert settings.SESSION_ENGINE == "django.contrib.sessions.backends.db" + + +@pytest.mark.django_db +def test_sign_in_ignores_an_external_return_target(client) -> None: + get_user_model().objects.create_user( + email="learner@csuchico.edu", password="Secure skillstreak password 2026!" + ) + + response = client.post( + "/sign-in?next=https://example.com", + {"email": "learner@csuchico.edu", "password": "Secure skillstreak password 2026!"}, + ) + + assert response.status_code == 302 + assert response.url == "/" diff --git a/tests/application/test_dashboard.py b/tests/application/test_dashboard.py index 69858c0..dda73a4 100644 --- a/tests/application/test_dashboard.py +++ b/tests/application/test_dashboard.py @@ -1,70 +1,43 @@ -"""Tests for the fixed-demo dashboard sign-in.""" +"""Tests for the authenticated sample dashboard.""" -from django.test import Client, override_settings +import pytest +from django.contrib.auth import get_user_model +from django.test import Client -def test_home_page_shows_a_sign_in_prompt_when_session_is_not_authenticated(client) -> None: - response = client.get("/") - - assert response.status_code == 200 - assert "Welcome to SkillStreak" in response.content.decode() - assert "Sign in" in response.content.decode() - assert "Your skills" not in response.content.decode() - - -@override_settings( - DEMO_LOGIN_EMAIL="demo@skillstreak.test", DEMO_LOGIN_PASSWORD="test-demo-password" -) -def test_valid_demo_credentials_create_a_session_and_show_the_dashboard(client) -> None: - response = client.post( - "/sign-in", - {"email": "demo@skillstreak.test", "password": "test-demo-password"}, +@pytest.mark.django_db +def test_authenticated_member_sees_the_static_dashboard(client) -> None: + user = get_user_model().objects.create_user( + email="learner@csuchico.edu", password="Secure skillstreak password 2026!" ) + client.force_login(user) - assert response.status_code == 302 - assert response.url == "/" - - dashboard_response = client.get("/") + response = client.get("/") - assert "Your skills" in dashboard_response.content.decode() - assert "Welcome to SkillStreak" not in dashboard_response.content.decode() + content = response.content.decode() + assert response.status_code == 200 + assert "Your skills" in content + assert "learner@csuchico.edu" in content + assert "Demo session" not in content -@override_settings( - DEMO_LOGIN_EMAIL="demo@skillstreak.test", DEMO_LOGIN_PASSWORD="test-demo-password" -) -def test_invalid_demo_credentials_remain_blocked_with_a_generic_error(client) -> None: - response = client.post( - "/sign-in", - {"email": "demo@skillstreak.test", "password": "wrong-password"}, +@pytest.mark.django_db +def test_logout_clears_the_authenticated_session(client) -> None: + user = get_user_model().objects.create_user( + email="learner@csuchico.edu", password="Secure skillstreak password 2026!" ) + client.force_login(user) - content = response.content.decode() + response = client.post("/logout") - assert response.status_code == 200 - assert "The email or password is incorrect." in content - assert "Your skills" not in content - assert "demo@skillstreak.test" not in content + assert response.status_code == 302 + assert response.url == "/sign-in" + assert client.get("/").url == "/sign-in?next=/" -def test_sign_in_rejects_a_request_without_a_csrf_token() -> None: +def test_logout_rejects_a_request_without_a_csrf_token() -> None: csrf_client = Client(enforce_csrf_checks=True) - response = csrf_client.post("/sign-in", {"email": "any", "password": "value"}) + response = csrf_client.post("/logout") assert response.status_code == 403 - - -@override_settings( - DEMO_LOGIN_EMAIL="demo@skillstreak.test", DEMO_LOGIN_PASSWORD="test-demo-password" -) -def test_logout_clears_the_demo_session(client) -> None: - client.post( - "/sign-in", - {"email": "demo@skillstreak.test", "password": "test-demo-password"}, - ) - response = client.post("/logout") - - assert response.status_code == 302 - assert response.url == "/" - assert "Welcome to SkillStreak" in client.get("/").content.decode() From 48c4ab7f4c4f954c267977aa8ab32918e6b9eaf2 Mon Sep 17 00:00:00 2001 From: Tariq Kadir Date: Mon, 5 Oct 2026 16:32:23 -0700 Subject: [PATCH 2/3] Resolving Pull request checks / Python quality and infrastructure harness (pull_request) error --- .github/workflows/pr-checks.yml | 20 +++++++++++++++++++ .../test_repository_configuration.py | 12 +++++++++++ 2 files changed, 32 insertions(+) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 14c277f..de6f4c0 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -10,6 +10,22 @@ jobs: quality: name: Python quality and infrastructure harness runs-on: ubuntu-24.04 + services: + postgres: + image: postgres:17.7-bookworm + env: + POSTGRES_DB: skillstreak + POSTGRES_USER: skillstreak + POSTGRES_PASSWORD: ci-test-password + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U skillstreak -d skillstreak" + --health-interval 5s + --health-timeout 3s + --health-retries 12 + env: + DATABASE_URL: postgresql://skillstreak:ci-test-password@localhost:5432/skillstreak steps: - uses: actions/checkout@v5 - uses: actions/setup-python@v6 @@ -29,6 +45,10 @@ jobs: run: pytest tests/infrastructure - name: Django checks when application bootstrap exists if: ${{ hashFiles('manage.py') != '' }} + env: + DJANGO_SETTINGS_MODULE: skillstreak.settings.production + DJANGO_SECRET_KEY: ci-only-deployment-check-signing-value-not-used-outside-continuous-integration-2026 + ALLOWED_HOSTS: localhost run: python manage.py check --deploy - name: Django tests and coverage when application bootstrap exists if: ${{ hashFiles('manage.py') != '' }} diff --git a/tests/infrastructure/test_repository_configuration.py b/tests/infrastructure/test_repository_configuration.py index 6e6a560..b21aa0f 100644 --- a/tests/infrastructure/test_repository_configuration.py +++ b/tests/infrastructure/test_repository_configuration.py @@ -33,3 +33,15 @@ def test_compose_exposes_the_web_service_without_exposing_postgresql() -> None: assert ' - "${APP_PORT:-8000}:8000"' in configuration assert "internal: true" not in configuration assert ' - "5432:5432"' not in configuration + + +def test_pull_request_quality_job_has_a_postgresql_service_for_django() -> None: + workflow = (ROOT / ".github/workflows/pr-checks.yml").read_text() + + assert "name: Python quality and infrastructure harness" in workflow + assert "postgres:17.7-bookworm" in workflow + assert ( + "DATABASE_URL: postgresql://skillstreak:ci-test-password@localhost:5432/skillstreak" + in workflow + ) + assert "DJANGO_SETTINGS_MODULE: skillstreak.settings.production" in workflow From ffd8671242a44d4fd2b2246f7795487123c66b02 Mon Sep 17 00:00:00 2001 From: Tariq Kadir Date: Mon, 5 Oct 2026 16:42:08 -0700 Subject: [PATCH 3/3] Resolving: Scan images fore critical vulnerabilities --- AGENTS.md | 4 +++- Dockerfile | 11 ++++++++--- README.md | 9 +++++---- requirements.runtime.in | 5 +++++ requirements.runtime.txt | 16 ++++++++++++++++ .../test_repository_configuration.py | 11 +++++++++++ 6 files changed, 48 insertions(+), 8 deletions(-) create mode 100644 requirements.runtime.in create mode 100644 requirements.runtime.txt diff --git a/AGENTS.md b/AGENTS.md index fb536d2..4e00759 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,9 @@ user-owned skill/progress behavior does not exist yet. ## Repository map - `infrastructure_plan.md`: approved infrastructure plan. -- `requirements.in`, `requirements.txt`, `pyproject.toml`, `.python-version`: Python toolchain and lockfile. +- `requirements.in`, `requirements.txt`, `requirements.runtime.in`, + `requirements.runtime.txt`, `pyproject.toml`, `.python-version`: Python + toolchain and development/runtime lockfiles. - `compose.yml`, `Dockerfile`, `.dockerignore`, `.env.example`: Docker infrastructure and safe local configuration template. - `scripts/`: infrastructure validation, container-image, and PostgreSQL smoke tests. - `tests/infrastructure/`: configuration harness tests only. diff --git a/Dockerfile b/Dockerfile index 48a627b..7742162 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,8 +6,8 @@ ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \ PYTHONDONTWRITEBYTECODE=1 WORKDIR /build -COPY requirements.txt ./ -RUN python -m pip install --prefix=/install --requirement requirements.txt +COPY requirements.runtime.txt ./ +RUN python -m pip install --prefix=/install --requirement requirements.runtime.txt FROM python:3.14.7-slim-bookworm AS runtime @@ -17,7 +17,12 @@ ENV PYTHONDONTWRITEBYTECODE=1 \ PATH=/usr/local/bin:$PATH WORKDIR /app -RUN groupadd --gid 10001 app && useradd --uid 10001 --gid app --create-home app +RUN apt-get update \ + && apt-get upgrade --yes \ + && apt-get install --yes --no-install-recommends libpq5 \ + && rm -rf /var/lib/apt/lists/* \ + && groupadd --gid 10001 app \ + && useradd --uid 10001 --gid app --create-home app COPY --from=builder /install /usr/local COPY --chown=app:app . . RUN chown app:app /app diff --git a/README.md b/README.md index 2714149..f35e2de 100644 --- a/README.md +++ b/README.md @@ -33,11 +33,12 @@ yet. Never commit `.env`. Cloud Run receives real `DATABASE_URL` and `DJANGO_SECRET_KEY` values from Google Cloud-managed secrets. -3. Regenerate the dependency lockfile after editing `requirements.in`: +3. Regenerate the dependency lockfiles after editing `requirements.in` or the + production-only `requirements.runtime.in`: ```sh docker run --rm --volume "$PWD:/workspace" --workdir /workspace python:3.14.7-slim-bookworm \ - sh -c 'python -m pip install "pip-tools>=7.5,<8" && python -m piptools compile --strip-extras --output-file requirements.txt requirements.in' + sh -c 'python -m pip install "pip-tools>=7.5,<8" && python -m piptools compile --strip-extras --output-file requirements.txt requirements.in && python -m piptools compile --strip-extras --output-file requirements.runtime.txt requirements.runtime.in' ``` 4. Start the local Django and PostgreSQL services: @@ -92,8 +93,8 @@ migrations and browser workflows remain future product work. ## Quality and CI -`requirements.txt` is the committed pip-tools lockfile. Pull requests verify the -lockfile, Ruff formatting and linting, the infrastructure harness, Gitleaks, +`requirements.txt` and `requirements.runtime.txt` are committed pip-tools +lockfiles. Pull requests verify the development lockfile, Ruff formatting and linting, the infrastructure harness, Gitleaks, CodeQL, and an image build with a critical-vulnerability scan. Django system checks and the 80% branch-and-line coverage gate now run in pull requests. Browser tests remain future product work. diff --git a/requirements.runtime.in b/requirements.runtime.in new file mode 100644 index 0000000..492ebf2 --- /dev/null +++ b/requirements.runtime.in @@ -0,0 +1,5 @@ +# Production application dependencies only. Development and browser tooling stay +# in requirements.in so they are not copied into the runtime image. +Django==5.2.17 +gunicorn==26.2.0 +psycopg==3.3.6 diff --git a/requirements.runtime.txt b/requirements.runtime.txt new file mode 100644 index 0000000..04d2269 --- /dev/null +++ b/requirements.runtime.txt @@ -0,0 +1,16 @@ +# +# This file is autogenerated by pip-compile with Python 3.14 +# by the following command: +# +# pip-compile --no-index --output-file=requirements.runtime.txt --strip-extras requirements.runtime.in +# +asgiref==3.12.1 + # via django +django==5.2.17 + # via -r requirements.runtime.in +gunicorn==26.2.0 + # via -r requirements.runtime.in +psycopg==3.3.6 + # via -r requirements.runtime.in +sqlparse==0.6.0 + # via django diff --git a/tests/infrastructure/test_repository_configuration.py b/tests/infrastructure/test_repository_configuration.py index b21aa0f..f97939b 100644 --- a/tests/infrastructure/test_repository_configuration.py +++ b/tests/infrastructure/test_repository_configuration.py @@ -22,6 +22,8 @@ def test_required_infrastructure_files_are_present() -> None: "compose.yml", "requirements.in", "requirements.txt", + "requirements.runtime.in", + "requirements.runtime.txt", ) assert all((ROOT / path).is_file() for path in required_files) @@ -45,3 +47,12 @@ def test_pull_request_quality_job_has_a_postgresql_service_for_django() -> None: in workflow ) assert "DJANGO_SETTINGS_MODULE: skillstreak.settings.production" in workflow + + +def test_runtime_image_excludes_development_dependencies_and_refreshes_os_packages() -> None: + dockerfile = (ROOT / "Dockerfile").read_text() + + assert "COPY requirements.runtime.txt ./" in dockerfile + assert "COPY requirements.txt ./" not in dockerfile + assert "apt-get upgrade --yes" in dockerfile + assert "libpq5" in dockerfile