From 2284f497bd5b2534e0aa7565b985e5b0594445e4 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:17:59 +0530 Subject: [PATCH 01/23] feat: configure production database cache auth and logging --- ember/settings.py | 76 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 67 insertions(+), 9 deletions(-) diff --git a/ember/settings.py b/ember/settings.py index dbda5b8..b8efb4c 100644 --- a/ember/settings.py +++ b/ember/settings.py @@ -1,4 +1,4 @@ -"""Ember settings. All sensitive values come from environment variables (or a local .env).""" +"""Ember settings. Sensitive configuration is read from environment variables.""" import os import sys from pathlib import Path @@ -55,6 +55,7 @@ def env_list(name, default=""): "django.contrib.messages", "django.contrib.humanize", "django.contrib.staticfiles", + "axes", "accounts", "notes", ] @@ -68,6 +69,7 @@ def env_list(name, default=""): "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", + "axes.middleware.AxesMiddleware", ] ROOT_URLCONF = "ember.urls" @@ -89,12 +91,45 @@ def env_list(name, default=""): }, ] -DATABASES = { - "default": { - "ENGINE": "django.db.backends.sqlite3", - "NAME": os.environ.get("DJANGO_DB_PATH") or BASE_DIR / "db.sqlite3", +DATABASE_URL = os.environ.get("DATABASE_URL", "").strip() +if DATABASE_URL: + import dj_database_url + DATABASES = {"default": dj_database_url.parse( + DATABASE_URL, conn_max_age=int(os.environ.get("DB_CONN_MAX_AGE", "60")), + conn_health_checks=True, + )} +else: + DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": os.environ.get("DJANGO_DB_PATH") or BASE_DIR / "db.sqlite3", + } } -} + +# Configure a shared cache (recommended for multi-worker production) or safe local fallback. +CACHE_URL = os.environ.get("CACHE_URL", "").strip() +if CACHE_URL.startswith(("redis://", "rediss://")): + CACHES = {"default": { + "BACKEND": "django.core.cache.backends.redis.RedisCache", + "LOCATION": CACHE_URL, + "KEY_PREFIX": "ember", + }} +else: + CACHES = {"default": { + "BACKEND": "django.core.cache.backends.locmem.LocMemCache", + "LOCATION": "ember-local-cache", + "KEY_PREFIX": "ember", + }} + +AUTHENTICATION_BACKENDS = [ + "axes.backends.AxesStandaloneBackend", + "django.contrib.auth.backends.ModelBackend", +] +AXES_FAILURE_LIMIT = int(os.environ.get("AXES_FAILURE_LIMIT", "5")) +AXES_COOLOFF_TIME = int(os.environ.get("AXES_COOLOFF_HOURS", "1")) +AXES_RESET_ON_SUCCESS = True +AXES_LOCKOUT_PARAMETERS = ["username", "ip_address"] +AXES_ENABLE_ADMIN = True AUTH_PASSWORD_VALIDATORS = [ {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"}, @@ -106,9 +141,22 @@ def env_list(name, default=""): LOGIN_URL = "login" LOGIN_REDIRECT_URL = "notes:list" LOGOUT_REDIRECT_URL = "login" +PASSWORD_RESET_TIMEOUT = 3600 +DEFAULT_FROM_EMAIL = os.environ.get("DEFAULT_FROM_EMAIL", "Ember Notes ") +if DEBUG: + EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" +else: + EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" + EMAIL_HOST = os.environ.get("EMAIL_HOST", "") + EMAIL_PORT = int(os.environ.get("EMAIL_PORT", "587")) + EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER", "") + EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD", "") + EMAIL_USE_TLS = env_bool("EMAIL_USE_TLS", True) + EMAIL_USE_SSL = env_bool("EMAIL_USE_SSL", False) + EMAIL_TIMEOUT = int(os.environ.get("EMAIL_TIMEOUT", "10")) LANGUAGE_CODE = "en-us" -TIME_ZONE = os.environ.get("DJANGO_TIME_ZONE", "UTC") +TIME_ZONE = os.environ.get("DJANGO_TIME_ZONE", "Asia/Kolkata") USE_I18N = True USE_TZ = True @@ -136,9 +184,19 @@ def env_list(name, default=""): if env_bool("DJANGO_BEHIND_PROXY", False): SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") +LOG_LEVEL = os.environ.get("DJANGO_LOG_LEVEL", "INFO").upper() LOGGING = { "version": 1, "disable_existing_loggers": False, - "handlers": {"console": {"class": "logging.StreamHandler"}}, - "root": {"handlers": ["console"], "level": os.environ.get("DJANGO_LOG_LEVEL", "INFO")}, + "formatters": { + "standard": {"format": "%(asctime)s %(levelname)s %(name)s %(message)s"}, + }, + "handlers": { + "console": {"class": "logging.StreamHandler", "formatter": "standard"}, + }, + "root": {"handlers": ["console"], "level": LOG_LEVEL}, + "loggers": { + "django.security": {"handlers": ["console"], "level": "WARNING", "propagate": False}, + "accounts.security": {"handlers": ["console"], "level": "INFO", "propagate": False}, + }, } From 082b3a282886b7ca27df7b410b8cd1744458be60 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:03 +0530 Subject: [PATCH 02/23] build: add PostgreSQL and auth protection dependencies --- requirements.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/requirements.txt b/requirements.txt index 8f7c471..fcb7e8c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,7 @@ Django>=5.2,<5.3 whitenoise>=6.7 gunicorn>=22.0 +dj-database-url>=2.2,<3.0 +psycopg[binary]>=3.2,<4.0 +django-axes>=7.0,<9.0 +django-ratelimit>=4.1,<5.0 From 68d81eee30ac520a9bfce4435b84f82d31c5b746 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:06 +0530 Subject: [PATCH 03/23] feat: add account password recovery routes --- ember/urls.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/ember/urls.py b/ember/urls.py index 48d1609..17d12f5 100644 --- a/ember/urls.py +++ b/ember/urls.py @@ -1,9 +1,26 @@ from django.conf import settings from django.contrib import admin +from django.contrib.auth import views as auth_views from django.urls import include, path urlpatterns = [ path(settings.ADMIN_URL, admin.site.urls), path("accounts/", include("accounts.urls")), + path("accounts/password-reset/", auth_views.PasswordResetView.as_view( + template_name="registration/password_reset_form.html", + email_template_name="registration/password_reset_email.html", + subject_template_name="registration/password_reset_subject.txt", + success_url="/accounts/password-reset/done/", + ), name="password_reset"), + path("accounts/password-reset/done/", auth_views.PasswordResetDoneView.as_view( + template_name="registration/password_reset_done.html", + ), name="password_reset_done"), + path("accounts/reset///", auth_views.PasswordResetConfirmView.as_view( + template_name="registration/password_reset_confirm.html", + success_url="/accounts/reset/complete/", + ), name="password_reset_confirm"), + path("accounts/reset/complete/", auth_views.PasswordResetCompleteView.as_view( + template_name="registration/password_reset_complete.html", + ), name="password_reset_complete"), path("", include("notes.urls")), ] From 97dd543aad84b3ae7598bce407e16692657b8ec4 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:09 +0530 Subject: [PATCH 04/23] feat: rate limit signup and log security events --- accounts/views.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/accounts/views.py b/accounts/views.py index 956442b..bcadd60 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -1,14 +1,22 @@ +import logging + from django.contrib.auth import login from django.shortcuts import redirect, render +from django_ratelimit.decorators import ratelimit from .forms import SignupForm +security_logger = logging.getLogger("accounts.security") + +@ratelimit(key="ip", rate="5/h", method="POST", block=True) def signup(request): if request.user.is_authenticated: return redirect("notes:list") form = SignupForm(request.POST or None) if request.method == "POST" and form.is_valid(): - login(request, form.save()) + user = form.save() + login(request, user) + security_logger.info("account_signup_succeeded") return redirect("notes:list") return render(request, "registration/signup.html", {"form": form}) From 2f48c4d2e5abfe8121769d6e6408bf314728e4d2 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:12 +0530 Subject: [PATCH 05/23] docs: document production database cache and email settings --- .env.example | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/.env.example b/.env.example index 713e00a..32127f2 100644 --- a/.env.example +++ b/.env.example @@ -12,4 +12,20 @@ DJANGO_BEHIND_PROXY=False DJANGO_HSTS_SECONDS=31536000 DJANGO_ADMIN_URL=admin/ DJANGO_DB_PATH= +# Optional PostgreSQL URL, e.g. postgres://user:password@host:5432/ember +DATABASE_URL= +DB_CONN_MAX_AGE=60 +# Optional Redis URL for a shared cache/rate-limit cache in multi-worker deployments +CACHE_URL= +AXES_FAILURE_LIMIT=5 +AXES_COOLOFF_HOURS=1 DJANGO_LOG_LEVEL=INFO +# Production SMTP for password-reset email +DEFAULT_FROM_EMAIL=Ember Notes +EMAIL_HOST= +EMAIL_PORT=587 +EMAIL_HOST_USER= +EMAIL_HOST_PASSWORD= +EMAIL_USE_TLS=True +EMAIL_USE_SSL=False +EMAIL_TIMEOUT=10 From ace8de69e169f59785e2f8ac94b4d0928a44c6f4 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:38 +0530 Subject: [PATCH 06/23] feat: add password_reset_form.html --- templates/registration/password_reset_form.html | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 templates/registration/password_reset_form.html diff --git a/templates/registration/password_reset_form.html b/templates/registration/password_reset_form.html new file mode 100644 index 0000000..a51f3fc --- /dev/null +++ b/templates/registration/password_reset_form.html @@ -0,0 +1,11 @@ +{% extends "auth.html" %} +{% block title %}Reset password – Ember{% endblock %} +{% block auth %} +

Reset your password

+

Enter the email address on your account. If it matches an eligible account, we'll send a reset link.

+
{% csrf_token %} + {% for field in form %}{% include "_field.html" %}{% endfor %} + +
+

Back to sign in

+{% endblock %} From 23dbbc1cffa51ac94ee110dbdb95af95c6c6d9f3 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:40 +0530 Subject: [PATCH 07/23] feat: add password_reset_done.html --- templates/registration/password_reset_done.html | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 templates/registration/password_reset_done.html diff --git a/templates/registration/password_reset_done.html b/templates/registration/password_reset_done.html new file mode 100644 index 0000000..930c726 --- /dev/null +++ b/templates/registration/password_reset_done.html @@ -0,0 +1,7 @@ +{% extends "auth.html" %} +{% block title %}Check your email – Ember{% endblock %} +{% block auth %} +

Check your email

+

If an eligible account matches that address, a password-reset link has been sent. Check your inbox and spam folder.

+

Back to sign in

+{% endblock %} From a24ce86449a3048b421cd9817ca5c46103f03a5c Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:45 +0530 Subject: [PATCH 08/23] feat: add password_reset_confirm.html --- templates/registration/password_reset_confirm.html | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 templates/registration/password_reset_confirm.html diff --git a/templates/registration/password_reset_confirm.html b/templates/registration/password_reset_confirm.html new file mode 100644 index 0000000..df0a92c --- /dev/null +++ b/templates/registration/password_reset_confirm.html @@ -0,0 +1,14 @@ +{% extends "auth.html" %} +{% block title %}Choose a new password – Ember{% endblock %} +{% block auth %} +

Choose a new password

+{% if validlink %} +
{% csrf_token %} + {% for field in form %}{% include "_field.html" %}{% endfor %} + +
+{% else %} +

This reset link is invalid or has expired. Request a fresh link to continue.

+

Request another link

+{% endif %} +{% endblock %} From c778ed030be2a00e17dca46d519367e76a354899 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:47 +0530 Subject: [PATCH 09/23] feat: add password_reset_complete.html --- templates/registration/password_reset_complete.html | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 templates/registration/password_reset_complete.html diff --git a/templates/registration/password_reset_complete.html b/templates/registration/password_reset_complete.html new file mode 100644 index 0000000..60815d7 --- /dev/null +++ b/templates/registration/password_reset_complete.html @@ -0,0 +1,7 @@ +{% extends "auth.html" %} +{% block title %}Password updated – Ember{% endblock %} +{% block auth %} +

Password updated

+

Your password has been changed. You can now sign in with the new password.

+

Sign in to Ember

+{% endblock %} From ebf3421ecf703be7b85f17c74b5a68b6916f046d Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:50 +0530 Subject: [PATCH 10/23] feat: add password_reset_email.html --- templates/registration/password_reset_email.html | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 templates/registration/password_reset_email.html diff --git a/templates/registration/password_reset_email.html b/templates/registration/password_reset_email.html new file mode 100644 index 0000000..3439812 --- /dev/null +++ b/templates/registration/password_reset_email.html @@ -0,0 +1,6 @@ +Someone requested a password reset for your Ember Notes account. + +Use the link below to choose a new password: +{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} + +If you did not request this, you can safely ignore this email. Your password will not change unless the link is used. From ddad5dbfe6950275f9f650a6acbdee82dcaa0e67 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:52 +0530 Subject: [PATCH 11/23] feat: add password_reset_subject.txt --- templates/registration/password_reset_subject.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 templates/registration/password_reset_subject.txt diff --git a/templates/registration/password_reset_subject.txt b/templates/registration/password_reset_subject.txt new file mode 100644 index 0000000..4f71b02 --- /dev/null +++ b/templates/registration/password_reset_subject.txt @@ -0,0 +1 @@ +Reset your Ember Notes password \ No newline at end of file From 6e24a2ab8fa38f8b9b322f18f29ba18fceafc814 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:54 +0530 Subject: [PATCH 12/23] feat: add backup_db.py --- notes/management/commands/backup_db.py | 50 ++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 notes/management/commands/backup_db.py diff --git a/notes/management/commands/backup_db.py b/notes/management/commands/backup_db.py new file mode 100644 index 0000000..ec078ce --- /dev/null +++ b/notes/management/commands/backup_db.py @@ -0,0 +1,50 @@ +import os +import sqlite3 +from datetime import datetime +from pathlib import Path + +from django.conf import settings +from django.core.management.base import BaseCommand, CommandError + + +class Command(BaseCommand): + help = "Create a consistent SQLite database snapshot. PostgreSQL backups should use pg_dump or provider snapshots." + + def add_arguments(self, parser): + parser.add_argument("--output", help="Destination .sqlite3 file (default: backups/ember-.sqlite3)") + + def handle(self, *args, **options): + database = settings.DATABASES["default"] + if database["ENGINE"] != "django.db.backends.sqlite3": + raise CommandError( + "This command supports SQLite only. For PostgreSQL, use pg_dump or your managed provider's backup/snapshot service." + ) + + source = Path(database["NAME"]).resolve() + if not source.is_file(): + raise CommandError(f"Database file does not exist: {source}") + + timestamp = datetime.now().strftime("%Y%m%d-%H%M%S") + destination = Path(options["output"] or (Path(settings.BASE_DIR) / "backups" / f"ember-{timestamp}.sqlite3")).expanduser().resolve() + if source == destination: + raise CommandError("Backup output must not be the live database file.") + if destination.exists(): + raise CommandError(f"Refusing to overwrite an existing backup: {destination}") + + destination.parent.mkdir(parents=True, exist_ok=True) + try: + with sqlite3.connect(f"file:{source}?mode=ro", uri=True) as source_db: + with sqlite3.connect(destination) as backup_db: + source_db.backup(backup_db) + check = backup_db.execute("PRAGMA integrity_check").fetchone()[0] + if check != "ok": + raise CommandError(f"Backup integrity check failed: {check}") + try: + os.chmod(destination, 0o600) + except OSError: + pass + except sqlite3.Error as exc: + destination.unlink(missing_ok=True) + raise CommandError(f"Could not create SQLite backup: {exc}") from exc + + self.stdout.write(self.style.SUCCESS(f"SQLite backup created and integrity-checked: {destination}")) From 04047efc74d9c474f35ac2ae70f7deb95e8c2bc5 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:18:58 +0530 Subject: [PATCH 13/23] feat: add restore_db.py --- notes/management/commands/restore_db.py | 69 +++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 notes/management/commands/restore_db.py diff --git a/notes/management/commands/restore_db.py b/notes/management/commands/restore_db.py new file mode 100644 index 0000000..0e48d8c --- /dev/null +++ b/notes/management/commands/restore_db.py @@ -0,0 +1,69 @@ +import os +import shutil +import sqlite3 +from datetime import datetime +from pathlib import Path + +from django.conf import settings +from django.core.management.base import BaseCommand, CommandError +from django.db import connections + + +class Command(BaseCommand): + help = "Restore a SQLite database backup. This replaces the live database; stop the application first." + + def add_arguments(self, parser): + parser.add_argument("backup", help="Path to a verified SQLite backup file") + parser.add_argument("--confirm", action="store_true", help="Required to replace the live database") + + def handle(self, *args, **options): + if not options["confirm"]: + raise CommandError("Restore is destructive. Stop the app and rerun with --confirm after verifying the backup.") + database = settings.DATABASES["default"] + if database["ENGINE"] != "django.db.backends.sqlite3": + raise CommandError( + "This command supports SQLite only. Restore PostgreSQL with your provider's documented restore process or pg_restore." + ) + + source = Path(options["backup"]).expanduser().resolve() + target = Path(database["NAME"]).resolve() + if not source.is_file(): + raise CommandError(f"Backup file not found: {source}") + if source == target: + raise CommandError("The backup path must differ from the live database path.") + try: + with sqlite3.connect(f"file:{source}?mode=ro", uri=True) as backup_db: + result = backup_db.execute("PRAGMA integrity_check").fetchone()[0] + if result != "ok": + raise CommandError(f"Backup integrity check failed: {result}") + except sqlite3.Error as exc: + raise CommandError(f"Could not read backup file: {exc}") from exc + + target.parent.mkdir(parents=True, exist_ok=True) + timestamp = datetime.now().strftime("%Y%m%d-%H%M%S") + safety_copy = target.with_name(f"{target.name}.pre-restore-{timestamp}") + connections.close_all() + try: + if target.exists(): + shutil.copy2(target, safety_copy) + try: + os.chmod(safety_copy, 0o600) + except OSError: + pass + temporary = target.with_name(f".{target.name}.restore-tmp") + shutil.copy2(source, temporary) + with sqlite3.connect(temporary) as restored_db: + result = restored_db.execute("PRAGMA integrity_check").fetchone()[0] + if result != "ok": + temporary.unlink(missing_ok=True) + raise CommandError(f"Restored copy integrity check failed: {result}") + os.replace(temporary, target) + for suffix in ("-wal", "-shm"): + Path(str(target) + suffix).unlink(missing_ok=True) + except (OSError, sqlite3.Error) as exc: + raise CommandError(f"Restore failed: {exc}") from exc + + message = f"SQLite database restored from {source}." + if safety_copy.exists(): + message += f" Previous database preserved at {safety_copy}." + self.stdout.write(self.style.SUCCESS(message)) From 6101ab9baaa3189510be6b8351f717f9498521fe Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:19:18 +0530 Subject: [PATCH 14/23] feat: link password recovery from sign-in --- templates/registration/login.html | 1 + 1 file changed, 1 insertion(+) diff --git a/templates/registration/login.html b/templates/registration/login.html index e39f6db..70f0fc3 100644 --- a/templates/registration/login.html +++ b/templates/registration/login.html @@ -8,5 +8,6 @@

Sign in

+

Forgot your password?

New to Ember? Create an account

{% endblock %} From f9d3463defd6ceb2fdb7ef5b85b74ad498855f5c Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:19:37 +0530 Subject: [PATCH 15/23] build: include Redis client for shared cache support --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index fcb7e8c..e486ece 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,4 @@ dj-database-url>=2.2,<3.0 psycopg[binary]>=3.2,<4.0 django-axes>=7.0,<9.0 django-ratelimit>=4.1,<5.0 +redis>=5.0,<7.0 From 7cd5af53569e534a6513ee57525a09fb51552fd3 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:19:42 +0530 Subject: [PATCH 16/23] security: require TLS for production PostgreSQL connections --- ember/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ember/settings.py b/ember/settings.py index b8efb4c..5d8cf72 100644 --- a/ember/settings.py +++ b/ember/settings.py @@ -96,7 +96,7 @@ def env_list(name, default=""): import dj_database_url DATABASES = {"default": dj_database_url.parse( DATABASE_URL, conn_max_age=int(os.environ.get("DB_CONN_MAX_AGE", "60")), - conn_health_checks=True, + conn_health_checks=True, ssl_require=PROD, )} else: DATABASES = { From f6b8cac19664031064119020bd8b43324b1b5bc4 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:19:49 +0530 Subject: [PATCH 17/23] feat: log privacy-conscious authentication security events --- accounts/security.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 accounts/security.py diff --git a/accounts/security.py b/accounts/security.py new file mode 100644 index 0000000..af0734c --- /dev/null +++ b/accounts/security.py @@ -0,0 +1,22 @@ +"""Privacy-conscious security event logging; never log note contents or credentials.""" +import logging + +from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed +from django.dispatch import receiver + +logger = logging.getLogger("accounts.security") + + +@receiver(user_logged_in, dispatch_uid="accounts.log_login_success") +def log_login_success(sender, request, user, **kwargs): + logger.info("authentication_succeeded") + + +@receiver(user_login_failed, dispatch_uid="accounts.log_login_failure") +def log_login_failure(sender, credentials, request, **kwargs): + logger.warning("authentication_failed") + + +@receiver(user_logged_out, dispatch_uid="accounts.log_logout") +def log_logout(sender, request, user, **kwargs): + logger.info("authentication_ended") From 4db408012f64eec1a6e3b0108b8ebab72ca29233 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:19:52 +0530 Subject: [PATCH 18/23] feat: register account security signal handlers --- accounts/apps.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/accounts/apps.py b/accounts/apps.py index 0cb51e6..c3b41e0 100644 --- a/accounts/apps.py +++ b/accounts/apps.py @@ -4,3 +4,6 @@ class AccountsConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "accounts" + + def ready(self): + from . import security # noqa: F401 From 7619e2c2fe2982cd419f46bdfea2a9f72d6e52b1 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:19:59 +0530 Subject: [PATCH 19/23] test: cover password recovery and email privacy --- accounts/tests.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 accounts/tests.py diff --git a/accounts/tests.py b/accounts/tests.py new file mode 100644 index 0000000..26ad38f --- /dev/null +++ b/accounts/tests.py @@ -0,0 +1,42 @@ +from django.contrib.auth import get_user_model +from django.core import mail +from django.test import TestCase, override_settings +from django.urls import reverse + + +User = get_user_model() + + +@override_settings( + EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend", + DEFAULT_FROM_EMAIL="Ember Notes ", +) +class PasswordRecoveryTests(TestCase): + def setUp(self): + self.user = User.objects.create_user( + username="recovery-user", + email="recovery@example.com", + password="Strong-test-password-482!", + ) + + def test_known_email_receives_reset_link(self): + response = self.client.post( + reverse("password_reset"), + {"email": self.user.email}, + ) + self.assertRedirects(response, reverse("password_reset_done")) + self.assertEqual(len(mail.outbox), 1) + self.assertIn("/accounts/reset/", mail.outbox[0].body) + + def test_unknown_email_uses_same_success_page_without_sending_mail(self): + response = self.client.post( + reverse("password_reset"), + {"email": "unknown@example.com"}, + ) + self.assertRedirects(response, reverse("password_reset_done")) + self.assertEqual(len(mail.outbox), 0) + + def test_reset_form_and_completion_pages_render(self): + self.assertEqual(self.client.get(reverse("password_reset")).status_code, 200) + self.assertEqual(self.client.get(reverse("password_reset_done")).status_code, 200) + self.assertEqual(self.client.get(reverse("password_reset_complete")).status_code, 200) From 6d0e15eea211468c53382ca5c4467316f6f61d73 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:20:05 +0530 Subject: [PATCH 20/23] fix: ensure account security signal handlers are loaded --- ember/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ember/settings.py b/ember/settings.py index 5d8cf72..2561e1b 100644 --- a/ember/settings.py +++ b/ember/settings.py @@ -56,7 +56,7 @@ def env_list(name, default=""): "django.contrib.humanize", "django.contrib.staticfiles", "axes", - "accounts", + "accounts.apps.AccountsConfig", "notes", ] From 804706dabb5c2c94b950d10b92f909c2ceee7c46 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:20:30 +0530 Subject: [PATCH 21/23] docs: document production database backups recovery and auth controls --- README.md | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index fcb1670..58a8017 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,15 @@ A self-hostable, Django-powered notes app with a focused dark interface, autosave, tags, pinning, archive, trash, search, sorting, and per-user note isolation. -> **Project status:** Phase 1 stabilization and documentation. Review the deployment and persistence checklist before hosting real user data. +> **Project status:** Phase 2 production-readiness work. Configure a persistent database, shared cache, SMTP and verified backups before hosting real user data. ## Features -- Account signup, login, and logout +- Account signup, login, logout, password-reset emails, and reset-token flow +- Brute-force protection for login attempts and IP-based signup throttling +- Privacy-conscious authentication event logs that omit credentials and note content +- Configurable PostgreSQL connections and optional Redis-backed shared cache +- SQLite backup/restore commands with integrity checks and a pre-restore safety copy - Create and edit notes with debounced autosave and manual save - Save-state feedback, retry on failure, and flush pending edits before destructive actions - Tags, pinned notes, archive, recoverable trash, and permanent deletion @@ -18,7 +22,7 @@ A self-hostable, Django-powered notes app with a focused dark interface, autosav - Python 3.10+ (use a supported Python version compatible with your deployment) - Django 5.2 -- SQLite by default +- SQLite for local development; PostgreSQL supported through `DATABASE_URL` - WhiteNoise for static files - Gunicorn as the WSGI server @@ -96,7 +100,15 @@ The deploy check is expected to report configuration warnings until the hosting | `DJANGO_BEHIND_PROXY` | Enables forwarded-protocol handling only when the trusted proxy is configured correctly. | | `DJANGO_HSTS_SECONDS` | HSTS duration in production; only enable long durations after HTTPS is confirmed. | | `DJANGO_ADMIN_URL` | Admin URL path. This is not a substitute for authentication or rate limiting. | -| `DJANGO_DB_PATH` | Optional path to the SQLite database file. | +| `DJANGO_DB_PATH` | Optional path to the SQLite database file when `DATABASE_URL` is unset. | +| `DATABASE_URL` | Optional PostgreSQL connection URL; TLS is required by the app in production. | +| `DB_CONN_MAX_AGE` | Persistent database connection lifetime in seconds (default 60). | +| `CACHE_URL` | Optional Redis URL for a shared cache; configure this for reliable IP rate limits across multiple workers. | +| `AXES_FAILURE_LIMIT` | Failed login attempts before lockout (default 5). | +| `AXES_COOLOFF_HOURS` | Login lockout duration in hours (default 1). | +| `DEFAULT_FROM_EMAIL` | Sender shown on password-reset emails. | +| `EMAIL_HOST`, `EMAIL_PORT`, `EMAIL_HOST_USER`, `EMAIL_HOST_PASSWORD` | Production SMTP connection settings; keep credentials in the hosting secret manager. | +| `EMAIL_USE_TLS`, `EMAIL_USE_SSL`, `EMAIL_TIMEOUT` | SMTP transport and timeout settings. | | `DJANGO_LOG_LEVEL` | Python root logger level. Do not log note contents or credentials. | The application currently configures SQLite in `ember/settings.py`. `DJANGO_DB_PATH` changes the file location; it does **not** make storage persistent on its own. On hosting platforms with ephemeral filesystems, SQLite data can disappear during redeploys/restarts. Before production use, confirm persistent storage or migrate to a managed database such as PostgreSQL, and test a restore from backup. @@ -112,11 +124,52 @@ Do not treat a successful local run as proof of production readiness. - [ ] Configure scheduled, access-controlled backups and perform a restore drill. - [ ] Apply migrations during deployment and collect static files with `python manage.py collectstatic --noinput`. - [ ] Run `python manage.py check --deploy` against the actual production environment and resolve applicable warnings. -- [ ] Add rate limiting for authentication endpoints and a password reset/account recovery flow before public launch. +- [ ] Confirm login lockout and signup rate limits with your actual shared-cache/worker topology. +- [ ] Configure production SMTP and test password recovery end to end. - [ ] Confirm logs do not contain secrets, passwords, session tokens, or private note content. - [ ] Schedule `python manage.py purge_trash --days 30` only after documenting its permanent-deletion policy and ensuring backups exist. - [ ] Verify registration, login/logout, CRUD, autosave, trash/restore, search, mobile layout, and error states in a real browser. +## Database backups and restore + +### SQLite (local/single-instance only) + +Create an integrity-checked snapshot: + +```bash +python manage.py backup_db +python manage.py backup_db --output /secure/backups/ember.sqlite3 +``` + +The default destination is `backups/`, which is excluded from Git. Backups contain private note content and account data: restrict access, encrypt them at rest, and copy them to storage independent of the app host. Never commit or publicly serve backups. + +To restore, **stop every app worker first** and verify the chosen backup. The command requires an explicit destructive confirmation and preserves the previous live database as a safety copy when one exists: + +```bash +python manage.py restore_db /secure/backups/ember.sqlite3 --confirm +``` + +The restore command supports SQLite only. Run a restore drill on a non-production copy before relying on it; a successful backup is not proof that recovery works. + +### PostgreSQL (recommended for production) + +Use managed database snapshots/PITR when your provider supports them. As a portable manual alternative, use the provider's recommended `pg_dump` and `pg_restore` workflow from a secured host: + +```bash +pg_dump --format=custom --file=ember-backup.dump "$DATABASE_URL" +# Destructive restore: stop app workers and confirm the target database first. +pg_restore --clean --if-exists --no-owner --dbname="$DATABASE_URL" ember-backup.dump +``` + +Keep dumps encrypted and access-controlled. A restore can replace database objects/data; never test it against the only production database. Schedule backups, monitor their success, and periodically restore into an isolated database. + +## Authentication protection and email + +- Login failures are tracked by Django Axes; the default lockout is five failures for the username/IP combination for one hour. +- Signup POSTs are limited to five per IP per hour. Configure `CACHE_URL` to Redis for shared rate-limit state across multiple workers; the local-memory fallback is not shared between processes. +- Password reset uses Django's token-based built-in flow. Unknown email addresses receive the same confirmation page to reduce account enumeration. Production must configure working SMTP credentials; development prints reset emails to the console. +- Authentication logs record event types only; they intentionally omit usernames, passwords, session tokens, and note contents. Protect and rotate host logs as part of operations. + ## Data and privacy notes Notes are private to the authenticated owner at the application-query level. This is not end-to-end encryption: operators with database access may be able to read stored note content. Do not promise encrypted notes unless encryption and key management are implemented and independently reviewed. From fea3194357348b79e830b5b2aaf6b0de43d64533 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:20:38 +0530 Subject: [PATCH 22/23] security: keep database backups out of version control --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 8127a6d..19c7106 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,7 @@ staticfiles/ # Ignore setup script setup_history.py + +# Database backups and pre-restore safety copies contain private user data +/backups/ +*.pre-restore-* From ecb9b59ed2901462053c378ea8571a24d63d5324 Mon Sep 17 00:00:00 2001 From: Ashutosh Palhare Date: Tue, 27 Oct 2026 22:21:37 +0530 Subject: [PATCH 23/23] fix: specify authentication backend for signup login --- accounts/views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/accounts/views.py b/accounts/views.py index bcadd60..d8fc1c3 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -16,7 +16,7 @@ def signup(request): form = SignupForm(request.POST or None) if request.method == "POST" and form.is_valid(): user = form.save() - login(request, user) + login(request, user, backend="django.contrib.auth.backends.ModelBackend") security_logger.info("account_signup_succeeded") return redirect("notes:list") return render(request, "registration/signup.html", {"form": form})