diff --git a/.env.example b/.env.example index 16daa4e..2e458ea 100644 --- a/.env.example +++ b/.env.example @@ -2,6 +2,11 @@ APP_NAME=Contínuos CRR SECRET_KEY=replace-with-a-long-random-value DATABASE_URL=sqlite:///./data/bar_rota.db BASE_URL=http://localhost:8000 + +# Behind a reverse proxy: the public address of the app, used in notification e-mails. +# ROOT_PATH is the prefix the proxy serves us under, e.g. /crr for https://host/crr/. +# Leave it empty when the app is at the root of the domain. +ROOT_PATH= PORT=8000 # Host directory bind-mounted at /app/data (used by docker compose only). @@ -25,5 +30,5 @@ SMTP_STARTTLS=true # Reminder command looks this many days ahead. REMINDER_DAYS_AHEAD=1 -# Set true when the app is served only over HTTPS. +# Set true when the app is served only over HTTPS (always true behind a TLS proxy). SESSION_HTTPS_ONLY=false diff --git a/Dockerfile b/Dockerfile index 6b1f3b5..80b40c5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ RUN pip install --no-cache-dir -r requirements.txt COPY . . RUN mkdir -p /app/data EXPOSE 8000 -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*"] # Development image: base plus dev dependencies. Used by docker-compose.dev.yml, # which supplies the reload command and per-service environment. @@ -18,7 +18,7 @@ FROM base AS dev COPY requirements-dev.txt ./ RUN pip install --no-cache-dir -r requirements-dev.txt -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload", "--proxy-headers", "--forwarded-allow-ips", "*"] # Keep plain `docker build .` on the production runtime as well. FROM base AS production diff --git a/Makefile b/Makefile index c72214b..64c2c8a 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,7 @@ dev-setup: setup # Host run with auto-reload, for fast debugging. dev: setup @test -x $(PYTHON) || (echo "Run 'make dev-setup' first." && exit 1) - $(PYTHON) -m uvicorn app.main:app --reload --port $(PORT) + $(PYTHON) -m uvicorn app.main:app --reload --port $(PORT) --proxy-headers --forwarded-allow-ips '*' # Full app in Docker with bind mounts and auto-reload. dev-up: setup diff --git a/README.md b/README.md index 2771825..7077077 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,8 @@ docker compose ps # includes the HTTP healthcheck status To move to another machine, stop the app, copy the **entire `data/` directory** and your `.env` configuration to the new project checkout, then run the deployment command there. Keep these private files out of Git and Docker images. Stopping the app before copying also avoids copying an active SQLite database mid-write. +Behind a reverse proxy, set `BASE_URL` to the public address (used in e-mail links), `ROOT_PATH` to the prefix the app is served under when it is not at the domain root (for example `/crr` for `https://host/crr/`), and `SESSION_HTTPS_ONLY=true` when the proxy terminates TLS. Uvicorn runs with `--proxy-headers --forwarded-allow-ips '*'`, so `X-Forwarded-Proto`/`X-Forwarded-Host` set the scheme and host used in generated URLs and cookies; the proxy must forward them and keep the prefix it advertises. + `DATA_DIR` changes the Docker host directory mounted at `/app/data`. Keep `DATABASE_URL=sqlite:///./data/bar_rota.db` in Docker: this path is relative to `/app` inside the container. For seamless switching between host and Docker, use the default `DATA_DIR=./data`; a custom directory requires a matching host `DATABASE_URL` when running locally. The port for Make development commands is selected with `PORT=...`; direct Compose commands use `.env`'s `PORT`. Update `BASE_URL` when changing the URL used in notification links. ## Email diff --git a/app/config.py b/app/config.py index 23fd05c..692baf0 100644 --- a/app/config.py +++ b/app/config.py @@ -8,6 +8,11 @@ class Settings(BaseSettings): secret_key: str = "dev-only-change-me" database_url: str = "sqlite:///./data/bar_rota.db" base_url: str = "http://localhost:8000" + # Prefix the reverse proxy serves the app under, e.g. "/crr" for https://host/crr/. + # The proxy must forward that prefix (X-Forwarded-Prefix) or the paths here must match. + root_path: str = "" + # Networks allowed to set X-Forwarded-*; "*" for a private docker network. + trusted_proxy_hosts: str = "*" initial_admin_name: str = "Administrador" initial_admin_username: str = "admin" @@ -31,5 +36,20 @@ class Settings(BaseSettings): def normalized_base_url(self) -> str: return self.base_url.rstrip("/") + @property + def prefix(self) -> str: + """The path the reverse proxy serves the app under, without a trailing slash.""" + return self.root_path.rstrip("/") + + def url(self, path: str) -> str: + """Prefix an internal path so it keeps working under a sub-path deployment.""" + if not self.prefix or not path.startswith("/") or path.startswith("//"): + return path + cut = min( + (index for index in (path.find("?"), path.find("#")) if index != -1), + default=len(path), + ) + return f"{self.prefix}{path[:cut]}{path[cut:]}" + settings = Settings() diff --git a/app/main.py b/app/main.py index 8e53c98..f466a85 100644 --- a/app/main.py +++ b/app/main.py @@ -46,7 +46,9 @@ async def lifespan(app: FastAPI): yield -app = FastAPI(title=settings.app_name, lifespan=lifespan) +app = FastAPI(title=settings.app_name, lifespan=lifespan, root_path=settings.root_path) +# Behind a reverse proxy, uvicorn runs with --proxy-headers so X-Forwarded-Proto/Host +# set the public scheme and host; ROOT_PATH adds the prefix the proxy serves us under. app.add_middleware( SessionMiddleware, secret_key=settings.secret_key, @@ -70,5 +72,6 @@ templates.env.filters.update( "evento": event_type_label, } ) +templates.env.globals["app_path"] = settings.url app.state.templates = templates app.include_router(router) diff --git a/app/templates/admin_assign.html b/app/templates/admin_assign.html index b24010a..4d058fe 100644 --- a/app/templates/admin_assign.html +++ b/app/templates/admin_assign.html @@ -3,26 +3,26 @@ {% block content %}