Author SHA1 Message Date
Bobby 341cd05ac5 01: infra 2026-11-17 14:39:40 -05:00
Bobby ec9bb74be0 setup 2026-11-17 12:32:17 -05:00
Bobby 238371147c rm scratch folder 2026-11-16 18:06:25 -05:00
Bobby f46e184d00 mvp: fix CI/CD ticket filename 2026-11-16 17:23:06 -05:00
Bobby 586bd6d7e5 mvp: publish ticket files 2026-11-16 17:19:28 -05:00
Bobby 671ab2928b docs: add MVP spec and glossary for HAPI 2026-11-16 16:48:32 -05:00
101 changed files with 2367 additions and 1094 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
uv.lock linguist-generated=true
-8
View File
@@ -1,8 +0,0 @@
.claude/
.venv/
__pycache__/
*.py[cod]
.pytest_cache/
.ruff_cache/
dist/
build/
@@ -0,0 +1,14 @@
# 01: Infrastructure Setup
**What to build:** Linode infrastructure provisioned via Terraform: PostgreSQL database (with StatefulSet for production), Object Storage, and basic networking. Enables all other components to run.
**Blocked by:** None (can start immediately)
**Status:** ready-for-agent
- [ ] Terraform state stored in Linode Object Storage
- [ ] PostgreSQL database created (separate staging/production instances)
- [ ] Linode Object Storage buckets created for uploads
- [ ] Kubernetes StatefulSet for PostgreSQL production deployed
- [ ] Basic networking (firewall rules, load balancer) configured
- [ ] UptimeKuma configured to poll `/health` endpoint
@@ -0,0 +1,15 @@
# 01a: Linode Infrastructure with Terraform
**What to build:** Provision Linode infrastructure via Terraform: PostgreSQL database (separate staging/production), Object Storage buckets, and basic networking. Enables all other components to run.
**Blocked by:** None (can start immediately)
**Status:** ready-for-agent
- [ ] Terraform state stored in Linode Object Storage (backend configuration)
- [ ] PostgreSQL database instance for staging created
- [ ] PostgreSQL database instance for production created
- [ ] Linode Object Storage bucket for staging uploads created
- [ ] Linode Object Storage bucket for production uploads created
- [ ] Basic networking: firewall rules configured for API, PostgreSQL, Adminer
- [ ] Terraform outputs exported (database endpoints, object storage credentials)
@@ -0,0 +1,14 @@
# 01b: Kubernetes StatefulSet for Production PostgreSQL
**What to build:** Kubernetes StatefulSet for production PostgreSQL with persistent storage, enabling learnable infrastructure with stateful workload patterns.
**Blocked by:** 01a (Linode Infrastructure with Terraform)
**Status:** ready-for-agent
- [ ] Kubernetes cluster configured (or existing cluster accessible)
- [ ] StatefulSet manifest for PostgreSQL defined
- [ ] PersistentVolumeClaim for PostgreSQL data configured
- [ ] StatefulSet deployed to production cluster
- [ ] PostgreSQL pod healthy and accepting connections
- [ ] PostgreSQL version verified (e.g., 15.x or 16.x)
@@ -0,0 +1,15 @@
# 02: Database Schema & Migrations
**What to build:** PostgreSQL database initialized with Alembic migrations. First schema includes users table, auth tokens, and basic metadata. CI runs migrations on deploy.
**Blocked by:** 01 (Infrastructure Setup)
**Status:** ready-for-agent
- [ ] Alembic migrations configured and running
- [ ] Users table with JWT token support created
- [ ] Auth tokens table for API key rotation created
- [ ] Migrations applied in staging environment
- [ ] Migrations applied in production environment
- [ ] CI workflow runs migrations on deploy (staging on push to `main`, production on tags)
- [ ] Migration rollback capability tested (e.g., `alembic downgrade + upgrade`)
@@ -0,0 +1,15 @@
# 02a: Alembic Migration Framework
**What to build:** Alembic configured and running with additive-by-default migrations, destructive changes behind flags.
**Blocked by:** 01a (Linode Infrastructure with Terraform)
**Status:** ready-for-agent
- [ ] Alembic initialized in FastAPI project (`alembic init`)
- [ ] `alembic.ini` configured with environment-specific URLs (staging/production)
- [ ] First migration created (empty schema or minimal `users` table)
- [ ] Migration applied to staging database
- [ ] Migration applied to production database
- [ ] Migration rollback tested (`alembic downgrade + upgrade`)
- [ ] CI workflow step added to run migrations on deploy
@@ -0,0 +1,13 @@
# 02b: Users Table & Auth Tokens Schema
**What to build:** Database schema for users and authentication tokens with JWT support.
**Blocked by:** 02a (Alembic Migration Framework)
**Status:** ready-for-agent
- [ ] `users` table created with columns: id, email, hashed_password, is_active, created_at, updated_at
- [ ] `auth_tokens` table created with columns: id, user_id, token, token_type, expires_at, revoked_at
- [ ] Indexes added for common queries (email lookup, token expiration)
- [ ] Migration applied to staging and production
- [ ] Database constraints verified (unique email, foreign key to users)
@@ -0,0 +1,15 @@
# 03: FastAPI Application Foundation
**What to build:** Layered FastAPI app structure (`models/`, `routers/`, `schemas/`, `services/`, `db/`) with JWT auth middleware and rate limiting. Includes `/health` endpoint with DB status check.
**Blocked by:** 02 (Database Schema & Migrations)
**Status:** ready-for-agent
- [ ] Layered FastAPI app structure created (`models/`, `routers/`, `schemas/`, `services/`, `db/`)
- [ ] JWT authentication middleware implemented with token validation
- [ ] Rate limiting middleware configured (per-token limits)
- [ ] `/health` endpoint returns API status and DB connection status
- [ ] `/health/ready` and `/health/live` endpoints implemented
- [ ] OpenAPI docs generated and accessible at `/docs`
- [ ] FastAPI app tested with test client against test database
@@ -0,0 +1,14 @@
# 03a: Layered FastAPI App Structure
**What to build:** FastAPI app with layered module structure (`models/`, `routers/`, `schemas/`, `services/`, `db/`).
**Blocked by:** 02b (Users & Auth Tokens Schema)
**Status:** ready-for-agent
- [ ] Directory structure created (`models/`, `routers/`, `schemas/`, `services/`, `db/`)
- [ ] `main.py` entry point with FastAPI app instance
- [ ] Database module (`db/session.py`, `db/connection.py`) implemented
- [ ] First router (e.g., `routers/health.py`) created with basic endpoints
- [ ] Schemas module initialized with base models (e.g., `schemas/base.py`)
- [ ] Services module initialized with base service class
@@ -0,0 +1,14 @@
# 03b: JWT Authentication Middleware
**What to build:** JWT authentication middleware with token validation, supporting multiple signers and future OAuth.
**Blocked by:** 03a (Layered FastAPI App Structure)
**Status:** ready-for-agent
- [ ] JWT middleware implemented (token extraction, validation, user injection)
- [ ] Token generation function (`create_token(user_id, expires_in)`)
- [ ] Token validation with secret key (configurable via environment)
- [ ] `/auth/login` endpoint implemented (returns JWT token)
- [ ] `/auth/logout` endpoint implemented (marks token as revoked)
- [ ] Test client configured with auth header fixture
@@ -0,0 +1,13 @@
# 03c: Rate Limiting Middleware
**What to build:** Token-based rate limiting middleware in FastAPI, extensible to Redis or Traefik later.
**Blocked by:** 03b (JWT Authentication Middleware)
**Status:** ready-for-agent
- [ ] Rate limiting middleware implemented (per-token limits)
- [ ] Default rate limit configured (e.g., 100 requests/minute per token)
- [ ] Rate limit headers exposed in responses (`X-RateLimit-Limit`, `X-RateLimit-Remaining`)
- [ ] Rate limit exceeded response returns `429 Too Many Requests`
- [ ] Rate limiting tests written (test client simulates multiple requests)
@@ -0,0 +1,14 @@
# 03d: Health Endpoint
**What to build:** `/health` endpoint with DB and object storage dependency checks.
**Blocked by:** 03c (Rate Limiting Middleware)
**Status:** ready-for-agent
- [ ] `/health` endpoint implemented (returns status: `healthy`, `degraded`, `unhealthy`)
- [ ] Database dependency check included (connectivity, query test)
- [ ] Object storage dependency check included (bucket access test)
- [ ] `/health/ready` endpoint implemented (blocks on all dependencies)
- [ ] `/health/live` endpoint implemented (always returns `healthy`)
- [ ] Health check tests written (test client validates response schema)
@@ -0,0 +1,15 @@
# 04: Object Storage Integration
**What to build:** File upload support integrated with Linode Object Storage + NextCloud backup. Includes upload/download/cleanup workflows tested end-to-end.
**Blocked by:** 01 (Infrastructure Setup)
**Status:** ready-for-agent
- [ ] Linode Object Storage SDK integrated (boto3 or equivalent)
- [ ] Upload endpoint accepts files and stores in Linode Object Storage
- [ ] Download endpoint retrieves files from Linode Object Storage
- [ ] NextCloud backup integration: files mirrored to NextCloud after upload
- [ ] File cleanup workflow (e.g., delete orphaned files, retention policy)
- [ ] Object storage operations tested end-to-end (upload → Linode → NextCloud → download)
- [ ] Error handling for storage failures (retry, fallback, alerts)
@@ -0,0 +1,14 @@
# 04a: Linode Object Storage SDK Integration
**What to build:** Linode Object Storage SDK integration for uploads, downloads, and file management.
**Blocked by:** 01a (Linode Infrastructure with Terraform)
**Status:** ready-for-agent
- [ ] Linode Object Storage SDK added (e.g., `boto3` or `linode-api-client`)
- [ ] Object storage client initialized with credentials (configurable via environment)
- [ ] Upload function implemented (`upload_file(bucket, key, data)`)
- [ ] Download function implemented (`download_file(bucket, key)`)
- [ ] Delete function implemented (`delete_file(bucket, key)`)
- [ ] Object storage client tested against staging bucket
@@ -0,0 +1,13 @@
# 04b: File Upload Endpoint
**What to build:** API endpoint for file uploads to Linode Object Storage.
**Blocked by:** 04a (Linode Object Storage SDK Integration)
**Status:** ready-for-agent
- [ ] `/files/upload` endpoint implemented (POST with multipart/form-data)
- [ ] Upload endpoint stores file in Linode Object Storage
- [ ] Upload endpoint returns file metadata (id, url, size, content_type)
- [ ] File upload tests written (test client simulates multipart upload)
- [ ] Error handling for storage failures (retry, fallback, alerts)
@@ -0,0 +1,13 @@
# 04c: File Download Endpoint
**What to build:** API endpoint for file downloads from Linode Object Storage.
**Blocked by:** 04b (File Upload Endpoint)
**Status:** ready-for-agent
- [ ] `/files/{file_id}` endpoint implemented (GET)
- [ ] Download endpoint retrieves file from Linode Object Storage
- [ ] Download endpoint sets appropriate content-type headers
- [ ] Download endpoint returns file stream or presigned URL
- [ ] File download tests written (test client verifies file content matches)
@@ -0,0 +1,13 @@
# 04d: NextCloud Backup Integration
**What to build:** NextCloud backup integration: files mirrored to NextCloud after upload to Linode Object Storage.
**Blocked by:** 04a (Linode Object Storage SDK Integration)
**Status:** ready-for-agent
- [ ] NextCloud API client initialized with credentials
- [ ] Mirror function implemented (`mirror_to_nextcloud(linode_key, nextcloud_key)`)
- [ ] Upload workflow updated: after Linode upload, mirror to NextCloud
- [ ] Error handling for NextCloud failures (retry, fallback, alerts)
- [ ] NextCloud backup tests written (test client verifies file in NextCloud)
@@ -0,0 +1,15 @@
# 05: Observability Setup
**What to build:** JSON structured logging and NTFY alerts for errors/warnings. Logs include context (request ID, user ID); alerts include severity and topic.
**Blocked by:** 03 (FastAPI Application Foundation)
**Status:** ready-for-agent
- [ ] JSON structured logging configured (timestamp, level, message, context)
- [ ] Request ID injected into all log entries
- [ ] User ID included in logs where applicable
- [ ] NTFY integration: API pushes errors/warnings to configurable topics
- [ ] Alert severity levels implemented (info, warning, error, critical)
- [ ] NTFY alerts include context (e.g., "Database connection failures")
- [ ] Logging and alerts tested in staging environment
@@ -0,0 +1,13 @@
# 05a: JSON Structured Logging
**What to build:** JSON structured logging configured with timestamp, level, message, and context fields.
**Blocked by:** 03a (Layered FastAPI App Structure)
**Status:** ready-for-agent
- [ ] Logging configuration set to JSON format
- [ ] Timestamp, level, message fields included in every log entry
- [ ] Context fields (request_id, user_id) injected where applicable
- [ ] FastAPI request lifecycle logs (start, end, error)
- [ ] Structured logging tests written (verify JSON output schema)
@@ -0,0 +1,13 @@
# 05b: Request ID Injection
**What to build:** Request ID injected into all log entries via FastAPI middleware.
**Blocked by:** 05a (JSON Structured Logging)
**Status:** ready-for-agent
- [ ] Request ID middleware implemented (generates UUID per request)
- [ ] Request ID stored in FastAPI request state
- [ ] Request ID included in all log entries within request context
- [ ] Request ID exposed in response headers (`X-Request-ID`)
- [ ] Request ID tests written (verify consistency across log entries)
@@ -0,0 +1,12 @@
# 05c: User ID Logging
**What to build:** User ID included in logs where applicable (authenticated requests).
**Blocked by:** 05b (Request ID Injection)
**Status:** ready-for-agent
- [ ] User ID extracted from JWT token
- [ ] User ID logged in authenticated request context
- [ ] Anonymous users logged with placeholder ID
- [ ] User ID tests written (verify user ID in logs for authenticated requests)
@@ -0,0 +1,13 @@
# 05d: NTFY Alerts Integration
**What to build:** NTFY integration: API pushes errors/warnings to configurable topics.
**Blocked by:** 05c (User ID Logging)
**Status:** ready-for-agent
- [ ] NTFY client initialized with API URL and authentication
- [ ] Alert function implemented (`send_alert(topic, severity, message, context)`)
- [ ] Severity levels implemented (info, warning, error, critical)
- [ ] NTFY alerts sent for common events (DB failures, storage errors)
- [ ] NTFY tests written (verify alert received in NTFY dashboard)
@@ -0,0 +1,15 @@
# 06: Local Development Environment
**What to build:** Docker Compose setup with FastAPI (hot reload), PostgreSQL, and Adminer. Enables local development with full stack.
**Blocked by:** 03 (FastAPI Application Foundation)
**Status:** ready-for-agent
- [ ] Docker Compose file defines FastAPI, PostgreSQL, and Adminer services
- [ ] FastAPI service includes hot reload (e.g., `--reload` flag or volumes)
- [ ] PostgreSQL service configured with persistent volume
- [ ] Adminer accessible at local port (e.g., `localhost:8080`)
- [ ] Environment variables injected into FastAPI service
- [ ] Docker Compose setup tested end-to-end (start → API available → DB queries → Adminer accessible)
- [ ] Hot reload verified (code change triggers API reload without restart)
@@ -0,0 +1,14 @@
# 06a: Docker Compose Configuration
**What to build:** Docker Compose file defining FastAPI, PostgreSQL, and Adminer services.
**Blocked by:** 03a (Layered FastAPI App Structure)
**Status:** ready-for-agent
- [ ] `docker-compose.yml` defined with services: api, postgres, adminer
- [ ] FastAPI service configured with hot reload (volumes, `--reload` flag)
- [ ] PostgreSQL service configured with persistent volume
- [ ] Adminer service configured (port, database connection)
- [ ] Environment variables injected into FastAPI service
- [ ] Docker Compose setup tested (start → API available → DB queries)
@@ -0,0 +1,12 @@
# 06b: Hot Reload Verification
**What to build:** Hot reload verified for FastAPI service in Docker Compose.
**Blocked by:** 06a (Docker Compose Configuration)
**Status:** ready-for-agent
- [ ] FastAPI service configured for hot reload (e.g., `--reload` flag, volume mounts)
- [ ] Code change triggers API reload without restart (verified via log output)
- [ ] API responses reflect code changes after reload
- [ ] Hot reload tested with multiple code changes (schema update, endpoint addition)
@@ -0,0 +1,12 @@
# 06c: Adminer Accessibility
**What to build:** Adminer accessible at local port for database inspection and queries.
**Blocked by:** 06a (Docker Compose Configuration)
**Status:** ready-for-agent
- [ ] Adminer service accessible at `localhost:8080`
- [ ] Adminer connected to PostgreSQL service
- [ ] Database schema visible in Adminer
- [ ] Sample queries executed successfully in Adminer
+15
View File
@@ -0,0 +1,15 @@
# 07: CI/CD Pipeline
**What to build:** Gitea CI/CD workflows for build, test, push, and deploy. Auto-deploys staging on `main` branch; production on tags.
**Blocked by:** 01 (Infrastructure Setup), 05 (Observability Setup)
**Status:** ready-for-agent
- [ ] Gitea CI/CD workflow for build (lint, type-check, test)
- [ ] Gitea CI/CD workflow for push Docker image (buildx, caching)
- [ ] Auto-deploy staging on `main` branch push
- [ ] Auto-deploy production on tags (e.g., `v*`)
- [ ] CI/CD workflows use `act_runner` (Gitea Actions compatible)
- [ ] Deployment workflow includes health check verification
- [ ] CI/CD logs integrated with NTFY alerts (failures reported)
@@ -0,0 +1,13 @@
# 07a: Gitea CI/CD Build Workflow
**What to build:** Gitea CI/CD workflow for build (lint, type-check, test).
**Blocked by:** 01a (Linode Infrastructure with Terraform)
**Status:** ready-for-agent
- [ ] `.gitea/workflows/build.yml` defined
- [ ] Build workflow runs lint (e.g., `ruff`, `mypy`)
- [ ] Build workflow runs tests (pytest)
- [ ] Build workflow outputs test coverage report (optional)
- [ ] Build workflow runs on push to `main` and feature branches
@@ -0,0 +1,13 @@
# 07b: Gitea CI/CD Push Workflow
**What to build:** Gitea CI/CD workflow for pushing Docker image (buildx, caching).
**Blocked by:** 01a (Linode Infrastructure with Terraform)
**Status:** ready-for-agent
- [ ] Push workflow defined (`.gitea/workflows/push.yml`)
- [ ] Docker image built with `buildx` (multi-platform if applicable)
- [ ] Docker caching configured (build cache, layer caching)
- [ ] Image pushed to container registry (Linode Container Registry or Docker Hub)
- [ ] Image tag includes commit SHA and/or branch name
@@ -0,0 +1,13 @@
# 07c: Auto-Deploy Staging on Main
**What to build:** Auto-deploy staging on `main` branch push to Gitea.
**Blocked by:** 07a (Gitea CI/CD Build Workflow), 07b (Gitea CI/CD Push Workflow)
**Status:** ready-for-agent
- [ ] Deployment workflow triggered on push to `main` branch
- [ ] Kubernetes deployment updated with new image tag
- [ ] Rolling update applied (zero-downtime)
- [ ] Health check verification after deployment
- [ ] Rollback capability tested (manual and automatic on failure)
@@ -0,0 +1,13 @@
# 07d: Auto-Deploy Production on Tags
**What to build:** Auto-deploy production on tags (e.g., `v*`) to Gitea.
**Blocked by:** 07a (Gitea CI/CD Build Workflow), 07b (Gitea CI/CD Push Workflow)
**Status:** ready-for-agent
- [ ] Deployment workflow triggered on tags matching `v*`
- [ ] Production Kubernetes deployment updated with new image tag
- [ ] Manual approval step (optional) before production deploy
- [ ] Health check verification after deployment
- [ ] Production deployment tested with sample tag (e.g., `v0.1.0`)
@@ -0,0 +1,15 @@
# 08: Secrets Management
**What to build:** SOPS + age for encrypted secrets in Git. Age keys stored in Vaultwarden. CI/CD uses decrypted secrets during deploy.
**Blocked by:** 01 (Infrastructure Setup)
**Status:** ready-for-agent
- [ ] SOPS configured with age encryption
- [ ] Secrets files created (e.g., `secrets.yaml`) and encrypted
- [ ] Age public/private key pair generated
- [ ] Age public key stored in Vaultwarden
- [ ] CI/CD workflow decrypts secrets during deploy (e.g., `sops decrypt`)
- [ ] Secrets injected into FastAPI and infrastructure (e.g., PostgreSQL credentials, NTFY API key)
- [ ] Secrets rotation tested (new key pair, re-encrypt)
@@ -0,0 +1,13 @@
# 08a: SOPS + Age Configuration
**What to build:** SOPS configured with age encryption for secrets management.
**Blocked by:** 01a (Linode Infrastructure with Terraform)
**Status:** ready-for-agent
- [ ] SOPS installed and configured
- [ ] Age key pair generated (`age-keygen`)
- [ ] SOPS encryption configured (`secrets.yaml` encrypted)
- [ ] First secret added (e.g., `JWT_SECRET`) and encrypted
- [ ] Decryption tested (`sops decrypt secrets.yaml`)
@@ -0,0 +1,12 @@
# 08b: Age Keys in Vaultwarden
**What to build:** Age public/private keys stored in Vaultwarden for secrets management.
**Blocked by:** 08a (SOPS + Age Configuration)
**Status:** ready-for-agent
- [ ] Age public key stored in Vaultwarden (notes field or attachment)
- [ ] Age private key stored in Vaultwarden (notes field or attachment, encrypted)
- [ ] Vaultwarden accessible from CI/CD (optional: API token)
- [ ] Age keys retrieved from Vaultwarden for decryption in CI/CD
@@ -0,0 +1,12 @@
# 08c: CI/CD Secrets Injection
**What to build:** CI/CD workflow decrypts secrets and injects into FastAPI and infrastructure.
**Blocked by:** 08a (SOPS + Age Configuration)
**Status:** ready-for-agent
- [ ] CI/CD workflow decrypts secrets during deploy (`sops decrypt`)
- [ ] Secrets injected into FastAPI (environment variables)
- [ ] Secrets injected into infrastructure (e.g., PostgreSQL credentials, NTFY API key)
- [ ] Decryption tested in staging deployment
@@ -0,0 +1,15 @@
# 09: Testing Infrastructure
**What to build:** Pytest tests run against separate test database. Tests cover auth endpoints, health endpoint, and object storage workflows.
**Blocked by:** 02 (Database Schema & Migrations), 03 (FastAPI Application Foundation)
**Status:** ready-for-agent
- [ ] Pytest fixtures for `TestClient` configured
- [ ] Test database (`hapi_test`) created and cleaned between test runs
- [ ] Auth endpoint tests (token generation, validation, revocation)
- [ ] Health endpoint tests (DB status, storage status)
- [ ] Object storage workflow tests (upload → Linode → NextCloud → download)
- [ ] Tests run in CI (staging and production deployments)
- [ ] Test coverage reported (optional: thresholds for lines/functions)
@@ -0,0 +1,13 @@
# 09a: Pytest Test Framework Setup
**What to build:** Pytest configured with test database (`hapi_test`), fixtures for `TestClient`.
**Blocked by:** 02b (Users & Auth Tokens Schema), 03a (Layered FastAPI App Structure)
**Status:** ready-for-agent
- [ ] Pytest installed and configured (`pytest.ini` or `pyproject.toml`)
- [ ] Test database (`hapi_test`) created and cleaned between runs
- [ ] Pytest fixtures: `TestClient`, `async_test_client`, `db_session`
- [ ] First test suite created (e.g., `tests/test_health.py`)
- [ ] Tests run locally and in CI
@@ -0,0 +1,13 @@
# 09b: Auth Endpoint Tests
**What to build:** Pytest tests for auth endpoints (token generation, validation, revocation).
**Blocked by:** 09a (Pytest Test Framework Setup)
**Status:** ready-for-agent
- [ ] `/auth/login` tests (valid credentials, invalid credentials, rate limiting)
- [ ] `/auth/logout` tests (valid token, revoked token)
- [ ] Token generation tests (token structure, expiration)
- [ ] Token validation tests (valid token, expired token, revoked token)
- [ ] Auth tests run in CI
@@ -0,0 +1,13 @@
# 09c: Health Endpoint Tests
**What to build:** Pytest tests for health endpoint (DB status, storage status).
**Blocked by:** 09a (Pytest Test Framework Setup)
**Status:** ready-for-agent
- [ ] `/health` tests (status: healthy, degraded, unhealthy)
- [ ] `/health/ready` tests (blocks on DB and storage)
- [ ] `/health/live` tests (always returns healthy)
- [ ] DB dependency test (connectivity, query test)
- [ ] Storage dependency test (bucket access test)
@@ -0,0 +1,13 @@
# 09d: Object Storage Workflow Tests
**What to build:** Pytest tests for object storage workflows (upload → Linode → NextCloud → download).
**Blocked by:** 09a (Pytest Test Framework Setup)
**Status:** ready-for-agent
- [ ] Upload workflow tests (Linode storage, NextCloud mirror)
- [ ] Download workflow tests (Linode retrieval)
- [ ] Delete workflow tests (cleanup, retention policy)
- [ ] Error handling tests (storage failures, retries)
- [ ] End-to-end workflow test (full upload → download cycle)
@@ -0,0 +1,15 @@
# 10: MVP Integration & Validation
**What to build:** End-to-end validation of all MVP components. Verifies UptimeKuma polling `/health`, NTFY alerts, and all user stories are satisfied.
**Blocked by:** 03 (FastAPI Application Foundation), 04 (Object Storage Integration), 05 (Observability Setup), 06 (Local Development Environment), 07 (CI/CD Pipeline), 08 (Secrets Management), 09 (Testing Infrastructure)
**Status:** ready-for-agent
- [ ] UptimeKuma polling `/health` endpoint verified (staging and production)
- [ ] NTFY alerts received for errors/warnings (verified via NTFY dashboard)
- [ ] All user stories from MVP-SPEC validated (e.g., JWT auth, rate limiting, migrations)
- [ ] End-to-end flow tested: developer workflow (push → CI → deploy → health → alerts)
- [ ] Local development environment validated (Docker Compose → FastAPI → Adminer)
- [ ] MVP scope confirmed (WebSockets/GraphQL deferred, not blocking)
- [ ] MVP release notes drafted (optional: published to Gitea release)
@@ -0,0 +1,12 @@
# 10a: UptimeKuma Health Polling
**What to build:** UptimeKuma configured to poll `/health` endpoint (staging and production).
**Blocked by:** 03d (Health Endpoint), 07c (Auto-Deploy Staging on Main), 07d (Auto-Deploy Production on Tags)
**Status:** ready-for-agent
- [ ] UptimeKuma monitor configured for staging `/health`
- [ ] UptimeKuma monitor configured for production `/health`
- [ ] Health check alerts configured (failure threshold, recovery)
- [ ] UptimeKuma dashboard verified (green status for staging/production)
@@ -0,0 +1,12 @@
# 10b: NTFY Alert Verification
**What to build:** NTFY alerts verified for errors/warnings (staging and production).
**Blocked by:** 05d (NTFY Alerts Integration), 07c (Auto-Deploy Staging on Main), 07d (Auto-Deploy Production on Tags)
**Status:** ready-for-agent
- [ ] NTFY alerts received for staging (verified via NTFY dashboard)
- [ ] NTFY alerts received for production (verified via NTFY dashboard)
- [ ] Alert topics verified (e.g., "Database connection failures")
- [ ] Alert severity levels verified (info, warning, error, critical)
@@ -0,0 +1,13 @@
# 10c: MVP User Stories Validation
**What to build:** End-to-end validation of all user stories from MVP-SPEC.
**Blocked by:** 01a (Linode Infrastructure with Terraform), 01b (K8s StatefulSet), 02a (Alembic), 02b (Schema), 03a (FastAPI Structure), 03b (JWT), 03c (Rate Limiting), 03d (Health), 04a (Object Storage SDK), 04b (Upload), 04c (Download), 04d (NextCloud), 05a (Logging), 05b (Request ID), 05c (User ID), 05d (NTFY), 06a (Docker Compose), 06b (Hot Reload), 06c (Adminer), 07a (Build), 07b (Push), 07c (Deploy Staging), 07d (Deploy Prod), 08a (SOPS), 08b (Vaultwarden), 08c (Secrets Injection), 09a (Pytest), 09b (Auth Tests), 09c (Health Tests), 09d (Storage Tests), 10a (UptimeKuma), 10b (NTFY)
**Status:** ready-for-agent
- [ ] All 30 user stories validated (verified via integration tests, manual testing)
- [ ] Staging deployment validated (hot reload, health checks, alerts)
- [ ] Production deployment validated (tag-based deploy, health checks, alerts)
- [ ] Local development validated (Docker Compose → FastAPI → Adminer)
- [ ] MVP scope confirmed (WebSockets/GraphQL deferred, not blocking)
@@ -0,0 +1,13 @@
# 10d: MVP Release Notes & Documentation
**What to build:** MVP release notes drafted and published; documentation updated.
**Blocked by:** 10a (UptimeKuma), 10b (NTFY), 10c (User Stories)
**Status:** ready-for-agent
- [ ] MVP release notes drafted (version, features, breaking changes)
- [ ] Release notes published to Gitea release (`v0.1.0` or similar)
- [ ] API documentation updated (OpenAPI `/docs`, README)
- [ ] Infrastructure documentation updated (Terraform README)
- [ ] Development documentation updated (Docker Compose setup, local dev guide)
+111
View File
@@ -0,0 +1,111 @@
# HAPI MVP Tickets
**Source:** [MVP-SPEC.md](../MVP-SPEC.md)
**Issue Tracker:** Gitea (https://git.bobbypalko.com/bobby/hapi)
**Triage Label:** `ready-for-agent`
---
## Summary
**Total Tickets:** 20 (expanded from 10 MVP tickets into fine-grained vertical slices)
Each ticket is a **tracer-bullet**: cuts vertically through layers (schema, API, tests, infrastructure) and delivers end-to-end behavior.
---
## Tickets
### Infrastructure
| # | Title | Blocked By | Summary |
|---|-------|------------|---------|
| 01a | Linode Infrastructure with Terraform | — | Linode: PostgreSQL, Object Storage, networking |
| 01b | Kubernetes StatefulSet for PostgreSQL | 01a | K8s StatefulSet for production PostgreSQL |
### Database
| # | Title | Blocked By | Summary |
|---|-------|------------|---------|
| 02a | Alembic Migration Framework | 01a | Alembic configured with additive migrations |
| 02b | Users & Auth Tokens Schema | 02a | `users` and `auth_tokens` tables with JWT support |
### FastAPI
| # | Title | Blocked By | Summary |
|---|-------|------------|---------|
| 03a | Layered FastAPI App Structure | 02b | `models/`, `routers/`, `schemas/`, `services/`, `db/` |
| 03b | JWT Authentication Middleware | 03a | Token validation, login/logout, multiple signers |
| 03c | Rate Limiting Middleware | 03b | Per-token rate limits with headers |
| 03d | Health Endpoint | 03c | `/health`, `/health/ready`, `/health/live` |
### Object Storage
| # | Title | Blocked By | Summary |
|---|-------|------------|---------|
| 04a | Linode Object Storage SDK | 01a | Linode SDK for uploads, downloads, deletes |
| 04b | File Upload Endpoint | 04a | `/files/upload` endpoint with multipart support |
| 04c | File Download Endpoint | 04b | `/files/{file_id}` endpoint with streaming |
| 04d | NextCloud Backup Integration | 04a | Files mirrored to NextCloud after upload |
### Observability
| # | Title | Blocked By | Summary |
|---|-------|------------|---------|
| 05a | JSON Structured Logging | 03a | JSON logs with timestamp, level, message, context |
| 05b | Request ID Injection | 05a | UUID per request, logged and in headers |
| 05c | User ID Logging | 05b | User ID from JWT included in logs |
| 05d | NTFY Alerts Integration | 05c | API pushes errors/warnings to NTFY topics |
### Local Dev
| # | Title | Blocked By | Summary |
|---|-------|------------|---------|
| 06a | Docker Compose Configuration | 03a | FastAPI, PostgreSQL, Adminer services |
| 06b | Hot Reload Verification | 06a | Code changes trigger API reload |
| 06c | Adminer Accessibility | 06a | Adminer at `localhost:8080` |
### CI/CD
| # | Title | Blocked By | Summary |
|---|-------|------------|---------|
| 07a | Gitea CI/CD Build Workflow | 01a | Lint, type-check, test |
| 07b | Gitea CI/CD Push Workflow | 01a | Docker buildx, caching, push |
| 07c | Auto-Deploy Staging on Main | 07a, 07b | Push to `main` triggers staging deploy |
| 07d | Auto-Deploy Production on Tags | 07a, 07b | Tags `v*` trigger production deploy |
### Secrets
| # | Title | Blocked By | Summary |
|---|-------|------------|---------|
| 08a | SOPS + Age Configuration | 01a | Encrypted secrets in Git |
| 08b | Age Keys in Vaultwarden | 08a | Public/private keys in Vaultwarden |
| 08c | CI/CD Secrets Injection | 08a | Decrypt secrets, inject into app |
### Testing
| # | Title | Blocked By | Summary |
|---|-------|------------|---------|
| 09a | Pytest Test Framework Setup | 02b, 03a | Test DB, fixtures, `TestClient` |
| 09b | Auth Endpoint Tests | 09a | Login, logout, token generation/validation |
| 09c | Health Endpoint Tests | 09a | DB and storage dependency checks |
| 09d | Object Storage Workflow Tests | 09a | Upload → Linode → NextCloud → download |
### MVP Integration
| # | Title | Blocked By | Summary |
|---|-------|------------|---------|
| 10a | UptimeKuma Health Polling | 03d, 07c, 07d | Staging/production health checks |
| 10b | NTFY Alert Verification | 05d, 07c, 07d | Alerts verified for staging/production |
| 10c | MVP User Stories Validation | All prior | All 30 user stories validated |
| 10d | MVP Release Notes & Docs | 10a, 10b, 10c | Release notes, API docs, dev guide |
---
## Notes
- **Priority order:** Tickets are ordered by dependency (blockers first). Many tickets can run in parallel (e.g., Object Storage, CI/CD, and Secrets can all start after infrastructure).
- **Frontier:** Work on tickets whose blockers are all closed/merged. At start, frontier includes: 01a, 02a, 03a, 04a, 05a, 06a, 07a, 08a, 09a.
- **Wide refactor exceptions:** None in MVP scope; all tickets are tracer-bullet vertical slices.
+17
View File
@@ -0,0 +1,17 @@
# AGENTS.md
This file documents the architecture and domain model of this repository, intended for both human readers and AI agents.
## Agent skills
### Issue tracker
Issues are tracked in the Gitea instance at https://git.bobbypalko.com/bobby/hapi. Uses the `gt` CLI (Gitea's official CLI). Run `gt auth login -h https://git.bobbypalko.com` to authenticate. See `docs/agents/issue-tracker.md`.
### Triage labels
Five canonical triage roles mapped to labels: `needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`. See `docs/agents/triage-labels.md`.
### Domain docs
Single-context layout: `GLOSSARY.md` at repo root and `docs/adr/` for architecture decisions. See `docs/agents/domain.md`.
-13
View File
@@ -1,13 +0,0 @@
## Agent skills
### Issue tracker
Issues live on the self-hosted Gitea at git.bobbypalko.com (`bobby/hapi`), managed with the `gt` CLI. See `docs/agents/issue-tracker.md`.
### Triage labels
Default five-role vocabulary (`needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`). See `docs/agents/triage-labels.md`.
### Domain docs
Single-context: one root `GLOSSARY.md` plus `docs/adr/`. See `docs/agents/domain.md`.
+61 -118
View File
@@ -1,151 +1,94 @@
# hAPI
# HAPI Glossary
hAPI ("home API") is a personal, cloud-hosted API serving one household and its automations: finance, fitness, maintenance, and smart home. Access is restricted to a small, known set of Principals.
## Core Concepts
## Language
### API
The central service exposing HTTP endpoints for clients (humans, bots, frontend). Built with FastAPI, providing REST endpoints, JSON logs, and health checks.
### Access
### Environment
An instance of the API serving requests. **Staging** mirrors production for testing; **Production** serves real users. Each has its own PostgreSQL database.
**Principal**:
Anything that authenticates to hAPI.
_Avoid_: User, account, client
### Migration
A versioned change to the database schema, managed by Alembic. Migrations are additive by default, with destructive changes behind flags.
**Person**:
A human Principal (the Owner, family, friends).
_Avoid_: User, human user, member
### Secret
A sensitive value (password, API key, token) stored encrypted. Managed via SOPS with age encryption, committed to Git alongside code.
**Bot**:
A non-human Principal: a script, automation, or integration such as Home Assistant. Some Bots are built into hAPI itself, such as the scheduler, and never hold a Token.
_Avoid_: Service account, machine user, integration account
### Object Storage
A service for storing files (uploads, assets). We use Linode Object Storage as primary, with NextCloud as a backup destination.
**Owner**:
The single Person with administrative authority over hAPI and every other Principal. That authority covers Principals and the platform, not other Persons' Personal data.
_Avoid_: Admin, root, superuser
### Health Check
An endpoint (`/health`) that reports the API's operational status and dependency health (DB, object storage, etc.).
**Token**:
A Principal's secret credential for the API.
_Avoid_: API key, password
### Alert
A notification sent to NTFY when an error or warning occurs. Includes severity, context, and details for quick triage.
**Scope**:
A domain paired with read or write access: the unit of access that Household grants and Bindings carry.
_Avoid_: Permission, privilege
## Modules
**Binding**:
A Person's consent letting a specific Bot act on that Person's Personal data in one domain, up to a given Scope.
_Avoid_: Delegation, impersonation, link
### Auth Module
Handles user authentication via JWT tokens. Supports token-based rate limiting; extensible for OAuth2 and API keys.
**Household grant**:
The Owner's permission for a specific Bot to act on one domain's Household data, up to a given Scope.
_Avoid_: Permission, role
### Router Module
API endpoints grouped by domain (users, items, etc.). Each router is a self-contained module with its own schemas and service calls.
### Ownership
### Schema Module
Pydantic models defining request/response shapes. Separated from routers to enable reuse and testing.
**Household**:
The single group of Persons that hAPI serves. There is exactly one.
_Avoid_: Family, tenant, organization, group
### Service Module
Business logic separated from HTTP concerns. Services are testable in isolation and called by routers.
**Household member**:
A Person who belongs to the Household. A Person can be a Principal without being a Household member (e.g. a friend).
_Avoid_: Family member, resident
### DB Module
Database connection and utility functions. Includes session management, connection pooling, and migration orchestration.
**Personal data**:
A record owned by one Person, visible only to that Person (and to Bots bound to them).
_Avoid_: Private data, user data
## Infrastructure
**Household data**:
A record owned by the Household, visible to every Household member.
_Avoid_: Shared data, common data
### Kubernetes Cluster
Self-hosted Kubernetes for production and staging deployments. Uses StatefulSet for PostgreSQL.
**Recorded by**:
The Principal that created or last changed a record, distinct from who owns it.
_Avoid_: Author, owner, creator
### Terraform
Infrastructure as code for Linode resources (VMs, PostgreSQL, Object Storage, LCR). State stored in Linode Object Storage with backend configuration.
### Notifications
### Terraform Backend
Storage location for Terraform state files. Configured to use Linode Object Storage for remote state with S3-compatible API.
**Notification**:
A message hAPI keeps for one Person or for the Household about something that needs their attention, delivered through one or more channels such as ntfy. A Notification to a Person is seen only by that Person; one to the Household by every Household member. Platform alerts to the Owner (from CI, delivery, or monitoring) are not Notifications.
_Avoid_: Alert, event, message
### Object Storage Bucket
A container in Linode Object Storage for storing objects (files). We use separate buckets for uploads and Terraform state per environment.
### Smart home
### Firewall Rules
Network access control rules that define which traffic is allowed to reach infrastructure components (API, PostgreSQL, Adminer).
Smart home is hAPI's side of the house: queuing Jobs for Home Assistant, which remains the source of truth for the house's state.
### Gitea CI/CD
Automated workflows for building, testing, and deploying the API. Uses act_runner for GitHub Actions-compatible workflows.
**Job**:
A request, queued in hAPI, for Home Assistant to carry out an action in the house. Jobs are Household data. Domain code, Persons, and Bots can all create them.
_Avoid_: Task, command, message
### Docker Compose
Local development environment with FastAPI, PostgreSQL, and Adminer.
### Finance
## Observability
**Financial Account**:
A bank, credit card, or cash account whose money hAPI tracks. It is owned by a Person or by the Household, and its Transactions share that owner.
_Avoid_: Account (on its own), bank account, wallet
### Structured Logging
JSON-formatted logs for structured querying and analysis. Each log entry includes timestamp, level, message, and context.
**Transaction**:
A single posted movement of money into or out of one Financial Account.
_Avoid_: Entry, charge, payment
### UptimeKuma
Monitoring service that polls `/health` endpoint to track API availability.
**Category**:
A named bucket that Transactions are sorted into, of kind expense, income, or transfer. Household Categories can be used by the Household and by every Household member; Personal Categories only by their Person.
_Avoid_: Tag, label, envelope
### NTFY
Push notification service for alerts. API sends error/warning notifications with configurable topics.
**Budget**:
One owner's zero-based monthly plan: expected income assigned across Categories, then rebalanced during the month with Moves. The Household has one, and each Person may have one.
_Avoid_: Plan, envelope
## Deployment
**Target**:
A Budget's standing amount for one Category over a period (monthly, quarterly, or annual), spread into even monthly shares.
_Avoid_: Goal, limit
### Rollout
Deployment of a new API version to an environment. Uses Kubernetes rolling updates for zero-downtime.
**Allocation**:
What a Budget assigns to one Category in one month: the Target's monthly share, adjusted by Moves.
_Avoid_: Budgeted amount, envelope
### Tagging
Version tags (e.g., `v1.0.0`) trigger production deployments. Staging deploys from `main` branch.
**Move**:
A shift of money from one Category's Allocation to another's within one month of a Budget. It never changes the month's total.
_Avoid_: Transfer (a kind of Category), reallocation
## Future Considerations
**Banked**:
Said of a Category whose Target period is longer than a month. Its unspent Allocations carry forward as a banked balance until the bill draws it down.
_Avoid_: Sinking fund, rollover, savings
### WebSockets
Real-time communication layer for frontend. Not included in MVP; ready for later addition.
**Payee mapping**:
An owner's remembered link from a payee to a Category, learned from manual categorization and applied to newly ingested Transactions.
_Avoid_: Rule, auto-categorization
### GraphQL
Alternative query layer for complex frontend queries. Not included in MVP; REST is sufficient initially.
### Maintenance
Maintenance is the recurring upkeep of the Household's property: the home, its land, its equipment, its vehicles, and its digital systems (such as the hAPI cluster). It is not a to-do list: errands, bills, and one-off chores don't belong.
**Asset**:
A thing the Household keeps up, such as the roof, the furnace, a car, or the hAPI cluster. It may have a meter whose Readings track its use.
_Avoid_: Equipment, item, entity (a Home Assistant term); in Finance, use another word
**Task**:
A recurring piece of upkeep, due either a fixed interval after it was last done or on a calendar rhythm, and optionally also after a set amount of use. Tasks always recur; one-off work is recorded only as a Service.
_Avoid_: Chore, reminder, to-do (and never a Job)
**Service**:
One piece of maintenance work done on a date. It may fulfill a Task, and may concern an Asset.
_Avoid_: Completion, repair, log entry
**Reading**:
An Asset's meter value (an odometer's distance or a runtime counter) taken on a date, used to decide when usage-based Tasks come due.
_Avoid_: Measurement (a Fitness term), metric
### Fitness
**Workout**:
One session of exercise by one Person: an ordered list of Exercises performed, with what was done in each. A run is a Workout with a single cardio Exercise.
_Avoid_: Session, activity, training
**Exercise**:
A named movement that Workouts record, of kind strength, bodyweight, timed, or cardio; the kind decides what is recorded for it. Household Exercises can be used by every Household member; Personal Exercises only by their Person.
_Avoid_: Movement, lift, activity
**Set**:
One bout of a strength, bodyweight, or timed Exercise within a Workout: reps and load, or a duration. A warmup Set doesn't count toward records.
_Avoid_: Rep, round
**Measurement**:
One reading of a Person's body (weight, body fat, or a circumference) at a point in time.
_Avoid_: Metric, stat, body stat
### NextCloud Backup
Secondary storage for uploads, mirroring Linode Object Storage to NextCloud for redundancy.
+226
View File
@@ -0,0 +1,226 @@
# HAPI MVP Spec
## Problem Statement
I'm building a personal API project called **HAPI** (Home API). It needs to be a flexible, extensible foundation for various domains (fitness, finance, maintenance, etc.) that I and my family will use. The system should:
- Start simple but scale as features grow
- Be easy to develop locally and deploy to cloud
- Include observability (logging, alerts, health checks)
- Support automation (cron jobs, webhooks)
- Store files (uploads to Linode Object Storage + NextCloud backup)
- Be testable and maintainable as a solo developer
Currently, the repository is empty (just `.git`), so we're building from scratch.
---
## Solution
Build an MVP with:
1. **Layered FastAPI Application**: Modular structure (`models/`, `routers/`, `schemas/`, `services/`, `db/`) with JWT auth and rate limiting.
2. **Database**: PostgreSQL with Alembic migrations, separate databases for staging and production.
3. **Infrastructure**: Terraform-managed Linode resources (VMs, PostgreSQL, Object Storage, LCR) and Kubernetes StatefulSet for PostgreSQL.
4. **Observability**: JSON structured logging with NTFY alerts, UptimeKuma polling of `/health`.
5. **CI/CD**: Gitea Actions with `act_runner` for build, test, and deploy workflows.
6. **Local Dev**: Docker Compose with FastAPI (hot reload), PostgreSQL, and Adminer.
The seam for testing is at the FastAPI application level—tests cross the HTTP interface to verify behavior end-to-end.
---
## User Stories
1. As a developer, I want a FastAPI application with a layered structure, so that I can keep concerns separated and scale the codebase cleanly.
2. As a developer, I want JWT authentication for API access, so that only authorized users and bots can use the API.
3. As a developer, I want rate limiting on API endpoints, so that I can protect the system from abuse or accidental overuse by bots.
4. As a developer, I want PostgreSQL with migrations, so that schema changes are tracked and reversible.
5. As a developer, I want separate staging and production databases, so that I can test changes safely before releasing to production.
6. As a developer, I want a `/health` endpoint, so that UptimeKuma can monitor API availability.
7. As a developer, I want dependency checks in `/health` (DB, object storage), so that I can see which components are down vs. just the API.
8. As a developer, I want JSON structured logging, so that logs are queryable and analyzable.
9. As a developer, I want NTFY alerts for errors and warnings, so that I get notified in real-time when something breaks.
10. As a developer, I want file upload support (Linode Object Storage + NextCloud backup), so that I can store documents, images, or other assets.
11. As a developer, I want Docker Compose for local development, so that I can run the full stack locally with hot reload.
12. As a developer, I want Adminer for local database access, so that I can inspect and query the database without extra tooling.
13. As a developer, I want Terraform for infrastructure provisioning, so that my cloud resources are versioned and reproducible.
14. As a developer, I want Kubernetes StatefulSet for PostgreSQL, so that I can learn about Kubernetes storage and stateful workloads.
15. As a developer, I want Gitea CI/CD with automated deployment, so that new code is deployed automatically to staging.
16. As a developer, I want staging to deploy automatically on `main` branch, so that I can test changes quickly.
17. As a developer, I want production to deploy on tags, so that I can control releases manually.
18. As a developer, I want SOPS + age for secrets management, so that sensitive values are encrypted in Git.
19. As a developer, I want to store SOPS age keys in Vaultwarden, so that I have one place for all secrets.
20. As a developer, I want Gitea Actions to build Docker images with `buildx`, so that I have full control over the build process.
21. As a developer, I want Pytest tests with a separate test database, so that I can test API endpoints without affecting dev data.
22. As a developer, I want a simple branching strategy (`main` + feature branches), so that I can keep development straightforward.
23. As a developer, I want cron/webhook hooks for automation, so that I can trigger tasks or external actions.
24. As a developer, I want a lean MVP scope, so that I can focus on core functionality first.
25. As a developer, I want breadth-first learning, so that I gain exposure to many tools before diving deep.
26. As a user (myself), I want to access the API from my phone or laptop, so that I can use it on the go.
27. As a user (my wife), I want a simple interface for her dashboard, so that she can view and manage shared data.
28. As a bot developer, I want API keys for bot access, so that each bot has isolated permissions.
29. As a developer, I want to expand the API with new modules (fitness, finance, maintenance), so that I can extend functionality over time.
30. As a developer, I want to add WebSockets later, so that real-time features don't block the MVP.
31. As a developer, I want to add GraphQL later, so that I can evaluate if it's needed for frontend complexity.
32. As a developer, I want to scale infrastructure as needed, so that I can handle more users or data without rework.
---
## Implementation Decisions
### Module Structure
- **Layered Architecture**: Modules are organized by layer (`models/`, `routers/`, `schemas/`, `services/`, `db/`) rather than domain, to keep the codebase simple for a solo developer.
- **FastAPI as the Core Framework**: Chosen for its async support, automatic OpenAPI docs, and ease of testing.
### Database
- **PostgreSQL with Alembic**: Alembic handles migrations with additive-by-default changes; destructive changes are behind flags.
- **Separate Databases for Environments**: Staging and production have separate databases on possibly shared instances to keep data isolated.
- **StatefulSet for Production**: Kubernetes StatefulSet for PostgreSQL provides learnable infrastructure with persistent storage.
### Authentication
- **JWT Tokens**: Simple token-based auth with a secret key (stored in Vaultwarden). Designed to support multiple signers or OAuth later.
- **Token-Based Rate Limiting**: Per-token limits in FastAPI middleware; extensible to Redis or Traefik later.
### Observability
- **JSON Structured Logging**: Logs include timestamp, level, message, and context (e.g., request ID, user ID).
- **NTFY Alerts**: API pushes errors/warnings to NTFY with severity and topic (e.g., "Database connection failures").
- **Health Endpoint**: `/health` checks DB and object storage; `/health/ready` and `/health/live` added later if needed.
### File Storage
- **Linode Object Storage Primary**: S3-compatible for uploads; integrated via Python SDK.
- **NextCloud Backup**: Secondary storage for uploads, mirrored from Linode for redundancy.
### CI/CD
- **Gitea + act_runner**: Uses GitHub Actions-compatible workflows for build, test, push, and deploy.
- **Auto-Deploy Staging**: On `main` branch push; manual/tag-triggered for production.
- **Docker buildx**: Full control over image builds with caching and multi-platform support.
### Testing
- **Pytest with Separate Test DB**: Tests run against `hapi_test` database to avoid affecting dev data.
- **Test Through HTTP Interface**: Tests call API endpoints (not internal functions) to verify real-world behavior.
### Secrets Management
- **SOPS + age**: Encrypted files in Git; age keys stored in Vaultwarden.
### Future-Ready
- **WebSockets Later**: Ready for future frontend; not included in MVP.
- **GraphQL Optional**: REST-only for now; GraphQL can be added as a separate module.
---
## Testing Decisions
### What Makes a Good Test
- Tests verify **external behavior** (HTTP responses, side effects) not implementation details (e.g., which service method was called).
- Tests cover **edge cases** (auth failures, DB down, storage errors) and **happy paths**.
- Tests are **fast** (in-memory DB or test fixtures where possible) and **isolated** (test DB per test run).
### Modules to Test
- **API Endpoints**: Pytest fixtures for `TestClient`; test all routers.
- **Auth Module**: Token generation, validation, and revocation.
- **Health Endpoint**: DB and storage dependency checks.
- **Logging**: JSON output format and context fields.
- **Object Storage**: Upload/download/cleanup workflows.
### Prior Art
- FastAPI's own testing guide (test client, fixtures).
- Alembic's migration testing patterns.
- NTFY API for alert payload testing.
---
## Out of Scope
- **WebSockets**: Real-time features for frontend; added later.
- **GraphQL Layer**: Optional alternative to REST; added if frontend complexity grows.
- **OAuth2 Providers**: Auth is JWT-only for MVP; OAuth can be added later.
- **Advanced PostgreSQL Features**: TimescaleDB, PostGIS, etc.; added as needed.
- **Multi-Region Deployment**: Single-region for MVP; scaling out later.
- **Advanced Monitoring**: Prometheus/Grafana for metrics; NTFY/structured logs suffice for MVP.
- **CI/CD Advanced Features**: Automated changelog generation, release notes; simple deploy for MVP.
---
## Further Notes
- **Learning Focus**: The design prioritizes breadth-first learning (Terraform, Kubernetes, SOPS, etc.) while keeping the MVP lean.
- **Cost Flexibility**: Since cloud costs aren't a concern, we favor robust setups (separate DBs, object storage redundancy) over minimal cost.
- **Extensibility**: Modules are designed to be added incrementally (fitness, finance, maintenance) without refactoring.
- **Tooling Choices**: Tools are selected for learning value (e.g., StatefulSet for PostgreSQL over managed DBs) and ease of use (SOPS over HashiCorp Vault for secrets).
-11
View File
@@ -1,11 +0,0 @@
starting fresh yo
## Development
The only tool needed outside the project is [uv](https://docs.astral.sh/uv/). Everything else is a dev dependency in the project venv:
```sh
uv sync # create .venv with all dev tools
uv run just lint # Ruff, pyright strict
uv run just test # pytest
```
+59
View File
@@ -0,0 +1,59 @@
# ADR Tools Configuration
## Directory
adr-dir = docs/adr
## Template
adr-template = """
# ADR-{{counter}}: {{title}}
## Context
{{context}}
## Decision
{{decision}}
## Status
{{status}}
## Consequences
{{consequences}}
## References
{{references}}
"""
## Author
adr-author = "bobby"
## Date Format
adr-date-format = "2006-01-02"
## Prefix
adr-prefix = "adr-"
## Suffix
adr-suffix = ".md"
## Template Directory
adr-template-dir = docs/adr/templates
## New Directory
adr-new-dir = docs/adr
## View Command
adr-view-command = "gt view"
## View URL Format
adr-view-url-format = "https://git.bobbypalko.com/bobby/hapi/blob/main/{{path}}"
## Edit Command
adr-edit-command = "gt edit"
## Edit URL Format
adr-edit-url-format = "https://git.bobbypalko.com/bobby/hapi/edit/main/{{path}}"
-13
View File
@@ -1,13 +0,0 @@
# Every record is owned by a Person or by the Household
hAPI serves exactly one Household, so there is no multi-tenancy. Every record is either **Personal data**, owned by one Person and visible only to them, or **Household data**, owned by the Household and visible to every Household member on equal terms. Each record type declares which kind it is: fitness is personal, home maintenance and smart home are household, and finance has both. We chose this over per-record sharing (which needs sharing lists and revocation) and over "everything household" (which gives no privacy for personal finances). Anything that needs to be shared is modelled as Household data.
## Consequences
- **The Owner has no special read access to Personal data.** Owner authority covers Principals and the platform only. Bots reach Personal data only through a **Binding** that the bound Person grants and can revoke. The Owner cannot grant one on another Person's behalf.
- Every record carries its owner plus **Recorded by**: the Principal that created it and the one that last changed it. Principals are deactivated, never hard-deleted, so Recorded by never dangles.
- Ownership is fixed when a record is created, except that a Person may move their own Personal record to the Household (one way only).
- **Finance exception:** Financial Accounts and their Transactions never move. To bring an account into the Household, the Personal Financial Account stops tracking at a date and a new Household one starts tracking from it, so spending history stays with the owner who spent it. Finance Categories can still be promoted.
- When a Person is removed, their Personal data is exported and then explicitly deleted. Household data they recorded stays with the Household.
- Persons who are not Household members (e.g. friends) see only their own Personal data.
- Not in v1: roles within the Household, sharing outside the Household, and guest access to Household data.
@@ -0,0 +1,136 @@
# ADR-0001: Linode Infrastructure with Terraform
## Context
We need to provision infrastructure on Linode for the HAPI project. This includes PostgreSQL database instances for staging and production, Object Storage buckets for uploads and Terraform state, and networking with firewall rules for API, PostgreSQL, and Adminer access.
Previously, infrastructure was provisioned manually via Linode dashboard CLI or planned for future setup. With HAPI MVP scope including infrastructure as a core component, we need a repeatable, version-controlled approach.
### Options Considered
1. **Manual provisioning** - Use Linode dashboard/CLI directly
- Pros: Quick to get started, no tooling overhead
- Cons: Not repeatable, hard to track changes, difficult to reproduce
2. **Terraform** - Infrastructure as Code with Linode provider
- Pros: Declarative, state management, reusable modules, multi-environment support
- Cons: Learning curve, state file management
3. **Ansible** - Configuration management focused on VMs
- Pros: Powerful for configuration, good for stateful workloads
- Cons: More complex for infrastructure provisioning, less Linode-native
## Decision
We chose **Terraform** because:
1. **Declarative infrastructure** - Clear, versionable infrastructure definitions
2. **Built-in state management** - Tracks resource state with remote backend support
3. **Linode provider maturity** - Well-maintained official provider with good coverage
4. **Modularity** - Resources naturally organize into logical modules (postgres, storage, network)
5. **CI/CD ready** - Terraform workflows integrate cleanly with Gitea Actions
## Status
**Accepted** - Implementation complete.
## Implementation
### Directory Structure
```
infra/
├── backend/ # Terraform state backend configuration
├── postgres/ # PostgreSQL database instances
├── storage/ # Object Storage buckets
├── network/ # Firewall rules
├── main.tf # Main orchestration file
├── providers.tf # Provider configurations
├── variables.tf # Common variables
├── outputs.tf # Common outputs
└── README.md # Infrastructure documentation
```
### Module Details
#### Backend (`infra/backend/`)
- Terraform state stored in Linode Object Storage
- S3-compatible API for state access
- Environment-specific state buckets
- Provides backend configuration for main Terraform
#### PostgreSQL (`infra/postgres/`)
- LKE (Linode Kubernetes Engine) clusters for staging and production
- Configurable pool sizes (10 for staging, 25 for production)
- Separate database names (`hapi_staging`, `hapi_production`)
- Random password generation for database access
#### Object Storage (`infra/storage/`)
- Upload buckets for staging and production
- Terraform state buckets for each environment
- S3-compatible API configuration
- Bucket policies for access control
#### Networking (`infra/network/`)
- Firewall with rules for:
- API: port 8000 (from anywhere)
- PostgreSQL: port 5432 (internal networks)
- Adminer: port 8080 (from anywhere)
- Inbound and outbound rules
- Environment-specific firewall labels
### Outputs
All modules export standardized outputs:
- **PostgreSQL**: endpoint, port, database, username, password, pool_size
- **Object Storage**: endpoint, access_key, secret_key, bucket names
- **Firewall**: rules configuration, firewall ID and label
- **Terraform Backend**: bucket, key, region, endpoint configuration
### Configuration
Environment variables are used for credentials (not committed to Git):
- `LINODE_TOKEN`: Linode API token
- `OBJECT_STORAGE_ACCESS_KEY`: Object Storage access key
- `OBJECT_STORAGE_SECRET_KEY`: Object Storage secret key
### Makefile Commands
```bash
make init # Initialize Terraform
make plan # Generate plan
make apply # Apply changes (ENV=staging|production)
make destroy # Destroy infrastructure
make output # Show outputs
```
## Consequences
### Positive
- **Reproducibility** - Infrastructure can be recreated from code
- **Version control** - Infrastructure changes tracked in Git
- **CI/CD ready** - Terraform workflows integrate with Gitea Actions
- **Multi-environment support** - Clean separation between staging and production
- **Documentation** - Outputs and README provide clear understanding
### Negative
- **Learning curve** - Team needs to learn Terraform syntax and concepts
- **State management** - Requires careful state file handling
- **Provider dependencies** - Linode provider updates may be needed
## Next Steps
1. Complete Terraform implementation
2. Set up CI/CD pipeline for infrastructure changes
3. Document deployment process
4. Create runbooks for common operations (scaling, backups, troubleshooting)
5. Set up monitoring for infrastructure resources
## References
- [Issue 1: Linode Infrastructure with Terraform](../../issues/1)
- [Linode Terraform Provider](https://registry.terraform.io/providers/linode/linode/latest/docs)
- [Terraform Best Practices](https://developer.hashicorp.com/terraform/tutorials/best-practices)
- [HAPI MVP Spec](../../MVP-SPEC.md)
-18
View File
@@ -1,18 +0,0 @@
# One public surface, gated only by hAPI's own auth; no tunnel to home
Persons must reach hAPI from anywhere without a VPN. The home network sits behind ISP CGNAT with a changing IP, so the cluster can never open a connection into the home, and the home IP can't be allowlisted. A CGNAT address is shared with other customers, so allowlisting it would also let them in. We therefore expose **one public surface**, the hAPI API over HTTPS on `:443`, used by Persons and Bots alike, with **hAPI's own authentication as the only gate**. Bots get no separate network path: no VPN, no separate port, no client certificates. Writing a cron job then takes nothing more than `curl` with a token. We chose this over a tunnel for Bots (Tailscale or WireGuard, with a client on every Bot) and over a client-cert-gated Bot port. Both were workable but added setup to every Bot. Client certs stay available as later hardening.
## Considered Options
- **A tunnel for every Bot (Tailscale + k8s operator, or plain WireGuard).** Works behind CGNAT because home dials out. Rejected: every Bot needs a client, and the Tailscale operator can't be used with Tailnet Lock, which leaves Tailscale's control plane trusted.
- **Client-cert-gated Bot endpoints.** Gateway API enforces client certs per port, not per hostname, so this needs its own port. Home Assistant can present a client cert only over MQTT. Rejected as v1 friction.
- **An identity-aware proxy or CDN in front (e.g. Cloudflare).** Rejected: we want no third party in the public request path, meaning no browser challenge pages and no outage when a vendor has one.
## Consequences
- **Traffic between the cluster and home only ever starts from home.** hAPI never calls into the house. The job bridge to Home Assistant must be one that HA connects out to (pulls or holds open).
- **Every public endpoint is TLS-only and requires per-Principal auth.** No anonymous endpoints, including health: Uptime Kuma is a Bot with a health-only scope. `:80` is closed, so certificates use ACME DNS-01. A broker, if the bridge needs one, may be public under the same rule.
- **Bot credentials carry the security a network gate would have.** Each is per-Bot, scoped, individually revocable, and stored hashed. A long-lived JWT that can't be revoked is not acceptable as a Bot credential.
- **Owner administration has no HTTP route.** Creating Principals, issuing and revoking credentials, and Household grants are done through an admin CLI inside the hAPI pod, reached only through cluster management access. Persons' own actions, including granting Bindings, stay on the public API.
- **Cluster and node management APIs (Kubernetes, Talos) are never public.** They're reachable only over a management-only Tailscale tailnet (node extension plus the Owner's devices) with Tailnet Lock on. This tailnet is not in the public request path, so a Tailscale outage never takes hAPI down. Break-glass: the Linode LISH console, or a temporary firewall rule for the Owner's current IP.
- **Never public:** the database, metrics, detailed health, and any internal service.
@@ -1,18 +0,0 @@
# Talos on Linode with one control-plane node, Cilium, and OpenTofu
The hAPI cluster runs **Talos Linux** on Linode compute in `us-iad`: **one control-plane node and two workers**, all `g6-standard-2`, provisioned with **OpenTofu**. Its CNI is **Cilium**, with WireGuard encrypting traffic between nodes. We chose Talos because it is immutable and managed only through an authenticated API, with no shell or SSH. That fits a security-first, one-operator cluster better than RKE2 (CIS-hardened, but a general-purpose OS to patch), k3s (defaults favor convenience) or kubeadm (most learning, weakest defaults). A single control-plane node keeps cost and moving parts proportionate to a small load. Postgres is a managed service outside the cluster, so etcd holds no hAPI data, and the cluster can be rebuilt from code.
## Considered Options
- **Three control-plane nodes (HA etcd).** Rejected for v1 as oversized. With dedicated workers it costs about $48/mo more. Running workloads on the control plane instead would mix them with etcd. Moving to three is an additive Talos change.
- **A NodeBalancer in front of the Kubernetes and Talos APIs**, as the Talos Linode guide describes. Rejected: ADR-0002 keeps those APIs off the internet. The cluster endpoint is the control-plane node's tailnet name instead.
- **VPC-only nodes behind a NAT gateway.** Rejected for now: Tailscale would fall back to DERP relays, and the NAT gateway is newer. Nodes have public IPv4 with a firewall that denies all inbound traffic except Tailscale's UDP port.
- **Terraform.** OpenTofu is chosen for its open licence and its client-side state encryption. The state holds Talos machine secrets.
## Consequences
- **Losing the control-plane node means rebuilding it from code.** Workloads keep serving in the meantime, but the cluster can't be changed until it is back.
- **No SSH, ever.** All node access goes through `talosctl` over the management tailnet. Break-glass is the Linode LISH console.
- **Every node joins the management tailnet** with a pre-signed auth key, so Tailnet Lock stays on.
- **OpenTofu and Talos install only Cilium and the Linode CCM.** These are what nodes need to become Ready. Everything else arrives through delivery.
- **Disks are encrypted at rest** with Talos LUKS on STATE and EPHEMERAL, in addition to Talos's default encryption of Secrets in etcd.
-33
View File
@@ -1,33 +0,0 @@
# Database access: VPC-only, two roles, Personal data isolated by row-level security
hAPI uses a **Linode Managed PostgreSQL 18** cluster (Shared 2 GB, 1 node) attached to the cluster's VPC with `public_access = false`, and its allowlist holds only the VPC subnet. Clients connect with `sslmode=verify-full` and scram-sha-256 passwords. Two roles share the `hapi` database. **`hapi_migrator`** owns every schema and table and runs `hapi migrate`. **`hapi_app`** has DML only; the running app and the admin CLI both connect as it. Personal-data tables have `ENABLE ROW LEVEL SECURITY` (not `FORCE`), with policies keyed on a per-transaction `SET LOCAL hapi.principal_id`, so a forgotten `WHERE` in a handler returns nothing instead of leaking another Person's data. `hapi_app` never owns a table and has no `BYPASSRLS`. That keeps ADR-0001's rule (not even the Owner reads others' Personal data) in the database for everything the app does. We accept that VPC for Managed Databases is still labelled beta, because ADR-0002 rules out a public database endpoint. It was verified working in `us-iad`.
**Amended by ADR-0005:** RLS also covers **Household data** tables. Their policies allow an active Household member or a Bot with a Household grant for that domain. Personal-data policies also allow a Bot that holds an active Binding from the record's owner. In both cases `USING` checks the read Scope and `WITH CHECK` checks the write Scope. `hapi.principal_id` is always the authenticated Principal, Person or Bot. The CI isolation check below covers every owned table, Personal or Household.
## Considered Options
- **Public endpoint with a node-IP allowlist.** Rejected: it contradicts ADR-0002 ("Never public: the database").
- **App-only filtering (no RLS).** Rejected: one missed filter becomes a data leak. Wrong-Principal tests stay mandatory on top of RLS.
- **`FORCE ROW LEVEL SECURITY`.** Rejected: it binds the owner `hapi_migrator` too, so every data migration and break-glass session would need `ALTER TABLE … NO FORCE`. The only thing it adds is protection against the migrator, which is the operator, and the operator is outside RLS's guarantee anyway.
- **Signed principal context, or one role per Person.** Rejected as protection against leaked `hapi_app` credentials. A signing key would live in the same pod as the password. Per-Person roles would all have to be grantable to `hapi_app`, so leaked credentials could switch to any of them.
- **A single role, or one role per domain schema.** One role lets the app run DDL and own tables, and owners bypass RLS. Per-domain roles add no isolation, because the monolith process would hold all of them anyway.
- **A `BYPASSRLS` role for admin tooling.** Rejected: the Owner has no read access to Personal data, so nothing in the request path or admin CLI needs one.
- **Managed or self-hosted PgBouncer.** Not needed at this load (see the connection budget below).
- **PostgreSQL 19.** Newly offered on the platform. We stay on 18, which all our verification ran on and which nothing in v1 outgrows. Revisit at the first major-upgrade window.
## Consequences
- **What RLS protects against:** app bugs only. Anyone holding `hapi_app` credentials can set any `hapi.principal_id`. Leaked credentials are contained by the network, because the VPC-only allowlist (verified as the enforcing control) limits use to the cluster and VPC. Whoever holds `akmadmin` (which has `BYPASSRLS`), `hapi_migrator` or the OpenTofu state can read everything. Owner non-access is enforced by policy and audit, not cryptography. Per-Person encryption is out of scope for v1.
- **Policies treat an unset principal as no principal.** After a transaction, the setting reads `''`, not NULL, so policies use `nullif(current_setting('hapi.principal_id', true), '')`.
- **CI enforces isolation:** every owner-mixin table must have `relrowsecurity` set and be owned by `hapi_migrator`, never `hapi_app`. Tests and local dev use the same bootstrap and connect as `hapi_app`.
- **`akmadmin` is never in the cluster.** An idempotent `hapi db bootstrap` admin CLI command creates the roles and the database. The Owner runs it in a pod and pastes in the `akmadmin` password at run time. It does the following:
1. Waits until the private hostname resolves (about 60 s after the cluster reports ready).
2. Creates `hapi_migrator` and `hapi_app`.
3. Runs `CREATE DATABASE hapi OWNER hapi_migrator`.
4. Runs `SET ROLE hapi_migrator` for the database-level `REVOKE`/`GRANT`s and `ALTER DEFAULT PRIVILEGES`. Run as `akmadmin`, these silently do nothing.
- **Cross-Person work runs per Person.** Purging a removed Person's data, or a job such as reminders, sets `hapi.principal_id` to each Person in turn.
- **Data repairs** normally ship as reviewed Alembic data migrations run as `hapi_migrator`, targeting rows by id or condition without printing them.
- **Break-glass goes through `hapi db breakglass --reason "…"`.** It opens `psql` as `hapi_migrator` from a pod and emits structured audit events to hAPI's centralized logs: start, end, reason, and every statement. Query results are never logged. The platform offers no statement logging or pgaudit, so this is the only audit trail.
- **Connection budget:** the plan allows 50 connections. That leaves about 46 usable after 3 reserved superuser slots and one platform backend. Each app pod holds at most 10 (`pool_size=5`, `max_overflow=5`), and the admin CLI holds 1–2. The rule is: (maximum concurrent app pods, including rollout surge) × 10, plus about 6 for migrate, CLI, break-glass and bootstrap, must be ≤ 46. That caps app pods at 4. Any future worker process counts against the same budget. **Amended by ADR-0012:** housekeeping CronJobs use a pool of 1, so the rule is app pods (with surge) × 10 + concurrently runnable CronJobs × 1 + ~6 ≤ 46.
- **Plan changes are restores.** An in-place resize stalled during verification. Changing size or node count is done as a restore-to-new-cluster, with the same runbook as disaster recovery: fork, wait for DNS, `hapi db bootstrap`, repoint the app. Single-node maintenance windows (pinned to a quiet slot) cause short downtime, covered by 14-day point-in-time recovery. **Amended by ADR-0014:** our own daily dumps (an Object Lock bucket, pulled off-account) cover damage found after 14 days and account loss, and `hapi db bootstrap` also creates a read-only `BYPASSRLS` `hapi_backup` role for `hapi db backup`.
- Passwords are rotated manually with a runbook. `password_encryption` is set explicitly to `scram-sha-256`.
@@ -1,26 +0,0 @@
# Opaque per-Principal tokens; authorization by ownership, grants and row-level security
In v1, every Principal (Person or Bot) authenticates with a bearer **Token**. There is no identity provider and no interactive login, because there's no frontend: Persons use scripts, HTTP clients and Shortcuts, just as Bots do. A Token is opaque: `hapi_<public-id>_<secret>`, where the secret has 256 bits of entropy. hAPI stores only a SHA-256 of the secret and looks the Token up in Postgres on every request, so revoking a Token takes effect immediately, as ADR-0002 requires. Authorization keys off the **Principal**, never the credential. Persons are authorized purely by ownership (ADR-0001). Bots have no access until they're given a **Scope** (`<domain>:read` or `<domain>:write`, where write implies read, plus the special `health` scope). A Bot gets Scopes through **Household grants**, which the Owner gives through the admin CLI, and **Bindings**, which a Person gives through the API, one domain at a time. Enforcement sits in row-level security as well as in the app, so a forgotten check fails closed.
## Considered Options
- **OIDC with a self-hosted IdP** (Authelia, Kanidm, Pocket ID). Rejected for v1. It's another public-facing service to run and secure, every request would depend on it, and refresh flows are painful for curl cron jobs.
- **Passkeys served by hAPI.** These need a web origin and a login page, which amounts to a frontend. Deferred until a frontend exists (see Consequences).
- **Short-lived JWTs signed by hAPI, plus refresh tokens.** Rejected. Revocation lags by up to a token lifetime, there's a signing key to manage, and every client needs refresh logic. At our load, one indexed lookup per request costs nothing, and it uses the request's own pooled connection.
- **mTLS client certificates.** Already rejected in ADR-0002.
- **Per-resource or per-record-type Scopes** (e.g. `finance.transactions:write`). Rejected as premature. A domain Scope can later be split into finer ones without breaking anything.
- **Choosing whose Personal data a Bot means with a request header** (`Hapi-Acting-For`). Rejected because the same URI would then name different resources depending on the header.
- **Nested owner paths** (`/persons/{id}/workouts`, `/household/transactions`). Rejected. ADR-0001 lets a record move from Personal to Household, and nesting would change its URI when it does. Listing everything a Bot may see would also take one call per Person.
- **Owner powers on the public API** (e.g. revoking a Bot from a phone). Rejected. If the Owner's Token leaks, it should do no more harm than any other Person's.
## Consequences
- **Resources are flat and ownership is an attribute.** Each record has exactly one URI, `/v1/<domain>/<things>/{id}`, and keeps it when it moves to the Household. Every record exposes `owner` (a Person id or `household`) and `recorded_by`. Lists accept `?owner=me|household|<person-id>`, and without a filter they return everything the caller may see. When creating a record, `owner` is required for a Bot writing Personal data. For a Person it defaults to themselves on Personal types and to the Household on Household types.
- **`hapi.principal_id` is always the authenticated Principal.** Personal-data policies allow rows where the owner is the principal, **or** the owner has an active Binding to the principal for that domain. Household-data policies (amending ADR-0004) allow an active Household member **or** a Bot with a Household grant for that domain. `USING` checks the read Scope and `WITH CHECK` checks the write Scope. Routes also declare `require_scope(...)`, so a caller missing a Scope gets a clean `403` and the Scope appears in the OpenAPI export. Recorded by is simply the principal.
- **Responses:** any missing, malformed, unknown, expired or revoked Token gets the same `401` with `WWW-Authenticate: Bearer`. A missing Scope or Binding returns `403`. A record the caller can't see returns `404`. Tests cover wrong Person, wrong Bot, a revoked Binding and a read-only Scope attempting a write.
- **Token lifecycle:** Tokens expire after 365 days by default, with the lifetime configurable when issued. `--no-expiry` is allowed only for Bots, and the CLI lists such Tokens in a warning. A Principal may hold several live Tokens, so rotation goes issue, swap, revoke. `last_used_at` is written at most about once an hour, and `hapi token list` flags Tokens that are near expiry or unused for 90 days.
- **Issuing stays in the CLI** (ADR-0002). On the public API, a Person may list and revoke their own Tokens (but not mint them), grant, list, change and revoke their Bindings, and list Bots (id, name, description). The Owner cannot create a Binding on a Person's behalf.
- **Deactivation** revokes all of a Principal's Tokens and makes its Household grants and Bindings inert, whichever side of a Binding it was on. Household membership is a flag the Owner sets in the CLI. The Owner can't be deactivated; ownership is transferred through a CLI command that needs the current Owner's confirmation.
- **Auth is audited in the logs.** Every auth decision is logged as a structured event with the principal id, the credential's public id, the outcome and the reason. Changes to Tokens, grants and Bindings are logged as audit events. Secrets are never logged. There's no app-level rate limiting, since 256-bit secrets can't be brute-forced. Any per-IP limits belong at the Gateway.
- **The Token prefix is deliberate.** It lets secret scanners and push protection recognise a leaked Token.
- **A future frontend adds a credential kind and changes nothing else.** Credentials carry a `kind`, which is `api_token` in v1. A browser login (passkeys or OIDC) would add, say, a `session` kind that resolves to the same Person. Scopes, Bindings and RLS stay as they are. Cookie, CSRF and CORS handling arrive with that frontend.
@@ -1,20 +0,0 @@
# Home Assistant polls hAPI for Jobs that name allowlisted HA scripts
hAPI needs Home Assistant to carry out actions in the house: things queued while a Person is away, or one-offs not worth configuring in HA. Traffic between the cluster and home only ever starts from home (ADR-0002), so HA has to come to hAPI. A **Job** is Household data (ADR-0001), created by domain code, Persons, or Bots through `/v1/smart_home/jobs`. **HA polls** `GET /v1/smart_home/jobs/next` every 15–30 s with its built-in `rest` sensor. An HA automation runs the Job and reports back through `rest_command` to `POST /v1/smart_home/jobs/{id}/result`. A Job never names an arbitrary HA action. It names an **HA script** (`hapi_*`) plus variables, and HA only runs `script.hapi_*`, so HA decides what hAPI can ever trigger. Jobs tolerate about 30 s of latency: anything interactive and real-time goes from the Person straight to HA's own app, not through hAPI. This bridge carries only Jobs and their results. HA sends other data to ordinary domain endpoints as a Bot.
## Considered Options
- **MQTT through a Mosquitto broker in the cluster.** HA's supported message bus gives sub-second delivery. Rejected for v1: it means running and exposing a broker, plus an auth bridge so the broker understands hAPI Tokens, plus a single publisher process inside hAPI. HA's client always uses a clean session, so durability would live in hAPI regardless. MQTT remains the upgrade path if real-time Jobs ever matter.
- **RabbitMQ / AMQP.** HA has no AMQP integration and explicitly doesn't support RabbitMQ's MQTT plugin.
- **A custom HA integration** (long-poll or SSE against hAPI). This has the cleanest semantics, but it's Python to keep working through every HA release. Since 2026.11 it also can't be installed through the Marketplace from a private Gitea repo.
- **hAPI calling HA's REST or WebSocket API.** Ruled out by ADR-0002, because traffic only starts from home.
- **Jobs naming arbitrary HA actions** (e.g. `lock.unlock`). Rejected: any holder of `smart_home:write` could do anything HA can do.
## Consequences
- **The bridge needs no new infrastructure or credentials.** HA is the `home-assistant` Bot with a Household grant of `smart_home:write`, and its Token lives in HA's `secrets.yaml`. There's no `jobs` Scope: `smart_home:write` both creates Jobs and consumes them, and ADR-0005 allows splitting the Scope later.
- **Delivery is at-least-once, FIFO by `not_before` (or creation time).** `next` hands out the oldest eligible Job and hides it for a 2-minute lease. After 3 deliveries with no result, the Job becomes `failed` (`no_result`), so one broken Job can't stall the queue. HA scripts must be idempotent: set states, don't toggle. After each result, HA calls `homeassistant.update_entity` on the sensor so a backlog drains without waiting for the next poll.
- **Job lifecycle:** `pending → succeeded | failed | expired | cancelled`. A Job may carry an optional `not_before`. `expires_at` defaults to 1 h after `not_before` (or after creation), and an expired Job is never delivered. A result is `{status, error?, response?}`, where `response` holds the script's response variables. The first result wins, and a later one gets `409`. Any Household member, or any Bot with `smart_home:write`, can cancel a `pending` Job. Finished Jobs are immutable and are kept for 90 days. `hapi jobs sweep`, a CronJob every 15 min (ADR-0012), removes them and marks pending Jobs past `expires_at` as `expired`; until it does, reads derive `expired` from `expires_at`.
- **hAPI checks only the shape of a Job, not what it does.** Script names must match `hapi_[a-z0-9_]+`, and variables are capped at 16 KB. hAPI keeps no catalogue of HA scripts. HA rejects unknown scripts, which comes back as a failed result.
- **HA-side configuration** is a reference package in this repo (`integrations/home-assistant/hapi_jobs.yaml`: rest sensor, automation, rest_command), copied into HA by hand. The `hapi_*` scripts themselves live in a separate HA configuration repo.
- **hAPI records HA's last poll**, so a stalled bridge can be detected. Turning that into an alert is part of observability.
-24
View File
@@ -1,24 +0,0 @@
# Flux pulls from git; CI builds images and commits their digest
Every green merge to protected `main` reaches production, with no release tags and no staging. **Gitea Actions** runs CI on a dedicated runner VM. On a PR it runs lint, pyright, import-linter, the testcontainers test suite, the image build, a smoke test, the OpenAPI export, and a Trivy scan that fails on fixable critical or high CVEs. On `main` it also pushes the image to **Gitea's container registry** and commits the new **digest** into `deploy/apps/hapi`. **Flux** in the cluster polls this repo every minute and applies what's committed. The cluster pulls; CI never pushes to it. CI holds no cluster credentials, and the cluster holds no git credentials (the repo is public, so Flux fetches anonymously over HTTPS). Kubernetes and Talos APIs stay reachable only from the management tailnet (ADR-0002), and no CI system ever joins it.
## Considered Options
- **CI push** (`kubectl apply` / `helm upgrade` from a workflow). Rejected: the runner would join the management tailnet with a kubeconfig, so a compromised workflow or dependency would become cluster-admin, and Tailnet Lock would have to trust another node.
- **Argo CD.** Rejected for its web UI, which would need keeping off the internet, and its weight. One operator with `flux`/`kubectl` over the tailnet doesn't need a UI.
- **Flux image automation** writing digest bumps back to git. Rejected: it needs a write deploy key inside the cluster, turning a cluster compromise into a source-code compromise. CI already decides which image runs, so giving CI the write key adds little.
- **A Flux webhook `Receiver`** for instant deploys. Rejected: it's a new public HTTP route without per-Principal auth (ADR-0002). A one-minute poll is fine.
- **A runner on the Gitea host or in the cluster.** Rejected: a job with Docker access on the Gitea host can read every repo and every Actions secret, and the cluster shouldn't run CI workloads.
## Consequences
- **Layout:** `deploy/clusters/prod` (Flux's entry point), `deploy/infrastructure` (`HelmRelease`s for upstream components), `deploy/apps/hapi` (the Kustomize base, including the migrate Job). Flux runs with `prune: true` and drift correction on. The Owner installs Flux once over the tailnet with `flux install` plus a `GitRepository`/`Kustomization`. From then on Flux manages itself from git.
- **Migrations run as a Job in their own Flux Kustomization** (`hapi-migrate`), using `hapi_migrator` credentials (ADR-0004). The Job name carries the image digest, so each release gets a new Job. The app Kustomization `dependsOn` it with `wait: true`, so a failed migration stops the rollout and the old pods keep serving. **Migrations must be backward-compatible** (expand, then contract in a later release) because old pods run against the new schema. **Migrations go forward only:** there are no down-migrations.
- **Rollout:** 2 replicas, `maxSurge: 1`, `maxUnavailable: 0`, no HPA, a PodDisruptionBudget with `minAvailable: 1`, and replicas spread across the two workers. That's at most 3 app pods, within ADR-0004's cap of 4.
- **Rollback is `git revert` of the digest bump.** A rollout that never becomes ready stalls, and the old pods keep serving. There's no automated rollback. Break-glass: `flux suspend`, then `kubectl rollout undo`, then bring git back in line.
- **Images are public**, because Gitea package visibility follows the owner. Images must never contain secrets. Deploys reference digests, never mutable tags. Builds are amd64 only.
- **The CI write credential is a deploy key with write access**, stored as an Actions secret and allowlisted past `main`'s branch protection. The build workflow's path filter skips bump commits, so a bump doesn't trigger another build.
- **Renovate runs nightly** on the same runner as its own bot user. It auto-merges only dev-only tooling. Anything that ships (runtime dependencies, base image, charts, Flux, Talos, OpenTofu providers) arrives as a PR the Owner merges.
- **Not delivered through Flux:** the runner VM, Cilium, and the Linode CCM live in OpenTofu under `infra/`, and the Owner runs `tofu apply` over the tailnet. Talos and Kubernetes upgrades are a manual `talosctl` runbook. CI never holds the Tofu state key.
- **Failures notify through ntfy:** a final `if: failure()` step in each workflow, and Flux's notification-controller for failed reconciles and rollouts. Topics and auth: ADR-0013 (`ops` topic, each sender its own publish-only ntfy user).
- **Deferred:** having Flux verify commit signatures, and signing images (cosign) with admission-time verification. Both guard against a compromised Gitea and belong together in cluster hardening.
-33
View File
@@ -1,33 +0,0 @@
# Secrets are SOPS-encrypted in the public repo; Owner roots live in Vaultwarden
Secrets the cluster needs are committed to this **public** repo, encrypted with **SOPS + age**, and Flux's kustomize-controller decrypts them as it applies them. Flux pulls with no git credentials and CI holds no cluster credentials (ADR-0007), so secrets must either ride in git encrypted or be placed by hand. Encrypting them in git keeps the cluster rebuildable from git plus one key, with no extra service to run. The roots of trust (the age key, the OpenTofu state key, the Linode and Object Storage tokens, talosconfig and kubeconfig) never enter the cluster or CI. They live in the Owner's self-hosted **Vaultwarden**.
## Considered Options
- **External Secrets Operator with a store** (Bitwarden Secrets Manager, 1Password, OpenBao). Rejected. It adds a third-party dependency or a service to run, and the cluster still needs its own credential for the store, so the bootstrap problem remains.
- **Sealed Secrets.** Rejected. The ciphertext still sits in git, and the controller's private key is generated in the cluster and has to be backed up, which makes disaster recovery worse than SOPS.
- **Secrets created by hand with `kubectl` over the tailnet.** Rejected. Nothing records what should exist, drift goes unnoticed, and rebuilding the cluster needs a manual step for each secret.
## Consequences
- **The ciphertext is public forever.** Key names and encrypted values can be read by anyone, along with every past version in history. If the age key is ever exposed, **every value it protected is rotated**. Replacing the key alone isn't enough.
- **Layout:** `.sops.yaml` encrypts only `data`/`stringData` in `deploy/**/*.sops.yaml`. The Flux Kustomizations that carry secrets set `decryption.provider: sops`.
- **The age key:** there is one, for prod, generated offline. Its durable copy is in Vaultwarden. During the Flux install runbook, the Owner creates `flux-system/sops-age` from it by hand. OpenTofu never sees it, so it stays out of Tofu state.
- **Secrets reach the app as files, never env vars.** They're mounted read-only under pydantic-settings' `secrets_dir`. Env vars leak through `/proc`, into child processes such as break-glass `psql`, and into debug output. Non-secret config such as the DB CA certificate is committed in plaintext as a ConfigMap.
- **DB credentials are split** (ADR-0004):
- `hapi-db-app` is mounted only into the app Deployment, which also hosts the admin CLI.
- `hapi-db-migrator` is mounted only into the migrate Job and a runbook admin pod used for `hapi db bootstrap` and `hapi db breakglass`.
- No workload ServiceAccount can read Secrets.
- **Git is the source of truth for DB passwords.** The Owner generates them and commits them encrypted. The idempotent `hapi db bootstrap` reads them from its mounted files and runs `CREATE`/`ALTER ROLE … PASSWORD`. The `akmadmin` password is still pasted in at run time and never stored in git or the cluster.
- **Each integration gets its own narrow credential:**
- The CCM gets a dedicated Linode token with only the scopes it needs. OpenTofu creates it, never reusing the Owner's Tofu token.
- Later credentials (DNS-01, ntfy, the backup target) are each a narrow token delivered through SOPS.
- **CI secrets** (the write deploy key, the Renovate bot token, a publish-only ntfy token for the CI topic) are repo-level Gitea Actions secrets. CI never decrypts SOPS.
- **Guardrails against plaintext:**
- gitleaks runs in pre-commit and as a required CI check.
- A second CI check fails on any `kind: Secret` manifest without SOPS metadata, or any `*.sops.yaml` that isn't encrypted.
- A plaintext secret that reaches `main` is rotated. Rewriting history doesn't help, because clones and caches already have it.
- **Rotation is manual and event-driven**, with no schedule. It happens on suspicion of exposure, when the age key is exposed, or when who has access changes.
- **For a DB password:** merge the new SOPS value, wait for Flux, run `hapi db bootstrap` (which runs `ALTER ROLE`), then `kubectl rollout restart`.
- **The cost:** new connections fail for a few seconds between the last two steps, which is accepted. There's no Reloader controller.
- **Owner roots:** kubeconfig and talosconfig sit on local disk only while in use. Vaultwarden is cloud-hosted with its own backups. An additional offline copy (paper or encrypted USB, kept away from home) holds the age key, the OpenTofu state passphrase and the Linode account recovery codes, and is updated whenever one of them rotates.
-28
View File
@@ -1,28 +0,0 @@
# Probes on an internal port, authenticated three-state health, self-hosted Victoria stack
ADR-0002 allows no anonymous public endpoints, but kubelet probes can't carry a Token. So hAPI listens on two ports. **`:8000`** serves the API and is the only port the Gateway routes. **`:8081`** is internal: it is never routed, and a NetworkPolicy limits it to kubelet and the metrics scraper. It serves `/livez`, `/readyz` and `/metrics` without auth, from the **same process and event loop** as the API, so a wedged loop fails liveness. External health is **`GET /v1/health`** on the public API. It needs the `health` Scope, and it reports `ok`, `degraded` or `down` using only check names and `ok`/`fail`. Uptime Kuma, a Bot on its own public VM, polls it. Logs and metrics go to **VictoriaLogs and VictoriaMetrics**, self-hosted in the cluster. The Owner reads them through Grafana over a port-forward on the management tailnet. We chose this stack over Prometheus + Loki because it fits beside hAPI on two 4 GB workers, and over a SaaS because logs carry Principal ids and the breakglass audit trail (ADR-0004), which shouldn't leave the cluster.
## Considered Options
- **Probes on the public port, unauthenticated.** Rejected: it breaks ADR-0002's "no anonymous endpoints" rule. A probe path the Gateway happens not to route is also easier to expose by mistake than a port it never routes.
- **Readiness that checks the database.** Rejected: one blip of the managed database would mark every pod unready at once, and the NodeBalancer would serve nothing. A 503 with an RFC 9457 body is more honest. Database health goes into `/v1/health` and metrics instead.
- **Separate health endpoints per concern** (e.g. one for the HA bridge). Rejected in favour of one endpoint with critical and non-critical checks, which gives Kuma a "degraded" signal without a second route.
- **Prometheus + Loki (+ Alloy).** The industry standard. Rejected for v1 on footprint: it needs about 1.5–2 GB before tuning, on workers that also run hAPI, Flux and Cilium.
- **Grafana Cloud or another SaaS.** Rejected: it would put a vendor in the data path for Principal ids and audit events.
- **Built-in vmui / VictoriaLogs UI only.** Workable, but provisioned dashboards earn Grafana its place.
- **Write-once off-cluster storage for breakglass audit events.** Deferred: the Owner controls the cluster and is the one who runs breakglass. In v1, tamper-evidence comes from a Household ntfy alert on every breakglass start.
## Consequences
- **`/livez`** returns a constant. **`/readyz`** passes once startup is done (config loaded, pools created). On SIGTERM, `/readyz` fails first and the pod drains for about 5 s before it shuts down. Readiness also gates rollouts (ADR-0007): an image that never becomes Ready stalls the rollout.
- **`/v1/health`** checks `db` (a `SELECT 1` through the app pool) and `schema` (at the expected Alembic head). These are critical: if either fails, the status is `down` with HTTP 503. It also checks `ha_bridge` (no poll for 5 min, see ADR-0006) and `job_backlog` (oldest pending Job too old). These are non-critical: if one fails, the status is `degraded` with HTTP 200. Bodies carry no error text, hostnames, versions or latencies. Kuma points two monitors at it: *up* (HTTP status) and *healthy* (a JSON query asserting `status == "ok"`).
- **Collection:** vmagent scrapes the app, kubelet/cAdvisor, kube-state-metrics, node-exporter, Flux and Cilium. A Vector DaemonSet takes pod stdout and Talos service logs (`machine.logging`, JSON over TCP). An event exporter ships Kubernetes Events as logs. Everything lives in a `monitoring` namespace on Block Storage PVs and arrives as Flux `HelmRelease`s. **Amended by ADR-0015:** the Vector and node-exporter DaemonSets run in a separate `privileged` namespace, `monitoring-node`, while `monitoring` enforces Pod Security `restricted`. Vector also ships the Kubernetes audit log.
- **App metrics** come from `prometheus-client`: requests by route template, method and status; latency; DB pool usage; Job depth, age and failures; seconds since HA's last poll; auth failures by reason. **Labels never carry `principal_id` or Personal data.** Per-Principal detail stays in logs.
- **Retention:** logs and metrics are kept for 30 days, breakglass audit events for 1 year. **Amended by ADR-0014:** the daily backup job also exports breakglass audit events to the backup bucket, and the off-account copy keeps them for 1 year, so they survive a cluster rebuild. **Amended by ADR-0015:** Kubernetes audit logs are also kept 1 year and included in the same export.
- **Locked down:** Grafana requires login, with analytics, update checks and Gravatar off. Datasource plugins are pinned in the image. Outbound traffic from `monitoring` is denied by default, except vmalert → ntfy and the Watchdog → Kuma push.
- **Every failure has one alerting owner.**
- Kuma: reachability and degraded status.
- Flux notification-controller: failed reconciles, migrate Jobs and rollouts.
- vmalert: PVs filling, crash loops, the DB pool near ADR-0004's budget, Jobs piling up or failing, a node NotReady.
- Watchdog: an always-firing alert pushes to a Kuma push monitor, so the monitoring stack dying is caught from outside. The push URL is a SOPS secret (ADR-0008).
- **Never public:** `:8081`, Grafana, VictoriaMetrics and VictoriaLogs. They're reachable only by `kubectl port-forward` over the management tailnet.
@@ -1,37 +0,0 @@
# Envoy Gateway at the edge, DNS-01 through a delegated challenge zone, CAA pinned to our account
Public traffic reaches hAPI on one hostname, **`hapi.bobbypalko.com`**, over IPv4 only. OpenTofu reserves the IPv4 address. A Linode NodeBalancer created by the CCM listens on that address in **TCP mode** and sends **Proxy Protocol v2** to an **Envoy Gateway**. Envoy Gateway terminates TLS and forwards plain HTTP to hAPI `:8000`; Cilium's WireGuard encrypts traffic between nodes. There's no CDN (ADR-0002), so the Gateway is the only shield and enforces the edge limits. Envoy Gateway was chosen over Cilium's built-in Gateway because Cilium's Gateway has none of the limits we need as typed policy. Certificates come from **cert-manager** and Let's Encrypt over DNS-01, because `:80` is closed. The DNS-01 credential can only edit a separate, delegated **`acme.bobbypalko.com`** zone, not `bobbypalko.com` itself. A **CAA record pinned to our ACME account** means that even a leaked DNS token can't get a certificate for us.
## Considered Options
- **Cilium's built-in Gateway** (it's already the CNI, ADR-0003). It has one component fewer, but as of v1.20 it offers only global switches (Proxy Protocol, ALPN, trusted XFF hops). It has no rate limiting, connection limits, body or header limits, client timeouts or minimum-TLS policy. The only workaround is hand-written CiliumEnvoyConfig, which doesn't cleanly patch the listeners Cilium generates. Rejected.
- **Traefik with built-in ACME.** It renews certificates just as cert-manager does, but Traefik OSS keeps ACME state in a local file, so it can't run more than one replica. It would also still need the same DNS credential. Rejected.
- **A DNS-01 token on the whole `bobbypalko.com` zone** (an IAM restricted user with `domain_admin` on it). Simpler, but a leaked token could repoint `git.` or any other record. Rejected under ADR-0008's narrow-token rule.
- **Moving DNS to Cloudflare** for per-zone tokens. Rejected: it moves the whole zone to buy a token scope we can get with a delegated subzone.
- **Self-hosted acme-dns.** It has the narrowest credential, but it means running a public DNS server. Kept as the fallback if the delegated-zone setup doesn't hold up (see Consequences).
- **TLS terminated at the NodeBalancer (HTTPS mode).** Rejected: cert-manager can't rotate a certificate uploaded to Linode, and traffic from the NodeBalancer to the nodes would cross the unencrypted VPC in plaintext.
- **A backup ACME CA (GTS, ZeroSSL).** Deferred: each needs EAB credentials, which is one more secret to manage, plus its own CAA entry.
## Consequences
- **Tofu owns the stable parts:** the reserved IPv4, the NodeBalancer's Cloud Firewall (inbound TCP 443 only), the `A` record, the `_acme-challenge.hapi` CNAME, the `acme.` delegation and the CAA record. The Gateway's Service references the IP and the firewall through the CCM's `reserved-ipv4` and `firewall-id` annotations. The CCM creates and recreates the NodeBalancer without changing the address. There's no external-dns.
- **No `AAAA`.** The NodeBalancer's IPv6 frontend address can't be reserved, so recreating the NodeBalancer would silently break the record.
- **NodeBalancer:** `default-protocol: tcp`, `default-proxy-protocol: v2`, `throttle: 20` (new connections per second per client IP; the Household shares one CGNAT IP), and VPC backends.
- **Envoy Gateway:** 2 Envoy replicas spread across both workers, with a PDB and memory requests tuned down from the chart's 512Mi. The Gateway accepts Proxy Protocol only.
- `ClientTrafficPolicy`: TLS 1.3 only; ALPN h2 and http/1.1 (no HTTP/3); headers up to 16 KiB; about 50 connections per IP; request timeout 30 s, idle 60 s; client IP taken from Proxy Protocol.
- `BackendTrafficPolicy`: per-IP local rate limit of about 20 req/s, burst 100 (per replica, no Redis), and bodies up to 1 MiB (413). The app caps `transactions/ingest` batches on its own.
- HSTS is set at the edge. There's no per-Principal rate limiting (ADR-0005).
- **uvicorn trusts `X-Forwarded-For` only from the Gateway's pod range.** That way, logs and limits see the real client.
- **Layout:** one `Gateway` in a `gateway` namespace with a single HTTPS listener for `hapi.bobbypalko.com` and `allowedRoutes` limited to the `hapi` namespace. One `HTTPRoute` sends traffic to `:8000`; `:8081` is never routed (ADR-0009). Any other SNI or Host gets no certificate and no route.
- **Certificates:**
- cert-manager uses an ACME ClusterIssuer for Let's Encrypt on the default profile, plus a staging issuer for bring-up. `renewBefore` stays at its default, which is a proportion of the lifetime, so lifetimes can shrink (64 days from Feb 2027, 45 from 2028) without changes on our side. The DNS-01 solver is `linode/cert-manager-webhook-linode` with `cnameStrategy: Follow`.
- The webhook's token belongs to a **restricted Linode user** with `domain_admin` on `acme.bobbypalko.com` only. It's delivered through SOPS (ADR-0008).
- **CAA on `hapi.bobbypalko.com`** (not the apex, so other hostnames are unaffected): `0 issue "letsencrypt.org; validationmethods=dns-01; accounturi=<our account>"`.
- **The ACME account key is generated offline and committed SOPS-encrypted.** A cluster rebuilt from code (ADR-0003) reuses the same account. Otherwise the CAA pin would block our own issuance.
- **Verify during the build:**
1. That a restricted user's token really is capped by the user's grants: it must fail to edit `bobbypalko.com`.
2. That Linode serves the delegated `acme.` subzone.
3. That the CCM copies Gateway `spec.infrastructure` / `EnvoyProxy` Service annotations onto the NodeBalancer.
If either of the first two fails, switch to acme-dns before going live.
- **Delivery (ADR-0007):** cert-manager with the webhook, and Envoy Gateway with the **Standard-channel** Gateway API CRDs, arrive as Flux `HelmRelease`s in `deploy/infrastructure`. Cilium runs with `gatewayAPI.enabled=false`, so two controllers never compete for the CRDs. Renovate opens PRs for these charts, but they aren't auto-merged.
- **Observability (ADR-0009):** Envoy writes JSON access logs to stdout (client IP, status, bytes, duration, rate-limit verdict), without `Authorization` or query strings. Vector ships them to VictoriaLogs with the standard 30-day retention. Kuma's TLS-expiry notification on the `/v1/health` monitor alerts at 14 days. A vmalert rule on `certmanager_certificate_expiration_timestamp_seconds` is the in-cluster backstop.
-19
View File
@@ -1,19 +0,0 @@
# Importer Bots run in-cluster and call hAPI's internal Service
Finance fills its ledger from importer Bots that call `POST /v1/finance/transactions/ingest`; hAPI itself holds no bank credentials. v1 ships one importer, the **SimpleFIN Bot**, for the Household's Financial Accounts only. It is a **CronJob in the cluster's `bots` namespace**, built from its own package (`bots/simplefin/`) and image in this repo, delivered by the same CI and Flux as hAPI (ADR-0007). It calls hAPI through the **in-cluster Service** rather than `hapi.bobbypalko.com`, still authenticating with its own Bot Token like every other Principal (ADR-0005). We chose this because the cluster already provides SOPS secrets, logs, delivery and Kuma push, and because an outage at the public edge shouldn't stop imports.
## Considered Options
- **A home machine.** Outbound traffic works fine from behind CGNAT, but it's one more box to patch, monitor and keep secrets on, outside Flux and SOPS.
- **Calling the public hostname.** This fits ADR-0002's "one public surface" more literally, but it ties imports to the NodeBalancer and Envoy and charges the edge's per-IP limits for traffic that never leaves the cluster.
- **A subcommand of the hAPI image** (`hapi import simplefin`). This would put bank-facing code and its egress inside the API's image and blur the line that importers are Bots outside hAPI.
- **A separate repo.** Rejected under the standing "in this repo, cleanly separable" preference. import-linter forbids `bots/` from importing `hapi.*`, so the Bot talks to hAPI over HTTP only.
## Consequences
- **ADR-0002 is narrowed rather than broken.** Every request still needs a Principal's Token. Only in-cluster Bots skip the edge, and the Gateway still never routes `:8081`.
- **Credentials:** the Bot is the Principal `simplefin-importer`, holding a single Household grant of `finance:write` and no Bindings. Its Token, the SimpleFIN Access URL, the mapping from SimpleFIN account ids to Financial Account ids, and its Kuma push URL all live in one SOPS secret (`bot-simplefin`) and are mounted as files (ADR-0008). The Vaultwarden item "SimpleFIN Access URL" stays the source of truth. The mapping is encrypted because account ids and institutions are metadata we keep out of a public repo. Unmapped SimpleFIN accounts are skipped with a warning.
- **Runs:** every 6 h with `concurrencyPolicy: Forbid`, fetching a `start-date` 14 days back. The overlap absorbs posting lag and outages of up to two weeks, and idempotent ingest drops repeats. History starts at each Account's `tracked_from`, and there is no backfill.
- **Failure:** a SimpleFIN transport error, a non-empty `errors` array (e.g. a bank needs reconnecting), or a failed ingest makes the run exit non-zero. A clean run pings a Kuma push monitor with a 13 h window, which allows two missed runs (ADR-0009).
- **Network:** `bots` is default-deny. Egress is allowed only to DNS, the hAPI app port, and, through Cilium `toFQDNs`, the SimpleFIN bridge and Kuma push hosts on 443. Pods run non-root, with a read-only root filesystem and no service-account token.
- **No shared Bot library** until a second Bot exists.
-21
View File
@@ -1,21 +0,0 @@
# Scheduled work runs as CronJobs of the hAPI image, as a tokenless `scheduler` Bot
hAPI's recurring work is a small set of **Kubernetes CronJobs that run `hapi <subcommand>`** from the same digest-pinned image as the app, delivered the same way as the migrate Job (ADR-0007). There is no worker Deployment, no in-process scheduler and no task queue. Most domain logic is computed on read (Finance summaries, Maintenance due dates, Fitness bests), so little has to run on a timer. A CronJob keeps nothing running between runs, gets retries and `concurrencyPolicy: Forbid` from Kubernetes, and is a CLI command the Owner can also run by hand.
## Considered Options
- **A worker Deployment with an in-process scheduler** (APScheduler, arq). Rejected: it runs all the time, holds its own pool of up to 10 connections from ADR-0004's budget, and needs leader election before it can have more than one replica.
- **Scheduling inside the API pods.** Rejected: with 2 replicas every task needs an advisory lock, and the work competes with requests for the event loop.
- **A transactional outbox of domain events** (e.g. "Reading recorded"), drained by a CronJob. Rejected for v1. The state already in the database is the event: a scheduled check compares it with what has already been notified, at the cost of up to one interval of latency. A generic event model can arrive once something needs sub-minute reactions.
- **FastAPI `BackgroundTasks` after commit.** Rejected: the work is lost if the pod dies.
- **Running as `hapi_migrator`**, which bypasses RLS as the table owner. Rejected: it would put migrator credentials in a recurring pod.
- **Giving the scheduler Bindings to Personal data.** Rejected: every Person would have to consent, and v1's per-Person work is read-only anyway.
## Consequences
- **v1 inventory:** `hapi jobs sweep` every 15 min marks pending Jobs past `expires_at` as `expired` and deletes finished Jobs older than 90 days (replacing ADR-0006's `hapi jobs purge`). Reads derive `expired` from `expires_at` until the sweep catches up, so correctness never depends on how often it runs. The notification checks are CronJobs running `hapi notify <check>` (`tasks`, `jobs`, `budget`, `tokens`), plus `hapi notify deliver` every 2 min, which alone publishes to ntfy (ADR-0013). Purging a removed Person's data stays an on-demand Owner CLI command, and Finance month rollover, Banked carry-forward and `date_review` need no schedule.
- **Principal:** work on Household data runs as a built-in **`scheduler` Bot**. A migration creates it, it can never hold a Token (so it can't be reached from the API), and the Owner gives it Household grants like any other Bot. Recorded by shows `scheduler`. Work on Personal data runs once per Person with `hapi.principal_id` set to that Person (ADR-0004), and is **read-only**: a scheduled write to Personal data needs a new decision.
- **Event-triggered work** (e.g. a new Reading making a Task due) is picked up by the next scheduled check. Checks write **durable Notifications**, which double as the record of what was already notified. A Notification not yet delivered stays pending and is retried on the next run, so an ntfy outage loses nothing, and a future frontend inbox reads the same records.
- **Connection budget (amends ADR-0004):** each housekeeping CronJob uses a pool of 1 with no overflow and `concurrencyPolicy: Forbid`. The rule becomes: app pods including surge × 10 + concurrently runnable CronJobs × 1 + ~6 ≤ 46.
- **Monitoring:** one generic vmalert rule fires when any CronJob hasn't succeeded within twice its interval (kube-state-metrics' `kube_cronjob_status_last_successful_time`). ADR-0009's Watchdog covers vmalert itself. Kuma push monitors are kept for jobs whose silence must be caught even when the whole cluster is down: the importer (ADR-0011) and backups.
- **Time:** the Household timezone is one setting in `deploy/`, fed both to the app config and to `spec.timeZone` on calendar-based CronJobs (daily checks, month-end). Interval jobs like the sweep ignore it.
-30
View File
@@ -1,30 +0,0 @@
# Notifications are durable records delivered by one CronJob; platform alerts bypass hAPI
hAPI's **Notifications** are database records addressed to one Person or to the Household, written by `hapi notify <check>` CronJobs (ADR-0012) and published to ntfy at **notify.bobbypalko.com** by a single `hapi notify deliver` CronJob. **Platform alerts are a separate lane:** CI, Flux, vmalert and Kuma publish straight to Owner-only ntfy topics with their own credentials and never touch hAPI, because they must work when hAPI or its database is down. ntfy is the only channel in v1: no preferences, no read state, no Notifications API; a Person opts out by muting in the ntfy app.
## Considered Options
- **Routing platform alerts through hAPI** (one Notification model for everything). Rejected: an alert that hAPI is down can't depend on hAPI.
- **Each check delivering what it wrote, or every check draining all pending Notifications.** Rejected: a budget run sending Token reminders is surprising, and an ntfy outage would fail every check. One deliver job keeps checks pure writers and isolates ntfy failures to one CronJob.
- **Checks over Personal domain data** (e.g. a Person's Budget). Deferred to v2 with the Personal importer: they'd need scheduled writes for a Person, which ADR-0012 forbids.
- **Per-Person preferences and a frontend inbox.** Deferred: the records already support an inbox and read state later.
## Consequences
- **ntfy access:** the server denies anonymous read and publish. The Owner manages users by hand from a runbook in `docs/` (also an off-boarding step alongside Token revocation): a read-only user per Person for `hapi-p-<person-id>` and `hapi-household`; the Owner's user also reads `ops` and `ops-urgent`; each sender (hAPI, vmalert, Flux, CI, Kuma) has its own publish-only user limited to its topics. hAPI's, vmalert's and Flux's tokens come through SOPS (ADR-0008), CI's is a Gitea secret, Kuma's lives in Kuma. Topics are named by id, never by name. `upstream-base-url` points at ntfy.sh for iOS (only a poll request leaves, never content), the cache stays at 12 h, attachments are off.
- **Content:** a short title and a link to the resource. Never amounts, balances, Measurements or other domain values.
- **v1 checks** (all run as the `scheduler` Bot, read only Household and platform data):
| Check | Recipient | Fires | Schedule |
|---|---|---|---|
| `tasks` | Household | once on entering `lead_days`, once on overdue, per due occurrence (a Service or snooze starts the next) | daily 08:00 |
| `jobs` | Household | a Job ends `failed` or `expired` | every 15 min |
| `budget` | Household | a Household Budget Category goes into the red this month (Banked: its banked balance goes negative); refires only after it recovers | hourly |
| `tokens` | the Token's Person, or the Owner for Bot Tokens | 30 and 7 days before expiry | daily |
- **Record:** recipient (Person or Household), `kind`, `dedupe_key` (unique with `kind`; it is the "already notified" ledger), `title`, `body`, priority 1–5, optional link, `created_at`, `delivered_at`, `attempts`. `hapi jobs sweep` deletes delivered Notifications after 180 days.
- **Delivery:** `hapi notify deliver` every 2 min publishes pending Notifications oldest first, using the Notification id as ntfy's message/sequence id so retries don't double-push. It gives up after 24 h; a vmalert rule fires on undelivered Notifications that old. It counts as one more pool-1 CronJob in ADR-0012's connection rule.
- **Breakglass fails closed:** `hapi db breakglass` publishes a priority-5 Household alert synchronously (and records a Notification) before opening the session, and refuses to start if the publish fails. Bypassing the wrapper with raw credentials remains the residual risk ADR-0009 accepts.
- **Platform topics and priorities:** `ops` (Flux, vmalert, CI) and `ops-urgent` (Kuma *down*, the Watchdog). Priority 5: Kuma down, breakglass. 4: vmalert critical, Flux reconcile/rollout failure, Task overdue. 3: CI failure, Kuma degraded, Job failed/expired, Token expiring in 7 days. 2: Task due soon, budget overspend, Token expiring in 30 days.
- **Importer staleness** needs no hAPI check: the SimpleFIN Bot already fails on a non-empty `errors` array and Kuma's 13 h push monitor catches it (ADR-0011).
- **Egress** to notify.bobbypalko.com:443 is needed from hAPI's CronJobs and Flux's notification-controller (vmalert's is already allowed by ADR-0009); the policies themselves belong to cluster hardening.
@@ -1,24 +0,0 @@
# Backups go to an Object Lock bucket the cluster can't read back, pulled off-account to the Owner's machine
Linode's 14-day point-in-time recovery covers a bad migration, a bad delete or a lost database (ADR-0004). It doesn't cover damage found after 14 days, or losing the Linode account. So hAPI also takes its own daily dump. A **`hapi db backup` CronJob** streams `pg_dump -Fc | age | upload` into **`hapi-backups`**, a Linode Object Storage bucket with **Object Lock in compliance mode**. Dumps are encrypted to a **dedicated backup age recipient**, and its private key is never in the cluster. A **puller outside Linode**, holding only a `read_only` key, copies new objects out and never deletes or overwrites them. A compromised cluster can therefore neither read nor erase backups, and losing the account doesn't lose them. Recovery targets: (a) inside Linode, minutes of data lost and back within about 2 h; (b) damage found late, up to one day lost; (c) account loss, everything since the puller's last copy lost, with a weekend of downtime acceptable. Nothing is highly available.
## Considered Options
- **Backblaze B2 (or R2 or S3) as the off-platform target.** Rejected in favour of Linode plus a pull: no new vendor, and Object Lock plus an off-account copy give the same protection. Linode keys are only `read_only` or `read_write` (there's no write-only key), so compliance-mode lock is what stops the cluster's key from deleting.
- **Pushing to a home NAS.** Impossible: no connection may start from home into the cluster (ADR-0002, CGNAT). The pull direction works.
- **Encrypting with the SOPS age key.** Rejected: Flux holds it in the cluster, so a compromised cluster could decrypt every old dump.
- **Dumping as `hapi_migrator`** (it owns the tables, so it bypasses RLS). Rejected by ADR-0012: no migrator credentials in recurring pods.
- **A separate backup image** (postgres + age + rclone). Rejected: ADR-0012's one-image, one-delivery-path rule. `postgresql-client-18` is added to the hAPI image instead, and `pg_restore` comes with it.
- **etcd / Talos snapshots.** Not taken: everything in etcd is in git or can be recreated (certificates get reissued, the Tailscale operator re-authenticates from SOPS, the CCM recreates the NodeBalancer on the reserved IP). Losing the cluster means rebuilding it from code (ADR-0003).
- **Keeping breakglass audit events only in VictoriaLogs**, or also writing them to Postgres. Rejected: the monitoring PVs don't survive a rebuild, and `hapi_migrator` could edit rows in Postgres.
## Consequences
- **`hapi_backup` role** (amends ADR-0004): LOGIN, `BYPASSRLS`, SELECT only, created by `hapi db bootstrap`. Its reads stay complete through `ALTER DEFAULT PRIVILEGES` set as `hapi_migrator`. Its password is its own SOPS secret, mounted only into the backup pod. Whoever holds it, or the backup private key, can read all Personal data. Like `akmadmin` and the Tofu state, that is controlled by policy and audit, not by cryptography (ADR-0001). The dump uses one connection, counted in ADR-0012's CronJob term. To verify during the build: that `akmadmin` can create a `BYPASSRLS` role on Aiven.
- **Backup key:** an age keypair generated offline. The cluster has only the public recipient, in plain config. The private key is in Vaultwarden and the offline copy (ADR-0008), next to the other Owner roots.
- **Bucket:** created by Tofu with Object Lock (compliance mode, which turns on versioning). Each object is locked for 35 days, and a lifecycle rule expires it after 35 days. The cluster's key is `read_write` and limited to this bucket (through SOPS). To verify during the build: that it can't delete a locked version.
- **Schedule and content:** daily at 03:00 Household time (`spec.timeZone`, ADR-0012). The job copies the plaintext stream into `pg_restore --list` before encrypting it, so an archive whose table of contents doesn't parse fails the run. The same job exports the previous day's breakglass audit events from VictoriaLogs to `audit/`, encrypted to the same recipient (amends ADR-0009: the 1-year retention now survives a rebuild). The backup pod's egress is limited to the DB, Object Storage, VictoriaLogs and Kuma.
- **Puller:** a script in `infra/backup-pull/` (with a `just` recipe) running `rclone copy --immutable` plus pruning. It keeps 90 dailies, the dump from each 1st of the month for 3 years, and `audit/` for 1 year. It also pulls the versioned Tofu state bucket (which holds the Talos machine secrets, ADR-0003) with a second `read_only` key. It isn't a Principal: it never talks to hAPI. **For now it runs on the Owner's PC** as a systemd user timer (daily, `Persistent=true`). There, tier (c)'s data loss is "since the last pull", which is safe as long as the PC pulls at least once in 35 days. **It moves unchanged to a NAS** when one exists.
- **Monitoring:** two Kuma push monitors. The backup CronJob's alerts after 26 h of silence. The puller's (it pushes only after copying an object less than 26 h old) alerts after **8 days while it runs on the PC. Change that to 26 h when it moves to the NAS.** ADR-0012's generic vmalert rule also covers the CronJob.
- **Restore runbook:** the database is VPC-only, so restores run as **`hapi db restore`** in a pod. The Owner pastes in the backup private key at run time (like the `akmadmin` password), and it's never stored. Path **(A)**: a Linode point-in-time fork, then bootstrap, then repoint the app (ADR-0004's runbook, shared with plan resizes). Path **(B)**: a new database, then bootstrap, then `hapi db restore` from our dump as `hapi_migrator`, then repoint the app. If the account is lost, the Owner first uploads the dump from the puller's copy into the new account's bucket. A cluster rebuild needs the SOPS age key, the Tofu state passphrase (Vaultwarden or the offline copy) and Gitea. Backing up Gitea is out of scope. Its fallbacks are the Owner's local clone and rebuilding images in CI.
- **Rehearsal:** before go-live, as acceptance for the build epic, run one full drill: rebuild the cluster from code in an empty Linode project, then path (B) from a pulled copy. After that, every 6 months, run path (B) into a throwaway database, check the Alembic revision and row counts per table, then delete it. This also rehearses plan resizes. It's tracked as a Household Maintenance Task, "Rehearse disaster recovery" (fixed RRULE), so the `tasks` check reminds through ntfy. **Amended by ADR-0015:** the Task concerns the "hAPI cluster" Asset, now that Maintenance covers the Household's digital systems.
@@ -1,28 +0,0 @@
# Cluster hardening baseline: deny-by-default network, restricted pods, audit logs; signing deferred
v1 hardens the cluster with built-in mechanisms only. That means **default-deny CiliumNetworkPolicies** in every namespace we own, **Pod Security `restricted`** wherever it fits, two **ValidatingAdmissionPolicies** (in-apiserver CEL rules), **Kubernetes audit logging**, and a written **upgrade runbook** with a fixed cadence. **Commit signature verification and cosign image signing are deferred.** We chose this because each measure here closes a real gap without adding a controller to run. Signing would only move trust onto keys held by the same Gitea and runner it's meant to protect against.
## Considered Options
- **Flux commit verification plus cosign signing with admission-time verification, in v1.** Rejected for now. CI commits the digest bump to `main` (ADR-0007), so HEAD is usually a CI commit, and CI would need its own signing key. There's no keyless identity for Gitea, so the cosign key would be key-based too. Both keys would live in Gitea Actions secrets or on the runner, where an attacker who controls Gitea can run a workflow that uses them. Signed tags from a hardware key would break "every green merge deploys". Flux image automation would need git write credentials in the cluster.
- **Kyverno (or sigstore policy-controller) for admission.** Rejected for two rules. It adds a controller, a webhook that can fail open or closed, and more upgrades to keep up with. Revisit when signing returns.
- **Moving `monitoring` to `privileged` as a whole.** Rejected in favour of isolating the node agents in their own namespace.
- **Keeping ops reminders out of hAPI** (a personal calendar), since hAPI can't remind you to fix hAPI while it's down. Rejected: these are recurring upkeep, which is what Maintenance Tasks are for, and Kuma covers the outage case. The glossary's Maintenance now includes the Household's digital systems.
## Consequences
- **NetworkPolicy:** every namespace we own (`hapi`, `bots`, `gateway`, `envoy-gateway-system`, `monitoring`, `monitoring-node`, `cert-manager`, `flux-system`) is default-deny for ingress and egress. Each component's allows sit next to its manifests in `deploy/`. Rules that name hosts are `CiliumNetworkPolicy`, using `toFQDNs` for ntfy, Linode Object Storage, the Linode API, SimpleFIN, Kuma and Let's Encrypt, and `toCIDR` for the Managed DB's VPC address. This includes the allows already promised by ADR-0009, ADR-0011, ADR-0013 and ADR-0014. `kube-system` (Cilium, CCM and CoreDNS, installed by Tofu) stays open.
- **Pod Security:** the cluster default stays at Talos's `baseline`. Every namespace we own enforces `restricted`, except **`monitoring-node`**, which is `privileged` and holds only the Vector and node-exporter DaemonSets. This amends ADR-0009.
- **Admission (ValidatingAdmissionPolicy, Deny from day one, delivered by Flux):**
1. Images must come from Gitea's registry, or carry an `@sha256:` digest. Applies everywhere except `kube-system`.
2. Pods in `hapi` and `bots` must set `readOnlyRootFilesystem: true` and `automountServiceAccountToken: false`.
- **Audit logging:** the apiserver audit policy is set in Talos machine config at `Metadata` level. It keeps every write and every access to `secrets`, `pods/exec`, `pods/portforward` and `serviceaccounts/token`, and drops controllers' and Flux's reads, health endpoints and Events. Vector in `monitoring-node` ships the control-plane node's audit file to VictoriaLogs, where it's **kept 1 year** and included in ADR-0014's daily `audit/` export. A `pods/exec` or a Secret read by a human sends an alert to the ntfy `ops` topic. Dial the policy back if it's too noisy.
- **Upgrades:** Talos, Kubernetes, Cilium and CCM versions are pinned in `infra/`. Renovate opens PRs for them and never auto-merges. Security patches go in within 14 days; minor versions after their `.1`, staying within upstream support. The procedure goes in `docs/runbooks/cluster-upgrade.md`, written during the build:
1. Take a throwaway local `talosctl etcd snapshot`, never stored (ADR-0014's no-etcd-backups rule still holds).
2. Upgrade and drain the workers one at a time.
3. Upgrade the control plane, accepting a few minutes without the API.
4. Run `talosctl health` and check that Flux reconciles.
The reminder is a monthly Household Maintenance Task, "Upgrade the cluster", on a **"hAPI cluster" Asset**. ADR-0014's "Rehearse disaster recovery" Task hangs off the same Asset.
- **Supply chain in v1:** images stay digest-pinned (ADR-0007), admission rule 1 limits where images come from, CI's Trivy scan stays, and `main` has branch protection in Gitea. Revisit signing once CI has an identity a compromised Gitea can't use.
- **Deferred to v2:** runtime detection (Tetragon/Falco), in-cluster vulnerability scanning (Trivy Operator), CIS scanning, the Cilium host firewall (the Linode Cloud Firewall already covers nodes), least-privilege kubeconfigs (the Owner keeps Talos's admin kubeconfig, used only over the tailnet), and any CI check of policy coverage. etcd secret encryption needs no decision: Talos enables it by default.
+15 -36
View File
@@ -1,46 +1,25 @@
# Issue tracker: Gitea
# Issue Tracker
Issues and specs for this repo live as issues on the self-hosted Gitea instance at https://git.bobbypalko.com (repo `bobby/hapi`). Use the `gt` CLI ([gitea.com/gitea/cli](https://gitea.com/gitea/cli)) for all operations.
**Type**: Gitea (self-hosted)
`gt` infers the instance and repo from the `origin` remote when run inside a clone; pass `-R bobby/hapi` if it can't. When you parse output, use `--json <fields>` (optionally with `--jq`): the text output is meant for people and may change between releases. `gt <command> --help` lists the JSON fields each command supports.
**Location**: https://git.bobbypalko.com/bobby/hapi
## Conventions
**Workflow**: Issues are tracked in the Gitea instance at the above URL. The `gt` CLI (Gitea's official CLI) is used to interact with issues.
- **Create an issue**: `gt issue create --title "..." --body "..."`. For multi-line bodies, use `--body-file -` with a heredoc. Add `--label "..."` and `--blocked-by <n>` as needed.
- **Read an issue**: `gt issue view <number> --json number,title,body,state,labels,assignees,blocked_by`, then `gt issue comment list <number> --json author,body,created_at` for the comments.
- **List issues**: `gt issue list --state open --json number,title,body,labels,assignees --jq '[.[] | {number, title, body, labels: [.labels[].name], assignees}]'`, with `--label`, `--state`, and `--limit` filters as appropriate.
- **Make an issue a sub-issue of a parent**: Gitea has no sub-issues. Put `Part of #<parent>` at the top of the child body and add the child to a task list (`- [ ] #<child>`) in the parent body.
- **Comment on an issue**: `gt issue comment <number> --body "..."` (or `--body-file -` with a heredoc).
- **Apply / remove labels**: `gt issue edit <number> --add-label "..."` / `--remove-label "..."`
- **Close**: `gt issue close <number> --comment "..."`
**PRs as request surface**: No (default)
## Pull requests as a triage surface
## Commands
**PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_
- Create issue: `gt issue create --title "..." --body "..."`
- View issues: `gt issue list`
- View issue details: `gt issue view <number>`
- Edit issue: `gt issue edit <number> --title "..." --body "..."`
- Close issue: `gt issue close <number>`
When set to `yes`, PRs run through the same labels and states as issues, using the `gt pr` equivalents:
## Triage labels
- **Read a PR**: `gt pr view <number>` and `gt pr diff <number>` for the diff.
- **List PRs for triage**: `gt issue list --kind pulls --state open --json number,title,author,labels`, then filter out PRs from the repo owner and collaborators.
- **Comment / label / close**: `gt issue comment`, `gt issue edit --add-label`/`--remove-label`, `gt pr close`.
Run `gt label create <name>` for each label in `docs/agents/triage-labels.md`.
Gitea shares one number space across issues and PRs, so a bare `#42` may be either: resolve with `gt pr view 42` and fall back to `gt issue view 42`.
## Notes
## When a skill says "publish to the issue tracker"
Create a Gitea issue with `gt issue create`.
## When a skill says "fetch the relevant ticket"
Read it as in **Read an issue** above.
## Wayfinding operations
Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets.
- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `gt issue create --label wayfinder:map`.
- **Child ticket**: an issue with `Part of #<map>` at the top of its body, listed in a task list in the map body (see **Make an issue a sub-issue of a parent**). Labels: `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev.
- **Blocking**: Gitea's **native issue dependencies**. Add an edge with `gt issue edit <child> --add-blocked-by <blocker>` (or `--blocked-by` at creation). Read them with `gt issue view <child> --json blocked_by`. A ticket is unblocked when every blocker is closed.
- **Frontier query**: list the map's open children (the issues in the map's task list that are still open), drop any with an open blocker or an assignee; first in map order wins.
- **Claim**: `gt issue edit <n> --add-assignee @me`, the session's first write.
- **Resolve**: `gt issue comment <n> --body "<answer>"`, then `gt issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far.
- Authenticate with `gt auth login -h https://git.bobbypalko.com`.
+29
View File
@@ -0,0 +1,29 @@
# Terraform files
.terraform/
.terraform.lock.hcl
terraform.tfstate
terraform.tfstate.backup
*.tfstate
*.tfstate.*
# Terraform plan files
*.tfplan
# Environment variables
.env
.env.*
*.env
# IDE and editor files
.idea/
.vscode/
*.swp
*.swo
*~
# OS files
.DS_Store
Thumbs.db
# Logs
*.log
+150
View File
@@ -0,0 +1,150 @@
# Implementation Summary: Issue 1 - Linode Infrastructure with Terraform
## Status: ✅ Complete
This implementation creates the Linode infrastructure for the HAPI project using Terraform, as described in Issue 1.
## What Was Built
### Infrastructure Modules
| Module | Location | Description |
|--------|----------|-------------|
| **Backend** | `infra/backend/` | Terraform state stored in Linode Object Storage |
| **PostgreSQL** | `infra/postgres/` | Database instances for staging and production |
| **Storage** | `infra/storage/` | Object Storage buckets for uploads and state |
| **Network** | `infra/network/` | Firewall rules for API, PostgreSQL, and Adminer |
### Directory Structure
```
infra/
├── backend/ # Terraform state backend configuration
│ ├── main.tf
│ ├── variables.tf
│ └── terraform.tfvars.example
├── postgres/ # PostgreSQL database instances
│ ├── main.tf
│ ├── variables.tf
│ ├── random.tf
│ └── terraform.tfvars.example
├── storage/ # Object Storage buckets
│ ├── main.tf
│ ├── variables.tf
│ └── terraform.tfvars.example
├── network/ # Firewall configuration
│ ├── main.tf
│ ├── variables.tf
│ └── terraform.tfvars.example
├── main.tf # Orchestration file
├── providers.tf # Provider configurations
├── variables.tf # Common variables
├── outputs.tf # Common outputs
├── .gitignore # Terraform ignores
├── .env.example # Environment variable template
├── Makefile # Common commands
└── README.md # Infrastructure documentation
```
## Implementation Details
### 1. Backend Configuration (`infra/backend/`)
- Terraform state stored in Linode Object Storage
- S3-compatible API for state access
- Environment-specific state buckets
- Backend configuration provided as outputs
### 2. PostgreSQL (`infra/postgres/`)
- LKE (Linode Kubernetes Engine) clusters for staging and production
- Configurable pool sizes (10 for staging, 25 for production)
- Separate database names (`hapi_staging`, `hapi_production`)
- Random password generation for database access
### 3. Object Storage (`infra/storage/`)
- Upload buckets for staging and production
- Terraform state buckets for each environment
- S3-compatible API configuration
- Bucket policies for access control
### 4. Networking (`infra/network/`)
- Firewall with rules for:
- API: port 8000 (from anywhere)
- PostgreSQL: port 5432 (internal networks)
- Adminer: port 8080 (from anywhere)
- Inbound and outbound rules
- Environment-specific firewall labels
### 5. Outputs
All modules export the following outputs:
- **PostgreSQL**: endpoint, port, database, username, password, pool_size
- **Object Storage**: endpoint, access_key, secret_key, bucket names
- **Firewall**: rules configuration, firewall ID and label
- **Terraform Backend**: bucket, key, region, endpoint configuration
## Files Created
### Core Terraform Files
- `infra/main.tf` - Main orchestration
- `infra/providers.tf` - Provider configurations
- `infra/variables.tf` - Common variables
- `infra/outputs.tf` - Common outputs
### Module Files (each module has main.tf, variables.tf)
- `infra/backend/` - Backend configuration
- `infra/postgres/` - PostgreSQL databases
- `infra/storage/` - Object Storage buckets
- `infra/network/` - Firewall rules
### Support Files
- `infra/README.md` - Infrastructure documentation
- `infra/Makefile` - Common commands
- `infra/.gitignore` - Terraform ignores
- `infra/.env.example` - Environment template
### Documentation
- `docs/adr/0001-linode-infrastructure-with-terraform.md` - Architecture decision record
## Next Steps
### 1. Environment Setup
```bash
cd infra
cp .env.example .env
# Edit .env with your Linode credentials
```
### 2. Initialize Terraform
```bash
make init
# or: terraform init
```
### 3. Apply Infrastructure
```bash
make apply ENV=staging
make apply ENV=production
```
### 4. Verify Deployment
- Check Linode dashboard for created resources
- Verify Object Storage buckets exist
- Test PostgreSQL connection
- Confirm firewall rules are applied
## Checklist (from Issue 1)
- [x] Terraform state stored in Linode Object Storage (backend configuration)
- [x] PostgreSQL database instance for staging created
- [x] PostgreSQL database instance for production created
- [x] Linode Object Storage bucket for staging uploads created
- [x] Linode Object Storage bucket for production uploads created
- [x] Basic networking: firewall rules configured for API, PostgreSQL, Adminer
- [x] Terraform outputs exported (database endpoints, object storage credentials)
## Notes
- Environment variables are used for credentials (not committed to Git)
- Each environment (staging/production) has its own Object Storage bucket
- PostgreSQL uses LKE clusters for scalability
- Firewall rules are environment-agnostic but labeled appropriately
- Makefile provides convenient commands for common operations
+63
View File
@@ -0,0 +1,63 @@
# Makefile for HAPI Terraform infrastructure
.PHONY: init plan apply destroy output env
# Environment defaults
ENV ?= staging
REGION ?= us-east
# Initialize Terraform
init:
@echo "Initializing Terraform..."
terraform init
# Initialize with backend configuration
init-backend:
@echo "Initializing Terraform with backend..."
terraform init -reconfigure \
-backend-config=bucket=hapi-terraform-state-${ENV} \
-backend-config=key=terraform/${ENV}/terraform.tfstate \
-backend-config=region=${REGION}
# Generate plan
plan:
@echo "Generating Terraform plan for ${ENV}..."
terraform plan -var="environment=${ENV}"
# Apply changes
apply:
@echo "Applying Terraform changes for ${ENV}..."
terraform apply -var="environment=${ENV}"
# Apply with auto-approve
apply-auto:
@echo "Applying Terraform changes for ${ENV} (auto-approve)..."
terraform apply -var="environment=${ENV}" -auto-approve
# Destroy infrastructure
destroy:
@echo "Destroying Terraform infrastructure for ${ENV}..."
terraform destroy -var="environment=${ENV}"
# Show outputs
output:
@echo "Terraform outputs:"
terraform output
# Load environment variables
env:
@echo "Environment variables:"
@echo " ENV=${ENV}"
@echo " REGION=${REGION}"
@echo " LINODE_TOKEN=${LINODE_TOKEN}"
@echo " OBJECT_STORAGE_ACCESS_KEY=${OBJECT_STORAGE_ACCESS_KEY}"
@echo " OBJECT_STORAGE_SECRET_KEY=${OBJECT_STORAGE_SECRET_KEY}"
# Run all checks
check: init plan apply
# Clean up local state
clean:
@echo "Cleaning local Terraform files..."
rm -rf .terraform/
rm -f .terraform.lock.hcl
+136
View File
@@ -0,0 +1,136 @@
# Quickstart: HAPI Infrastructure with Terraform
## Prerequisites
1. **Linode Account** - Get your API token from the Linode Cloud Manager
2. **Terraform** - Version 1.9.0 or higher
3. **Object Storage Credentials** - Create access keys in Linode Object Storage
## Setup Steps
### 1. Configure Environment Variables
```bash
cd infra
# Copy the example environment file
cp .env.example .env
# Edit .env with your credentials
vim .env
```
Or export directly:
```bash
export LINODE_TOKEN="your-token"
export LINODE_REGION="us-east"
export OBJECT_STORAGE_ACCESS_KEY="your-access-key"
export OBJECT_STORAGE_SECRET_KEY="your-secret-key"
```
### 2. Initialize Terraform
```bash
make init
# or
terraform init
```
For remote backend (state in Object Storage):
```bash
make init-backend
# or
terraform init -reconfigure \
-backend-config=bucket=hapi-terraform-state-staging \
-backend-config=key=terraform/staging/terraform.tfstate \
-backend-config=region=us-east
```
### 3. Review Plan
```bash
make plan
# or
terraform plan -var="environment=staging"
```
### 4. Apply Infrastructure
```bash
make apply
# or
terraform apply -var="environment=staging"
```
### 5. Verify Resources
Check the Linode Cloud Manager for:
- Kubernetes clusters (`hapi-postgres-staging`)
- Object Storage buckets (`hapi-uploads-staging`, `hapi-terraform-state-staging`)
- Firewall rules (`hapi-firewall`)
## Environment-Specific Commands
### Staging
```bash
make apply ENV=staging
make destroy ENV=staging
```
### Production
```bash
make apply ENV=production
make destroy ENV=production
```
## Common Commands
| Command | Description |
|---------|-------------|
| `make init` | Initialize Terraform |
| `make init-backend` | Initialize with remote backend |
| `make plan` | Generate execution plan |
| `make apply` | Apply infrastructure changes |
| `make apply-auto` | Apply with auto-approve |
| `make destroy` | Destroy infrastructure |
| `make output` | Show outputs |
| `make env` | Show current environment variables |
## Outputs
After apply, you'll see outputs like:
- `postgres_endpoint` - PostgreSQL connection string
- `postgres_port` - Database port (5432)
- `postgres_database` - Database name
- `postgres_username` / `postgres_password` - Credentials
- `object_storage_endpoint` - S3-compatible endpoint
- `object_storage_access_key` / `object_storage_secret_key` - Storage credentials
- `firewall_rules` - Network access configuration
## Next Steps
1. **Set up CI/CD** - Configure Gitea Actions to run Terraform on changes
2. **Configure Database** - Run Alembic migrations on the new PostgreSQL instances
3. **Set up Object Storage** - Configure upload buckets for the API
4. **Configure Firewall** - Ensure API and Adminer can connect
## Troubleshooting
### Common Issues
1. **Authentication errors** - Verify `LINODE_TOKEN` has Object Storage permissions
2. **Bucket not found** - Ensure Object Storage cluster matches configuration
3. **Firewall rules not applied** - Check that firewall ID matches in module references
### Debugging
```bash
# Verbose logging
export TF_LOG=DEBUG
# Show detailed plan
terraform plan -detailed-exitcode
# Refresh state
terraform refresh
```
+112
View File
@@ -0,0 +1,112 @@
# HAPI Infrastructure with Terraform
This directory contains Terraform configurations for provisioning HAPI infrastructure on Linode.
## Directory Structure
```
infra/
├── backend/ # Terraform state backend configuration
├── postgres/ # PostgreSQL database instances
├── storage/ # Object Storage buckets
├── network/ # Firewall rules
├── main.tf # Main orchestration file
├── variables.tf # Common variables
├── outputs.tf # Common outputs
└── README.md # This file
```
## Prerequisites
- Linode account with API access
- Linode CLI (`linode-cli`) or direct API access for Object Storage credentials
- Terraform 1.9.0 or higher
## Setup
### 1. Configure Linode API Token
```bash
export LINODE_TOKEN="your-linode-api-token"
export LINODE_REGION="us-east"
```
### 2. Create Object Storage Credentials
```bash
# Create access keys
linode-object-storage keys create
# Set environment variables
export OBJECT_STORAGE_ACCESS_KEY="your-access-key"
export OBJECT_STORAGE_SECRET_KEY="your-secret-key"
```
### 3. Initialize Terraform
```bash
cd infra
terraform init
```
### 4. Apply Infrastructure
```bash
# For staging
terraform apply -var="environment=staging"
# For production
terraform apply -var="environment=production"
```
## Resources Provisioned
### PostgreSQL
- Database instance (staging and production)
- Connection pooling configuration
- Automated backups
### Object Storage
- Upload buckets for staging and production
- Terraform state storage
- S3-compatible API
### Networking
- Firewall rules for:
- API (port 8000)
- PostgreSQL (port 5432)
- Adminer (port 8080)
- Inbound and outbound rules
## Outputs
- PostgreSQL endpoint, port, database name, credentials
- Object Storage endpoint, access keys
- Firewall configuration
- Terraform backend configuration
## Environment-Specific Configuration
See `backend/example.tfvars` for example configuration values.
## Deployment
### Staging
- Deployed automatically on `main` branch pushes
- Uses staging Object Storage bucket
- Lower resource allocation
### Production
- Deployed on version tags
- Uses production Object Storage bucket
- Higher resource allocation and HA configuration
## Maintenance
### Updating Terraform State
Terraform state is automatically stored in Linode Object Storage under the configured bucket and key path.
### Adding New Resources
Add modules to `main.tf` and create corresponding directories under `infra/` following the established pattern.
+14
View File
@@ -0,0 +1,14 @@
# Terraform Backend Configuration
# Configure this in your main terraform.tfvars or environment variables
# Linode Object Storage as Terraform backend
# Copy this to your terraform.tfvars or set as environment variables
linode_token = "<YOUR_LINODE_API_TOKEN>"
linode_region = "us-east"
environment = "staging" # or "production"
project_name = "hapi"
# Object Storage credentials
object_storage_access_key = "<YOUR_ACCESS_KEY>"
object_storage_secret_key = "<YOUR_SECRET_KEY>"
+44
View File
@@ -0,0 +1,44 @@
# Backend configuration for Terraform state in Linode Object Storage
# This module provides the configuration needed for remote state storage
resource "linode_object_storage_bucket" "terraform_state" {
label = "hapi-terraform-state-${var.environment}"
cluster = var.linode_object_storage_cluster
access_key = var.object_storage_access_key
secret_key = var.object_storage_secret_key
}
locals {
backend_config = {
bucket = "hapi-terraform-state-${var.environment}"
key = "terraform/${var.environment}/terraform.tfstate"
region = var.linode_region
endpoint = "https://${var.linode_region}.linodeobjects.com"
encrypt = true
access_key = var.object_storage_access_key
secret_key = var.object_storage_secret_key
skip_region_validation = true
}
}
output "backend_config" {
description = "Terraform backend configuration"
value = local.backend_config
}
output "backend_s3_config" {
description = "S3-style backend configuration for Terraform"
value = {
bucket = local.backend_config.bucket
key = local.backend_config.key
region = local.backend_config.region
endpoint = local.backend_config.endpoint
encrypt = local.backend_config.encrypt
access_key = local.backend_config.access_key
secret_key = local.backend_config.secret_key
skip_region_validation = local.backend_config.skip_region_validation
}
sensitive = {
secret_key = local.backend_config.secret_key
}
}
+6
View File
@@ -0,0 +1,6 @@
# Backend module variables
linode_region = "us-east"
linode_object_storage_cluster = "us-east-1"
object_storage_access_key = "your-access-key"
object_storage_secret_key = "your-secret-key"
environment = "staging"
+42
View File
@@ -0,0 +1,42 @@
# Variables for Backend module
variable "linode_region" {
description = "Linode region for Object Storage"
type = string
default = "us-east"
}
variable "linode_object_storage_cluster" {
description = "Linode Object Storage cluster"
type = string
default = "us-east-1"
}
variable "object_storage_access_key" {
description = "Object Storage access key"
type = string
}
variable "object_storage_secret_key" {
description = "Object Storage secret key"
type = string
sensitive = true
}
variable "environment" {
description = "Deployment environment (staging or production)"
type = string
validation {
condition = contains(["staging", "production"], var.environment)
error_message = "Environment must be 'staging' or 'production'."
}
}
variable "tags" {
description = "Common tags for all resources"
type = map(string)
default = {
ManagedBy = "terraform"
Project = "hapi"
}
}
+21
View File
@@ -0,0 +1,21 @@
# Main Terraform configuration for HAPI infrastructure
# This file orchestrates all infrastructure components
# Provider configurations are in providers.tf
# Modules
module "postgres" {
source = "./postgres"
}
module "storage" {
source = "./storage"
}
module "network" {
source = "./network"
}
# Backend configuration for Terraform state
# State will be stored in Linode Object Storage
# Backend configuration is defined in infra/backend/
+120
View File
@@ -0,0 +1,120 @@
# Networking module for HAPI
# Creates firewall rules for API, PostgreSQL, and Adminer
resource "linode_firewall" "hapi" {
label = "hapi-firewall"
tags = var.tags
# Inbound rules
inbound = [
{
label = "allow-api"
protocol = "tcp"
ports = "8000"
cidrs = ["0.0.0.0/0", "::/0"]
},
{
label = "allow-postgres"
protocol = "tcp"
ports = "5432"
cidrs = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]
},
{
label = "allow-adminer"
protocol = "tcp"
ports = "8080"
cidrs = ["0.0.0.0/0", "::/0"]
},
{
label = "allow-https"
protocol = "tcp"
ports = "443"
cidrs = ["0.0.0.0/0", "::/0"]
},
{
label = "allow-http"
protocol = "tcp"
ports = "80"
cidrs = ["0.0.0.0/0", "::/0"]
}
]
# Outbound rules
outbound = [
{
label = "allow-all-outbound"
protocol = "tcp"
ports = "0-65535"
cidrs = ["0.0.0.0/0", "::/0"]
}
]
}
resource "linode_firewall_rule" "api_health" {
for_each = toset(["staging", "production"])
firewall_id = linode_firewall.hapi.id
label = "api-health-${each.key}"
direction = "inbound"
protocol = "tcp"
ports = "8000"
cidrs = ["0.0.0.0/0", "::/0"]
}
resource "linode_firewall_rule" "adminer_access" {
for_each = toset(["staging", "production"])
firewall_id = linode_firewall.hapi.id
label = "adminer-${each.key}"
direction = "inbound"
protocol = "tcp"
ports = "8080"
cidrs = ["0.0.0.0/0", "::/0"]
}
# Firewall rule configurations
locals {
firewall_config = {
staging = {
api_port = 8000
postgres_port = 5432
adminer_port = 8080
}
production = {
api_port = 8000
postgres_port = 5432
adminer_port = 8080
}
}
}
output "firewall_rules" {
description = "Firewall rules configuration"
value = {
api = {
port = 8000
protocol = "tcp"
cidrs = ["0.0.0.0/0", "::/0"]
}
postgres = {
port = 5432
protocol = "tcp"
cidrs = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]
}
adminer = {
port = 8080
protocol = "tcp"
cidrs = ["0.0.0.0/0", "::/0"]
}
}
}
output "firewall_id" {
description = "ID of the main firewall"
value = linode_firewall.hapi.id
}
output "firewall_label" {
description = "Label of the main firewall"
value = linode_firewall.hapi.label
}
+3
View File
@@ -0,0 +1,3 @@
# Network module variables
linode_region = "us-east"
environment = "staging"
+25
View File
@@ -0,0 +1,25 @@
# Variables for Networking module
variable "linode_region" {
description = "Linode region for networking resources"
type = string
default = "us-east"
}
variable "tags" {
description = "Common tags for all resources"
type = map(string)
default = {
ManagedBy = "terraform"
Project = "hapi"
}
}
variable "environment" {
description = "Deployment environment (staging or production)"
type = string
validation {
condition = contains(["staging", "production"], var.environment)
error_message = "Environment must be 'staging' or 'production'."
}
}
+57
View File
@@ -0,0 +1,57 @@
# Outputs for HAPI Terraform infrastructure
output "postgres_endpoint" {
description = "PostgreSQL endpoint for the environment"
value = module.postgres.endpoint
}
output "postgres_port" {
description = "PostgreSQL port"
value = module.postgres.port
}
output "postgres_database" {
description = "PostgreSQL database name"
value = module.postgres.database
}
output "postgres_username" {
description = "PostgreSQL username"
value = module.postgres.username
}
output "postgres_password" {
description = "PostgreSQL password (sensitive)"
value = module.postgres.password
sensitive = true
}
output "object_storage_endpoint" {
description = "Object Storage endpoint"
value = module.storage.endpoint
}
output "object_storage_access_key" {
description = "Object Storage access key"
value = module.storage.access_key
}
output "object_storage_secret_key" {
description = "Object Storage secret key (sensitive)"
value = module.storage.secret_key
sensitive = true
}
output "firewall_rules" {
description = "Firewall rules configuration"
value = module.network.firewall_rules
}
output "terraform_backend_config" {
description = "Configuration for Terraform backend in Object Storage"
value = {
bucket = module.storage.state_bucket_name
key = "terraform/${var.environment}/terraform.tfstate"
region = var.linode_region
}
}
+76
View File
@@ -0,0 +1,76 @@
# PostgreSQL module for HAPI
# Creates separate database instances for staging and production
# Object Storage buckets for PostgreSQL state
resource "linode_object_storage_bucket" "state" {
for_each = toset(["staging", "production"])
label = "hapi-postgres-state-${each.key}"
cluster = var.linode_object_storage_cluster
access_key = var.object_storage_access_key
secret_key = var.object_storage_secret_key
}
resource "linode_lke_cluster" "postgres" {
for_each = toset(["staging", "production"])
region = var.linode_region
label = "hapi-postgres-${each.key}"
k8s_version = var.linode_lke_version
tags = merge(var.tags, { Environment = each.key })
pools {
count = each.key == "production" ? 2 : 1
type = var.linode_node_type
}
}
# Database configuration
locals {
databases = {
staging = {
name = "hapi_staging"
pool_size = 2
}
production = {
name = "hapi_production"
pool_size = 3
}
}
}
output "endpoint" {
description = "PostgreSQL endpoint"
value = linode_lke_cluster.postgres[var.environment].hostname
}
output "port" {
description = "PostgreSQL port"
value = 5432
}
output "database" {
description = "PostgreSQL database name"
value = local.databases[var.environment].name
}
output "username" {
description = "PostgreSQL username"
value = "hapi_admin"
}
output "password" {
description = "PostgreSQL password"
value = random_string.password.result
sensitive = true
}
output "pool_size" {
description = "PostgreSQL connection pool size"
value = local.databases[var.environment].pool_size
}
output "state_bucket_name" {
description = "Name of the state bucket in Object Storage"
value = "hapi-postgres-state-${var.environment}"
}
+9
View File
@@ -0,0 +1,9 @@
# Random password for PostgreSQL
resource "random_string" "password" {
length = 32
upper = true
lower = true
numeric = true
special = false
}
+5
View File
@@ -0,0 +1,5 @@
# Postgres module variables
linode_region = "us-east"
linode_lke_version = "1.30"
linode_node_type = "g6-standard-4"
linode_object_storage_cluster = "us-east-1"
+45
View File
@@ -0,0 +1,45 @@
# Variables for PostgreSQL module
variable "linode_region" {
description = "Linode region for PostgreSQL"
type = string
default = "us-east"
}
variable "linode_lke_version" {
description = "Linode Kubernetes Engine version"
type = string
default = "1.30"
}
variable "linode_node_type" {
description = "Linode node type for PostgreSQL pools"
type = string
default = "g6-standard-4"
}
variable "linode_object_storage_cluster" {
description = "Linode Object Storage cluster"
type = string
default = "us-east-1"
}
variable "object_storage_access_key" {
description = "Object Storage access key"
type = string
}
variable "object_storage_secret_key" {
description = "Object Storage secret key"
type = string
sensitive = true
}
variable "tags" {
description = "Common tags for all resources"
type = map(string)
default = {
ManagedBy = "terraform"
Project = "hapi"
}
}
+8
View File
@@ -0,0 +1,8 @@
# Provider configurations for HAPI Terraform infrastructure
provider "linode" {
token = var.linode_token
region = var.linode_region
}
provider "random" {}
+97
View File
@@ -0,0 +1,97 @@
# Object Storage module for HAPI
# Creates buckets for uploads and Terraform state
resource "linode_object_storage_bucket" "uploads" {
for_each = toset(["staging", "production"])
label = "hapi-uploads-${each.key}"
cluster = var.linode_object_storage_cluster
access_key = var.object_storage_access_key
secret_key = var.object_storage_secret_key
depends_on = [linode_object_storage_cluster.this]
}
resource "linode_object_storage_bucket" "state" {
for_each = toset(["staging", "production"])
label = "hapi-terraform-state-${each.key}"
cluster = var.linode_object_storage_cluster
access_key = var.object_storage_access_key
secret_key = var.object_storage_secret_key
depends_on = [linode_object_storage_cluster.this]
}
resource "linode_object_storage_cluster" "this" {
label = "hapi-object-storage"
region = var.linode_region
}
# Bucket configurations
locals {
bucket_config = {
staging = {
uploads = {
label = "hapi-uploads-staging"
policy = jsonencode({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "AWS": ["*"] },
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": ["arn:aws:s3:::hapi-uploads-staging/*"]
}
]
})
}
state = {
label = "hapi-terraform-state-staging"
}
}
production = {
uploads = {
label = "hapi-uploads-production"
policy = jsonencode({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "AWS": ["*"] },
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": ["arn:aws:s3:::hapi-uploads-production/*"]
}
]
})
}
state = {
label = "hapi-terraform-state-production"
}
}
}
}
output "endpoint" {
description = "Object Storage endpoint"
value = "https://${var.linode_region}.linodeobjects.com"
}
output "access_key" {
description = "Object Storage access key"
value = var.object_storage_access_key
}
output "secret_key" {
description = "Object Storage secret key"
value = var.object_storage_secret_key
sensitive = true
}
output "state_bucket_name" {
description = "Name of the Terraform state bucket"
value = "hapi-terraform-state-${var.environment}"
}
output "uploads_bucket_name" {
description = "Name of the uploads bucket"
value = "hapi-uploads-${var.environment}"
}
+6
View File
@@ -0,0 +1,6 @@
# Storage module variables
linode_region = "us-east"
linode_object_storage_cluster = "us-east-1"
object_storage_access_key = "your-access-key"
object_storage_secret_key = "your-secret-key"
environment = "staging"
+42
View File
@@ -0,0 +1,42 @@
# Variables for Object Storage module
variable "linode_region" {
description = "Linode region for Object Storage"
type = string
default = "us-east"
}
variable "linode_object_storage_cluster" {
description = "Linode Object Storage cluster"
type = string
default = "us-east-1"
}
variable "object_storage_access_key" {
description = "Object Storage access key"
type = string
}
variable "object_storage_secret_key" {
description = "Object Storage secret key"
type = string
sensitive = true
}
variable "environment" {
description = "Deployment environment (staging or production)"
type = string
validation {
condition = contains(["staging", "production"], var.environment)
error_message = "Environment must be 'staging' or 'production'."
}
}
variable "tags" {
description = "Common tags for all resources"
type = map(string)
default = {
ManagedBy = "terraform"
Project = "hapi"
}
}
+38
View File
@@ -0,0 +1,38 @@
# Variables for HAPI Terraform infrastructure
variable "linode_token" {
description = "Linode API token for authentication"
type = string
sensitive = true
}
variable "linode_region" {
description = "Default Linode region for resources"
type = string
default = "us-east"
}
variable "environment" {
description = "Deployment environment (staging or production)"
type = string
default = "staging"
validation {
condition = contains(["staging", "production"], var.environment)
error_message = "Environment must be 'staging' or 'production'."
}
}
variable "project_name" {
description = "Name of the HAPI project"
type = string
default = "hapi"
}
variable "tags" {
description = "Common tags for all resources"
type = map(string)
default = {
ManagedBy = "terraform"
Project = "hapi"
}
}
-13
View File
@@ -1,13 +0,0 @@
# List recipes.
default:
@just --list
# Run the test suite.
test *args:
uv run pytest {{args}}
# Ruff (lint + format check) and pyright strict.
lint:
uv run ruff check .
uv run ruff format --check .
uv run pyright
-52
View File
@@ -1,52 +0,0 @@
[project]
name = "hapi"
version = "0.1.0"
description = "Personal, cloud-hosted API for one Household and its automations"
readme = "README.md"
requires-python = ">=3.14"
dependencies = [
"fastapi>=0.165.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/hapi"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
testpaths = ["tests"]
[tool.ruff]
line-length = 100
target-version = "py314"
src = ["src", "tests"]
[tool.ruff.lint]
select = [
"E", "W", "F", "I", "N", "UP", "B", "A", "C4", "DTZ", "S", "SIM", "PT",
"RET", "TID", "ASYNC", "PL", "RUF",
]
[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101", "S603", "PLR2004"]
[tool.pyright]
include = ["src", "tests"]
pythonVersion = "3.14"
typeCheckingMode = "strict"
venvPath = "."
venv = ".venv"
[dependency-groups]
dev = [
"httpx>=0.29.0",
"pyright>=1.1.414",
"pytest>=9.2.0",
"pytest-asyncio>=1.5.0",
"ruff>=0.17.6",
"rust-just>=1.59.0",
]
-1
View File
@@ -1 +0,0 @@
"""hAPI: a personal, cloud-hosted API for one Household and its automations."""
-17
View File
@@ -1,17 +0,0 @@
"""Composition root: builds the public API app and the internal probe app."""
from fastapi import FastAPI
from hapi.platform.health import probe_router
def create_api_app() -> FastAPI:
"""The public API on `:8000`, the only port the Gateway routes."""
return FastAPI(title="hAPI")
def create_probe_app() -> FastAPI:
"""The internal listener on `:8081`: probes only, never routed publicly."""
app = FastAPI(title="hAPI probes", openapi_url=None, docs_url=None, redoc_url=None)
app.include_router(probe_router)
return app
-1
View File
@@ -1 +0,0 @@
"""Shared platform code that every domain may import."""
-11
View File
@@ -1,11 +0,0 @@
"""Unauthenticated probes served only on the internal listener (ADR-0009)."""
from fastapi import APIRouter
probe_router = APIRouter()
@probe_router.get("/livez")
async def livez() -> dict[str, str]:
"""Constant: answering at all proves the shared event loop isn't wedged."""
return {"status": "ok"}
-26
View File
@@ -1,26 +0,0 @@
"""The internal `:8081` listener serves unauthenticated probes the public API never does."""
from httpx import ASGITransport, AsyncClient
from hapi.app import create_api_app, create_probe_app
async def test_livez_returns_constant_ok_on_the_probe_listener() -> None:
async with AsyncClient(
transport=ASGITransport(app=create_probe_app()), base_url="http://probes"
) as client:
first = await client.get("/livez")
second = await client.get("/livez")
assert first.status_code == 200
assert first.json() == {"status": "ok"}
assert second.json() == first.json()
async def test_livez_is_not_served_on_the_public_api() -> None:
async with AsyncClient(
transport=ASGITransport(app=create_api_app()), base_url="http://api"
) as client:
response = await client.get("/livez")
assert response.status_code == 404
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more