BS-001 Initialize BortStack foundation and project workflow

This commit is contained in:
rob
2026-11-10 14:02:50 +00:00
parent 1ec90a082f
commit 52265961cb
119 changed files with 10298 additions and 64 deletions
+10
View File
@@ -0,0 +1,10 @@
[run]
source = .
omit =
tests/*
migrations/*
import.py
[report]
show_missing = true
skip_covered = true
+10
View File
@@ -0,0 +1,10 @@
.env
.env.*
.venv
__pycache__
instance
migrations/__pycache__
tests
*.pyc
*.sqlite
*.db
+3
View File
@@ -0,0 +1,3 @@
FLASK_APP=api.py
FLASK_ENV=development
FLASK_DEBUG=1
+15
View File
@@ -0,0 +1,15 @@
FROM python:3.12-slim
WORKDIR /app
COPY config/requirements.txt ./config/requirements.txt
RUN pip install --no-cache-dir -r ./config/requirements.txt \
&& groupadd --gid 10001 app \
&& useradd --uid 10001 --gid app --create-home --shell /usr/sbin/nologin app
COPY . /app
ENV HOME=/home/app \
PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
USER app:app
EXPOSE 5000
CMD ["gunicorn", "--config", "gunicorn.conf.py", "api:app"]
+5
View File
@@ -0,0 +1,5 @@
from flask import Flask
from settings import app
from models import AccountToken, User # noqa: F401
from routes.routes import *
+33
View File
@@ -0,0 +1,33 @@
"""Auth."""
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
from models import User
from errors import error_response
basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth()
@basic_auth.verify_password
def verify_password(email, password):
"""Verify password."""
user = User.query.filter_by(email=email).first()
if user and user.check_password(password):
return user
@basic_auth.error_handler
def basic_auth_error(status):
"""Basic auth error."""
return error_response(status)
@token_auth.verify_token
def verify_token(token):
"""Verify token."""
return User.check_token(token) if token else None
@token_auth.error_handler
def token_auth_error(status):
"""Token auth error."""
return error_response(status)
+4
View File
@@ -0,0 +1,4 @@
-r requirements.txt
pytest==9.1.1
pytest-cov==7.1.0
+10
View File
@@ -0,0 +1,10 @@
Flask==3.1.3
Flask-Migrate==4.1.0
Flask-SQLAlchemy==3.1.1
PyMySQL==1.2.0
flask-cors==6.0.5
python-dotenv==1.2.3
Flask-HTTPAuth==4.8.1
Flask-Limiter==4.1.1
gunicorn==26.2.0
resend==2.42.0
+85
View File
@@ -0,0 +1,85 @@
from html import escape
import resend
from flask import current_app
class EmailDeliveryError(RuntimeError):
pass
def send_email(*, to, subject, html, text, reply_to=None):
if not current_app.config["EMAIL_DELIVERY_ENABLED"]:
return {"id": "email-delivery-disabled"}
resend.api_key = current_app.config["RESEND_API_KEY"]
payload = {
"from": current_app.config["EMAIL_FROM"],
"to": [to],
"subject": subject,
"html": html,
"text": text,
}
if reply_to:
payload["reply_to"] = reply_to
try:
return resend.Emails.send(payload)
except Exception as error:
raise EmailDeliveryError("Email delivery failed") from error
def action_email(*, to, subject, heading, body, action_label, action_url):
safe_heading = escape(heading)
safe_body = escape(body)
safe_label = escape(action_label)
safe_url = escape(action_url, quote=True)
html = (
'<div style="font-family:Arial,sans-serif;max-width:600px;margin:auto">'
f"<h1>{safe_heading}</h1><p>{safe_body}</p>"
f'<p><a href="{safe_url}">{safe_label}</a></p>'
f"<p>If the button does not work, copy this link:<br>{safe_url}</p></div>"
)
text = f"{heading}\n\n{body}\n\n{action_label}: {action_url}"
return send_email(to=to, subject=subject, html=html, text=text)
def send_verification_email(user, raw_token):
url = f"{current_app.config['APP_URL']}/verify-email?token={raw_token}"
return action_email(
to=user.email,
subject="Verify your email",
heading="Verify your email",
body="Confirm your email address to activate your account.",
action_label="Verify email",
action_url=url,
)
def send_password_reset_email(user, raw_token):
url = f"{current_app.config['APP_URL']}/reset-password?token={raw_token}"
return action_email(
to=user.email,
subject="Reset your password",
heading="Reset your password",
body="Use this secure link to choose a new password. If you did not request this, ignore this email.",
action_label="Reset password",
action_url=url,
)
def send_contact_email(*, name, email, subject, message):
safe_name = escape(name)
safe_email = escape(email)
safe_subject = escape(subject)
safe_message = escape(message).replace("\n", "<br>")
return send_email(
to=current_app.config["CONTACT_EMAIL"],
subject=f"Website contact: {subject}",
html=(
"<h1>Contact form</h1>"
f"<p><strong>From:</strong> {safe_name} ({safe_email})</p>"
f"<p><strong>Subject:</strong> {safe_subject}</p>"
f"<p>{safe_message}</p>"
),
text=f"From: {name} <{email}>\nSubject: {subject}\n\n{message}",
reply_to=email,
)
+18
View File
@@ -0,0 +1,18 @@
"""Response errors."""
from flask import jsonify
from werkzeug.http import HTTP_STATUS_CODES
def error_response(status_code, message=None):
"""Error response."""
payload = {"error": HTTP_STATUS_CODES.get(status_code, "Unknown error")}
if message:
payload["message"] = message
response = jsonify(payload)
response.status_code = status_code
return response
def bad_request(message):
"""Bad request."""
return error_response(400, message)
+12
View File
@@ -0,0 +1,12 @@
"""Environment-tunable Gunicorn defaults for the generic container."""
import os
bind = "0.0.0.0:5000"
workers = int(os.environ.get("GUNICORN_WORKERS", "2"))
timeout = int(os.environ.get("GUNICORN_TIMEOUT", "30"))
graceful_timeout = int(os.environ.get("GUNICORN_GRACEFUL_TIMEOUT", "30"))
keepalive = int(os.environ.get("GUNICORN_KEEPALIVE", "5"))
errorlog = "-"
accesslog = None # Query strings may contain verification/reset tokens.
capture_output = False
+27
View File
@@ -0,0 +1,27 @@
"""Minimal structured application logging without request payloads."""
import json
import logging
from datetime import datetime, timezone
class JsonFormatter(logging.Formatter):
def format(self, record):
payload = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
if record.exc_info:
payload["exception"] = self.formatException(record.exc_info)
return json.dumps(payload, ensure_ascii=False)
def configure_logging(app):
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
app.logger.handlers.clear()
app.logger.addHandler(handler)
app.logger.setLevel(app.config["LOG_LEVEL"])
app.logger.propagate = False
+1
View File
@@ -0,0 +1 @@
Single-database configuration for Flask.
+50
View File
@@ -0,0 +1,50 @@
# A generic, single database configuration.
[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic,flask_migrate
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[logger_flask_migrate]
level = INFO
handlers =
qualname = flask_migrate
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+113
View File
@@ -0,0 +1,113 @@
import logging
from logging.config import fileConfig
from flask import current_app
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
def get_engine():
try:
# this works with Flask-SQLAlchemy<3 and Alchemical
return current_app.extensions['migrate'].db.get_engine()
except (TypeError, AttributeError):
# this works with Flask-SQLAlchemy>=3
return current_app.extensions['migrate'].db.engine
def get_engine_url():
try:
return get_engine().url.render_as_string(hide_password=False).replace(
'%', '%%')
except AttributeError:
return str(get_engine().url).replace('%', '%%')
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
config.set_main_option('sqlalchemy.url', get_engine_url())
target_db = current_app.extensions['migrate'].db
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def get_metadata():
if hasattr(target_db, 'metadatas'):
return target_db.metadatas[None]
return target_db.metadata
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=get_metadata(), literal_binds=True
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')
conf_args = current_app.extensions['migrate'].configure_args
if conf_args.get("process_revision_directives") is None:
conf_args["process_revision_directives"] = process_revision_directives
connectable = get_engine()
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=get_metadata(),
**conf_args
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+24
View File
@@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}
@@ -0,0 +1,55 @@
"""user table
Revision ID: 0f62f2706427
Revises:
Create Date: 2023-12-04 12:52:57.863223
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "0f62f2706427"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
"user",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("email", sa.String(length=80), nullable=True),
sa.Column("username", sa.String(length=100), nullable=True),
sa.Column("password_hash", sa.String(length=255), nullable=True),
sa.Column("token", sa.String(length=32), nullable=True),
sa.Column("token_expiration", sa.DateTime(), nullable=True),
sa.Column("refresh_token", sa.String(length=32), nullable=True),
sa.Column("reset_password_code", sa.String(length=8), nullable=True),
sa.Column("reset_password_expiration", sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("email"),
)
with op.batch_alter_table("user", schema=None) as batch_op:
batch_op.create_index(
batch_op.f("ix_user_refresh_token"), ["refresh_token"], unique=True
)
batch_op.create_index(
batch_op.f("ix_user_reset_password_code"),
["reset_password_code"],
unique=True,
)
batch_op.create_index(
batch_op.f("ix_user_token"), ["token"], unique=True
)
def downgrade():
with op.batch_alter_table("user", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_user_token"))
batch_op.drop_index(batch_op.f("ix_user_reset_password_code"))
batch_op.drop_index(batch_op.f("ix_user_refresh_token"))
op.drop_table("user")
@@ -0,0 +1,70 @@
"""add account email tokens
Revision ID: 7a4e1b9c2d3f
Revises: 0f62f2706427
Create Date: 2026-08-28
"""
from alembic import op
import sqlalchemy as sa
revision = "7a4e1b9c2d3f"
down_revision = "0f62f2706427"
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("user", schema=None) as batch_op:
batch_op.add_column(
sa.Column("email_verified_at", sa.DateTime(), nullable=True)
)
batch_op.drop_index(batch_op.f("ix_user_reset_password_code"))
batch_op.drop_column("reset_password_expiration")
batch_op.drop_column("reset_password_code")
op.create_table(
"account_token",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("purpose", sa.String(length=32), nullable=False),
sa.Column("token_hash", sa.String(length=64), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("expires_at", sa.DateTime(), nullable=False),
sa.Column("used_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(["user_id"], ["user.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("token_hash"),
)
with op.batch_alter_table("account_token", schema=None) as batch_op:
batch_op.create_index(
batch_op.f("ix_account_token_expires_at"), ["expires_at"]
)
batch_op.create_index(
batch_op.f("ix_account_token_purpose"), ["purpose"]
)
batch_op.create_index(
batch_op.f("ix_account_token_user_id"), ["user_id"]
)
def downgrade():
with op.batch_alter_table("account_token", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_account_token_user_id"))
batch_op.drop_index(batch_op.f("ix_account_token_purpose"))
batch_op.drop_index(batch_op.f("ix_account_token_expires_at"))
op.drop_table("account_token")
with op.batch_alter_table("user", schema=None) as batch_op:
batch_op.add_column(
sa.Column("reset_password_code", sa.String(length=8), nullable=True)
)
batch_op.add_column(
sa.Column("reset_password_expiration", sa.DateTime(), nullable=True)
)
batch_op.create_index(
batch_op.f("ix_user_reset_password_code"),
["reset_password_code"],
unique=True,
)
batch_op.drop_column("email_verified_at")
+2
View File
@@ -0,0 +1,2 @@
from .user import User # noqa
from .account_token import AccountToken # noqa
+69
View File
@@ -0,0 +1,69 @@
import hashlib
import hmac
import secrets
from datetime import datetime, timedelta
from settings import db
def utcnow():
return datetime.utcnow()
class AccountToken(db.Model):
__tablename__ = "account_token"
PURPOSE_EMAIL_VERIFICATION = "email_verification"
PURPOSE_PASSWORD_RESET = "password_reset"
PURPOSES = {PURPOSE_EMAIL_VERIFICATION, PURPOSE_PASSWORD_RESET}
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(
db.Integer, db.ForeignKey("user.id"), nullable=False, index=True
)
purpose = db.Column(db.String(32), nullable=False, index=True)
token_hash = db.Column(db.String(64), nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False, default=utcnow)
expires_at = db.Column(db.DateTime, nullable=False, index=True)
used_at = db.Column(db.DateTime, nullable=True)
user = db.relationship("User")
@staticmethod
def hash_token(token, purpose):
return hashlib.sha256(f"{purpose}:{token}".encode()).hexdigest()
@classmethod
def issue(cls, user, purpose, lifetime):
if purpose not in cls.PURPOSES:
raise ValueError("Unsupported account token purpose")
cls.query.filter_by(user_id=user.id, purpose=purpose, used_at=None).update(
{"used_at": utcnow()}
)
raw_token = secrets.token_urlsafe(32)
token = cls(
user_id=user.id,
purpose=purpose,
token_hash=cls.hash_token(raw_token, purpose),
expires_at=utcnow() + lifetime,
)
db.session.add(token)
return token, raw_token
@classmethod
def find_valid(cls, raw_token, purpose):
if not isinstance(raw_token, str) or not raw_token or purpose not in cls.PURPOSES:
return None
candidate = cls.hash_token(raw_token, purpose)
token = cls.query.filter_by(token_hash=candidate, purpose=purpose).first()
if token is None or not hmac.compare_digest(token.token_hash, candidate):
return None
return token if token.is_valid else None
@property
def is_valid(self):
return self.used_at is None and self.expires_at > utcnow()
def consume(self):
if not self.is_valid:
raise ValueError("Token is invalid or expired")
self.used_at = utcnow()
+64
View File
@@ -0,0 +1,64 @@
from werkzeug.security import generate_password_hash, check_password_hash
from settings import db
import base64
from datetime import datetime, timedelta
import os
def normalize_email(email):
return email.strip().casefold()
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(80), unique=True)
username = db.Column(db.String(100))
password_hash = db.Column(db.String(255))
token = db.Column(db.String(32), index=True, unique=True)
token_expiration = db.Column(db.DateTime)
refresh_token = db.Column(db.String(32), index=True, unique=True)
email_verified_at = db.Column(db.DateTime, nullable=True)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
@staticmethod
def normalize_email(email):
return normalize_email(email)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return "<User {}, {}>".format(self.id, self.username)
def to_dict(self):
return {"id": self.id, "username": self.username}
def get_token(self, expires_in=3600):
now = datetime.utcnow()
if self.token and self.token_expiration > now + timedelta(seconds=60):
return self.token
self.token = base64.b64encode(os.urandom(24)).decode("utf-8")
self.token_expiration = now + timedelta(seconds=expires_in)
db.session.add(self)
return self.token
def get_refresh_token(self):
if self.refresh_token:
return self.refresh_token
self.refresh_token = base64.b64encode(os.urandom(24)).decode("utf-8")
db.session.add(self)
return self.refresh_token
def revoke_tokens(self):
self.token_expiration = datetime.utcnow() - timedelta(seconds=1)
self.refresh_token = None
@staticmethod
def check_token(token):
user = User.query.filter_by(token=token).first()
if user is None or user.token_expiration < datetime.utcnow():
return None
return user
+3
View File
@@ -0,0 +1,3 @@
[pytest]
testpaths = tests
addopts = -q
+56
View File
@@ -0,0 +1,56 @@
"""Generic contact-form endpoint."""
from email.utils import parseaddr
from flask import request
from email_service import EmailDeliveryError, send_contact_email
from errors import error_response
from settings import app, limiter
def valid_email(value):
return bool(
value
and "\r" not in value
and "\n" not in value
and parseaddr(value)[1] == value
and "@" in value
)
@app.post("/api/contact")
@limiter.limit("5 per hour")
def contact():
req = request.get_json(silent=True) or {}
# Quietly accept bot submissions that fill the hidden honeypot field.
if req.get("website"):
return {"success": True}
name = req.get("name", "").strip()
email = req.get("email", "").strip()
subject = req.get("subject", "").strip()
message = req.get("message", "").strip()
if not (1 <= len(name) <= 100 and valid_email(email)):
return error_response(400, "A valid name and email are required")
if not (
1 <= len(subject) <= 150
and "\r" not in subject
and "\n" not in subject
and 10 <= len(message) <= 5000
):
return error_response(400, "A valid subject and message are required")
try:
send_contact_email(
name=name,
email=email,
subject=subject,
message=message,
)
except EmailDeliveryError:
app.logger.error("Contact email delivery failed")
return error_response(503, "Unable to send message right now")
return {"success": True}
+34
View File
@@ -0,0 +1,34 @@
from settings import app
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from settings import db
from .token_routes import * # noqa: F401 F403
from .user_routes import * # noqa: F401 F403
from .contact_routes import * # noqa: F401 F403
@app.route("/api/test")
def test_route():
"""Test."""
return {"success": True}
@app.get("/api/health")
def health():
"""Backward-compatible liveness probe."""
return {"status": "ok"}
@app.get("/api/health/live")
def health_live():
return {"status": "ok"}
@app.get("/api/health/ready")
def health_ready():
try:
db.session.execute(text("SELECT 1"))
except SQLAlchemyError:
app.logger.error("Database readiness check failed")
return {"status": "unavailable"}, 503
return {"status": "ready"}
+69
View File
@@ -0,0 +1,69 @@
"""Token routes."""
from flask import jsonify, make_response, request
from settings import db, app
from auth import token_auth, basic_auth
from models.user import User
from errors import error_response
# todo - put in basic_auth
basic_auth.scheme = "Custom"
basic_auth.realm = "Incorrect Credentials"
@app.route("/api/auth/tokens", methods=["POST"])
@basic_auth.login_required
def get_token():
"""Get token."""
token = basic_auth.current_user().get_token()
refresh_token = basic_auth.current_user().get_refresh_token()
db.session.commit()
response = make_response(
jsonify(
{
"token": token,
"username": basic_auth.current_user().username,
"user_id": basic_auth.current_user().id,
}
)
)
response.set_cookie(
"refresh_token",
value=refresh_token,
httponly=app.config["SESSION_COOKIE_HTTPONLY"],
secure=app.config["SESSION_COOKIE_SECURE"],
samesite=app.config["SESSION_COOKIE_SAMESITE"],
)
return response
@app.route("/api/auth/tokens", methods=["DELETE"])
@token_auth.login_required
def revoke_token():
"""Revoke token."""
token_auth.current_user().revoke_tokens()
db.session.commit()
response = make_response(jsonify({"success": True}))
response.delete_cookie(
"refresh_token",
httponly=app.config["SESSION_COOKIE_HTTPONLY"],
secure=app.config["SESSION_COOKIE_SECURE"],
samesite=app.config["SESSION_COOKIE_SAMESITE"],
)
return response
@app.route("/api/auth/refresh", methods=["GET"])
def refresh_token():
"""Refresh token."""
refresh_token = request.cookies.get("refresh_token")
if refresh_token is None:
return error_response(400, "Bad request, no refresh token")
user = User.query.filter_by(refresh_token=refresh_token).first()
if user is not None:
access_token = user.get_token()
db.session.commit()
return {
"token": access_token,
"user_id": user.id,
}
return error_response(401, "Invalid refresh token")
+146
View File
@@ -0,0 +1,146 @@
"""Generic account routes."""
from datetime import datetime, timedelta
from flask import request
from sqlalchemy import func
from sqlalchemy.exc import IntegrityError
from auth import token_auth
from email_service import (
EmailDeliveryError,
send_password_reset_email,
send_verification_email,
)
from errors import error_response
from models.account_token import AccountToken
from models.user import User, normalize_email
from settings import app, db, limiter
@app.get("/api/user/registration-status")
def registration_status():
return {"mode": app.config["REGISTRATION_MODE"]}
@app.get("/api/user/profile")
@token_auth.login_required
def get_user_profile():
return token_auth.current_user().to_dict()
@app.get("/api/user/current")
@token_auth.login_required
def get_current_user():
return token_auth.current_user().to_dict()
@app.post("/api/user/register")
@limiter.limit("5 per hour")
def register_user():
if app.config["REGISTRATION_MODE"] == "closed":
return error_response(403, "Registration is closed")
req = request.get_json(silent=True) or {}
if not all(req.get(field) for field in ("email", "username", "password")):
return error_response(400, "Email, username, and password are required")
if len(req["password"]) < 8:
return error_response(400, "Password must contain at least 8 characters")
email = normalize_email(req["email"])
if User.query.filter(func.lower(User.email) == email).first() is not None:
return error_response(409, "Email exists")
user = User(username=req["username"].strip(), email=email)
user.set_password(req["password"])
db.session.add(user)
try:
db.session.flush()
_, raw_token = AccountToken.issue(
user,
AccountToken.PURPOSE_EMAIL_VERIFICATION,
timedelta(hours=24),
)
db.session.commit()
except IntegrityError:
db.session.rollback()
return error_response(409, "Unable to create account")
try:
send_verification_email(user, raw_token)
except EmailDeliveryError:
app.logger.error("Verification email delivery failed")
return {"success": True}, 201
@app.post("/api/user/verify-email")
@limiter.limit("20 per hour")
def verify_email():
req = request.get_json(silent=True) or {}
token = AccountToken.find_valid(
req.get("token"), AccountToken.PURPOSE_EMAIL_VERIFICATION
)
if token is None:
return error_response(400, "Verification link is invalid or expired")
token.user.email_verified_at = datetime.utcnow()
token.consume()
db.session.commit()
return {"success": True}
@app.post("/api/user/resend-verification")
@limiter.limit("3 per hour")
def resend_verification():
req = request.get_json(silent=True) or {}
email = normalize_email(req.get("email", ""))
user = User.query.filter(func.lower(User.email) == email).first()
if user is not None and user.email_verified_at is None:
_, raw_token = AccountToken.issue(
user,
AccountToken.PURPOSE_EMAIL_VERIFICATION,
timedelta(hours=24),
)
db.session.commit()
try:
send_verification_email(user, raw_token)
except EmailDeliveryError:
app.logger.error("Verification email delivery failed")
return {"success": True}
@app.post("/api/user/reset-password")
@limiter.limit("3 per hour")
def request_password_reset():
req = request.get_json(silent=True) or {}
email = normalize_email(req.get("email", ""))
user = User.query.filter(func.lower(User.email) == email).first()
if user is not None:
_, raw_token = AccountToken.issue(
user,
AccountToken.PURPOSE_PASSWORD_RESET,
timedelta(hours=1),
)
db.session.commit()
try:
send_password_reset_email(user, raw_token)
except EmailDeliveryError:
app.logger.error("Password reset email delivery failed")
return {"success": True}
@app.post("/api/user/update-password")
@limiter.limit("10 per hour")
def update_password():
req = request.get_json(silent=True) or {}
if len(req.get("password", "")) < 8:
return error_response(400, "Password must contain at least 8 characters")
token = AccountToken.find_valid(
req.get("token"), AccountToken.PURPOSE_PASSWORD_RESET
)
if token is None:
return error_response(400, "Reset link is invalid or expired")
token.user.set_password(req["password"])
token.user.revoke_tokens()
token.consume()
db.session.commit()
return {"success": True}
+116
View File
@@ -0,0 +1,116 @@
import os
from dotenv import load_dotenv
from flask import Flask
from flask_cors import CORS
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from werkzeug.middleware.proxy_fix import ProxyFix
from logging_config import configure_logging
environment = os.environ.get("APP_ENV", "development").lower()
if environment == "development":
load_dotenv()
environment = os.environ.get("APP_ENV", environment).lower()
if environment not in {"development", "testing", "production"}:
raise RuntimeError(
"APP_ENV must be one of: development, testing, production"
)
def env_bool(name, default=False):
value = os.environ.get(name)
if value is None:
return default
return value.lower() in {"1", "true", "yes", "on"}
convention = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
app = Flask(__name__)
app.config.update(
{
"APP_ENV": environment,
"DEBUG": env_bool("DEBUG", environment == "development"),
"TESTING": environment == "testing",
"SECRET_KEY": os.environ.get("SECRET_KEY"),
"SQLALCHEMY_DATABASE_URI": os.environ.get(
"SQLALCHEMY_DATABASE_URI",
"sqlite:///:memory:"
if environment == "testing"
else "sqlite:///mydatabase.sqlite",
),
"SQLALCHEMY_ECHO": env_bool("SQLALCHEMY_ECHO"),
"SQLALCHEMY_TRACK_MODIFICATIONS": env_bool(
"SQLALCHEMY_TRACK_MODIFICATIONS"
),
"APP_URL": os.environ.get("APP_URL", "http://localhost:8080").rstrip("/"),
"CORS_ORIGINS": [
origin.strip()
for origin in os.environ.get("CORS_ORIGINS", "*").split(",")
if origin.strip()
],
"REGISTRATION_MODE": os.environ.get("REGISTRATION_MODE", "open").lower(),
"EMAIL_DELIVERY_ENABLED": env_bool(
"EMAIL_DELIVERY_ENABLED", environment == "production"
),
"RESEND_API_KEY": os.environ.get("RESEND_API_KEY"),
"EMAIL_FROM": os.environ.get("EMAIL_FROM"),
"CONTACT_EMAIL": os.environ.get("CONTACT_EMAIL"),
"LOG_LEVEL": os.environ.get("LOG_LEVEL", "INFO").upper(),
"MAX_CONTENT_LENGTH": int(os.environ.get("MAX_CONTENT_LENGTH", 1_048_576)),
"RATELIMIT_ENABLED": env_bool("RATELIMIT_ENABLED", True),
"SESSION_COOKIE_SECURE": env_bool(
"SESSION_COOKIE_SECURE", environment == "production"
),
"SESSION_COOKIE_HTTPONLY": env_bool("SESSION_COOKIE_HTTPONLY", True),
"SESSION_COOKIE_SAMESITE": os.environ.get("SESSION_COOKIE_SAMESITE", "Lax"),
}
)
if app.config["REGISTRATION_MODE"] not in {"open", "closed"}:
raise RuntimeError("REGISTRATION_MODE must be one of: open, closed")
if environment == "production":
required = ["SECRET_KEY", "SQLALCHEMY_DATABASE_URI", "CORS_ORIGINS"]
if app.config["EMAIL_DELIVERY_ENABLED"]:
required.extend(
["RESEND_API_KEY", "EMAIL_FROM", "CONTACT_EMAIL", "APP_URL"]
)
missing = [name for name in required if not os.environ.get(name)]
if missing:
raise RuntimeError(
"Missing required production configuration: " + ", ".join(missing)
)
if len(app.config["SECRET_KEY"]) < 32:
raise RuntimeError("SECRET_KEY must contain at least 32 characters in production")
if "*" in app.config["CORS_ORIGINS"]:
raise RuntimeError("CORS_ORIGINS must not contain '*' in production")
if app.config["SESSION_COOKIE_SAMESITE"].lower() == "none" and not app.config[
"SESSION_COOKIE_SECURE"
]:
raise RuntimeError("SESSION_COOKIE_SAMESITE=None requires SESSION_COOKIE_SECURE=true")
if app.config["SQLALCHEMY_ECHO"]:
raise RuntimeError("SQLALCHEMY_ECHO must be disabled in production")
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
configure_logging(app)
metadata = MetaData(naming_convention=convention)
db = SQLAlchemy(app, metadata=metadata)
migrate = Migrate(app, db, render_as_batch=True)
CORS(app, origins=app.config["CORS_ORIGINS"], supports_credentials=True)
limiter = Limiter(
get_remote_address,
app=app,
enabled=app.config["RATELIMIT_ENABLED"],
storage_uri="memory://",
)
+32
View File
@@ -0,0 +1,32 @@
import os
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
TEST_DEFAULTS = {
"APP_ENV": "testing",
"SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:",
"SECRET_KEY": "test-key",
"REGISTRATION_MODE": "open",
"EMAIL_DELIVERY_ENABLED": "false",
"RATELIMIT_ENABLED": "true",
}
for name, value in TEST_DEFAULTS.items():
os.environ.setdefault(name, value)
import pytest
from api import app
from settings import db, limiter
@pytest.fixture()
def client():
with app.app_context():
limiter.reset()
db.create_all()
yield app.test_client()
db.session.remove()
db.drop_all()
limiter.reset()
+157
View File
@@ -0,0 +1,157 @@
import base64
from datetime import datetime, timedelta
from models.account_token import AccountToken
from models.user import User
from settings import app, db
def register(client, **overrides):
payload = {
"email": "person@example.com",
"username": "person",
"password": "long-enough-password",
**overrides,
}
return client.post("/api/user/register", json=payload)
def basic_header(email="person@example.com", password="long-enough-password"):
encoded = base64.b64encode(f"{email}:{password}".encode()).decode()
return {"Authorization": f"Basic {encoded}"}
def test_health_and_registration_status(client):
assert client.get("/api/health").get_json() == {"status": "ok"}
assert client.get("/api/health/live").get_json() == {"status": "ok"}
assert client.get("/api/health/ready").get_json() == {"status": "ready"}
assert client.get("/api/user/registration-status").get_json() == {
"mode": "open"
}
def test_readiness_failure_is_generic(client, monkeypatch):
from sqlalchemy.exc import OperationalError
def fail(_statement):
raise OperationalError("SELECT 1", {}, RuntimeError("private database detail"))
monkeypatch.setattr("routes.routes.db.session.execute", fail)
response = client.get("/api/health/ready")
assert response.status_code == 503
assert response.get_json() == {"status": "unavailable"}
def test_registration_normalizes_email_and_hashes_one_time_token(client):
response = register(client, email=" PERSON@Example.COM ")
assert response.status_code == 201
user = User.query.one()
token = AccountToken.query.one()
assert user.email == "person@example.com"
assert user.password_hash != "long-enough-password"
assert token.purpose == AccountToken.PURPOSE_EMAIL_VERIFICATION
assert len(token.token_hash) == 64
def test_registration_validates_input_and_duplicate_email(client):
assert register(client, password="short").status_code == 400
assert register(client).status_code == 201
assert register(client, email="PERSON@example.com").status_code == 409
def test_closed_registration_rejects_accounts(client):
original = app.config["REGISTRATION_MODE"]
app.config["REGISTRATION_MODE"] = "closed"
try:
assert register(client).status_code == 403
finally:
app.config["REGISTRATION_MODE"] = original
def test_login_refresh_logout_cycle(client):
assert register(client).status_code == 201
login = client.post("/api/auth/tokens", headers=basic_header())
assert login.status_code == 200
token = login.get_json()["token"]
refreshed = client.get("/api/auth/refresh")
assert refreshed.status_code == 200
assert refreshed.get_json()["user_id"] == login.get_json()["user_id"]
logout = client.delete(
"/api/auth/tokens", headers={"Authorization": f"Bearer {token}"}
)
assert logout.status_code == 200
assert client.get("/api/auth/refresh").status_code == 400
def test_password_reset_is_non_enumerating_and_single_use(client):
assert register(client).status_code == 201
assert client.post(
"/api/user/reset-password", json={"email": "missing@example.com"}
).status_code == 200
assert client.post(
"/api/user/reset-password", json={"email": "person@example.com"}
).status_code == 200
token = AccountToken.query.filter_by(
purpose=AccountToken.PURPOSE_PASSWORD_RESET
).one()
assert token.token_hash
assert client.post(
"/api/user/update-password",
json={"token": "not-the-token", "password": "new-password-value"},
).status_code == 400
def test_verification_and_password_reset_tokens_are_consumed(client, monkeypatch):
captured = {}
def capture_verification(user, raw_token):
captured["verification"] = raw_token
def capture_reset(user, raw_token):
captured["reset"] = raw_token
monkeypatch.setattr("routes.user_routes.send_verification_email", capture_verification)
monkeypatch.setattr("routes.user_routes.send_password_reset_email", capture_reset)
assert register(client).status_code == 201
assert client.post(
"/api/user/verify-email", json={"token": captured["verification"]}
).status_code == 200
assert client.post(
"/api/user/verify-email", json={"token": captured["verification"]}
).status_code == 400
assert client.post(
"/api/user/reset-password", json={"email": "person@example.com"}
).status_code == 200
assert client.post(
"/api/user/update-password",
json={"token": captured["reset"], "password": "replacement-password"},
).status_code == 200
assert client.post(
"/api/user/update-password",
json={"token": captured["reset"], "password": "another-password"},
).status_code == 400
assert client.post(
"/api/auth/tokens",
headers=basic_header(password="replacement-password"),
).status_code == 200
def test_expired_account_tokens_are_rejected(client, monkeypatch):
captured = {}
monkeypatch.setattr(
"routes.user_routes.send_verification_email",
lambda _user, raw_token: captured.update(verification=raw_token),
)
assert register(client).status_code == 201
token = AccountToken.query.filter_by(
purpose=AccountToken.PURPOSE_EMAIL_VERIFICATION
).one()
token.expires_at = datetime.utcnow() - timedelta(seconds=1)
db.session.commit()
response = client.post(
"/api/user/verify-email", json={"token": captured["verification"]}
)
assert response.status_code == 400
assert response.get_json()["message"] == "Verification link is invalid or expired"
+67
View File
@@ -0,0 +1,67 @@
from email_service import EmailDeliveryError
VALID_MESSAGE = {
"name": "Example Person",
"email": "person@example.com",
"subject": "A useful question",
"message": "This message is long enough to be accepted.",
"website": "",
}
def test_contact_delivers_valid_message(client, monkeypatch):
delivered = {}
def capture(**payload):
delivered.update(payload)
monkeypatch.setattr("routes.contact_routes.send_contact_email", capture)
response = client.post("/api/contact", json=VALID_MESSAGE)
assert response.status_code == 200
assert delivered == {
key: VALID_MESSAGE[key] for key in ("name", "email", "subject", "message")
}
def test_contact_rejects_invalid_and_injection_input(client):
assert client.post("/api/contact", json={}).status_code == 400
assert client.post(
"/api/contact",
json={**VALID_MESSAGE, "email": "person@example.com\nBcc:test@example.com"},
).status_code == 400
assert client.post(
"/api/contact",
json={**VALID_MESSAGE, "subject": "Hello\r\nBcc: test@example.com"},
).status_code == 400
assert client.post(
"/api/contact", json={**VALID_MESSAGE, "message": "short"}
).status_code == 400
def test_contact_honeypot_does_not_deliver(client, monkeypatch):
def unexpected(**_payload):
raise AssertionError("honeypot submission must not be delivered")
monkeypatch.setattr("routes.contact_routes.send_contact_email", unexpected)
response = client.post(
"/api/contact", json={**VALID_MESSAGE, "website": "https://bot.invalid"}
)
assert response.status_code == 200
def test_contact_delivery_failure_is_generic(client, monkeypatch):
def fail(**_payload):
raise EmailDeliveryError("provider detail must not escape")
monkeypatch.setattr("routes.contact_routes.send_contact_email", fail)
response = client.post("/api/contact", json=VALID_MESSAGE)
assert response.status_code == 503
assert response.get_json()["message"] == "Unable to send message right now"
def test_contact_rate_limit_rejects_sixth_submission(client, monkeypatch):
monkeypatch.setattr("routes.contact_routes.send_contact_email", lambda **_: None)
responses = [client.post("/api/contact", json=VALID_MESSAGE) for _ in range(6)]
assert [response.status_code for response in responses[:5]] == [200] * 5
assert responses[5].status_code == 429