diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..6fa6df3 --- /dev/null +++ b/.env.example @@ -0,0 +1,8 @@ +DATABASE_URL=postgres://mercury:mercury@db:5432/mercury +JWT_SECRET=change_me_in_production +JWT_EXPIRY_SECS=3600 +CACHE_MAX_CAPACITY=10000 +CACHE_IDLE_TIMEOUT_SECS=300 +CACHE_SWEEP_INTERVAL_SECS=60 +# Comma-separated allowed CORS origins, or * for permissive. Empty = no CORS headers. +CORS_ORIGINS= diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml new file mode 100644 index 0000000..db6ed94 --- /dev/null +++ b/.forgejo/workflows/ci.yml @@ -0,0 +1,89 @@ +name: ci + +on: + push: + tags: + - 'v*' + pull_request: + +jobs: + test: + runs-on: self-hosted + container: git.mcpeakdev.com/mcpeakdev/rust-ci:latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Cache cargo registry + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: ${{ runner.os }}-cargo-${{ hashFiles('Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo- + + - name: Check formatting + run: cargo fmt --check + + - name: Clippy + run: cargo clippy -- -D warnings + + - name: Run tests + run: cargo test + + build-ui: + runs-on: self-hosted + container: git.mcpeakdev.com/mcpeakdev/bun-ci:latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install dependencies + run: bun install --frozen-lockfile + working-directory: ui + + - name: Audit dependencies + run: bun audit || true + working-directory: ui + + - name: Type check + run: bun run build + working-directory: ui + + publish: + needs: [test, build-ui] + if: startsWith(github.ref, 'refs/tags/v') + runs-on: self-hosted + container: git.mcpeakdev.com/mcpeakdev/docker-pub:latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to registry + uses: docker/login-action@v3 + with: + registry: git.mcpeakdev.com + username: ${{ github.actor }} + password: ${{ secrets.FORGEJO_TOKEN }} + + - name: Extract image tag + id: meta + run: echo "tag=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT" + + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile + push: true + tags: | + git.mcpeakdev.com/mcpeakdev/mercury:${{ steps.meta.outputs.tag }} + git.mcpeakdev.com/mcpeakdev/mercury:latest + cache-from: type=registry,ref=git.mcpeakdev.com/mcpeakdev/mercury:latest + cache-to: type=inline diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..8656b47 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "mercury" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "mercury" +path = "src/main.rs" + +[dependencies] +axum = { version = "0.7", features = ["macros"] } +tokio = { version = "1", features = ["full"] } +sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono", "migrate"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +jsonwebtoken = "9" +bcrypt = "0.15" +dashmap = "5" +glob = "0.3" +tower-http = { version = "0.5", features = ["fs", "cors"] } +tower = { version = "0.4", features = ["util"] } +uuid = { version = "1", features = ["v4", "serde"] } +chrono = { version = "0.4", features = ["serde"] } +dotenvy = "0.15" +anyhow = "1" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +sha2 = "0.10" + +[dev-dependencies] +tower = { version = "0.4", features = ["util"] } +http-body-util = "0.1" diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..fcf3464 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +# Stage 1: Build Vue UI +FROM oven/bun:1-alpine AS ui-builder +WORKDIR /ui +COPY ui/ . +RUN bun run build + +# Stage 2: Build Rust API +FROM rust:1.96-slim AS api-builder +RUN apt-get update && apt-get install -y pkg-config libssl-dev && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY Cargo.toml Cargo.lock ./ +COPY src/ src/ +RUN cargo build --release + +# Stage 3: Final image +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y ca-certificates libssl3 && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY --from=api-builder /app/target/release/mercury . +COPY --from=ui-builder /ui/dist ./ui/dist +EXPOSE 3000 +CMD ["./mercury"] diff --git a/README.md b/README.md index 8b09366..2781a6a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,174 @@ # Mercury -A learning rust API \ No newline at end of file +A high-performance, monolithic Rust API with a dynamic CRUD engine, query registry cache, JWT bitmask permissions, and a Vue 3 admin frontend. + +![Login](pics/Mercury-Login.png) +![Permissions](pics/Mercury.png) + +## Quick Start + +```bash +cp .env.example .env # set JWT_SECRET +docker compose up --build +``` + +API: http://localhost:3000/api +Admin UI: http://localhost:3000 +Default credentials: `admin` / `admin` + +--- + +## API Contract + +### Authentication + +``` +POST /auth/login +Body: { "username": "...", "password": "..." } +Returns: { "token": "" } +``` + +All admin routes require `Authorization: Bearer `. + +--- + +### CRUD — Dynamic Table Access + +Requests are mapped to the named PostgreSQL table. The SQL is generated, cached, and executed automatically. + +``` +GET /api/{table} List all rows (supports ?col=val filters) +GET /api/{table}/{id} Get row by id +POST /api/{table} Insert row (JSON body) +PUT /api/{table}/{id} Update row by id (JSON body) +DELETE /api/{table}/{id} Delete row by id +``` + +**Notes:** +- `users` and `permissions` tables are blacklisted from public CRUD — use the admin suite. +- Filters are ANDed together: `GET /api/orders?status=open&priority=high` + +--- + +### Admin — Query Registry + +Requires JWT with `ADMIN_QUERY` permission (bit 8). + +``` +GET /admin/queries List all registered queries +POST /admin/queries Register a raw SQL template +GET /admin/queries/{identifier} Get query by slug +PUT /admin/queries/{identifier} Update SQL template or description +DELETE /admin/queries/{identifier} Remove query (evicts from cache) +GET /admin/queries/{identifier}/execute Execute query with ?param=val bindings +``` + +SQL templates use `:param_name` placeholders: +```sql +SELECT * FROM orders WHERE user_id = :user_id AND status = :status +``` + +--- + +### Admin — Cache + +Requires JWT with `ADMIN_CACHE` permission (bit 16). + +``` +GET /admin/cache/stats Cache size, hit count, miss count +DELETE /admin/cache Flush entire cache +``` + +--- + +### Admin — Users + +Requires JWT with `SUPER_ADMIN` permission (bit 32). + +``` +GET /admin/users List users +POST /admin/users Create user +GET /admin/users/{id} Get user +PUT /admin/users/{id} Update user +DELETE /admin/users/{id} Delete user +POST /admin/users/{id}/permissions/grant/{bit} OR bit into permissions mask +DELETE /admin/users/{id}/permissions/revoke/{bit} AND NOT bit from permissions mask +``` + +--- + +### Admin — Permissions + +Requires JWT with `SUPER_ADMIN` permission (bit 32). + +``` +GET /admin/permissions List permission definitions +POST /admin/permissions Create custom permission (auto-assigns next bit) +PUT /admin/permissions/{id} Update name/description +DELETE /admin/permissions/{id} Remove permission +``` + +--- + +### Admin — Route Blacklist + +Requires JWT with `SUPER_ADMIN` permission (bit 32). Changes take effect immediately in memory. + +``` +GET /admin/blacklist List all entries +POST /admin/blacklist Add glob pattern +PUT /admin/blacklist/{id} Update entry (set active: false to disable) +DELETE /admin/blacklist/{id} Remove entry +``` + +Pattern syntax: `*` matches one path segment, `**` matches many. +Example: `/api/sensitive/**` blocks all methods under that path. + +--- + +## Permission Bitmask + +| Name | Bit | Value | +|-------------|-----|-------| +| READ | 0 | 1 | +| WRITE | 1 | 2 | +| DELETE | 2 | 4 | +| ADMIN_QUERY | 3 | 8 | +| ADMIN_CACHE | 4 | 16 | +| SUPER_ADMIN | 5 | 32 | + +Custom permissions are added via the admin suite and assigned the next available power-of-2 bit. Masks support up to 128 bits (u128). + +--- + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `DATABASE_URL` | required | PostgreSQL connection string | +| `JWT_SECRET` | required | HMAC-HS256 signing secret | +| `JWT_EXPIRY_SECS` | 3600 | Token lifetime in seconds | +| `CACHE_MAX_CAPACITY` | 10000 | Max query templates in memory | +| `CACHE_IDLE_TIMEOUT_SECS` | 300 | Evict after N seconds idle | +| `CACHE_SWEEP_INTERVAL_SECS` | 60 | Sweep interval for eviction task | + +--- + +## Development + +```bash +# API only (requires local Postgres) +cargo run + +# UI dev server (proxies to local API) +cd ui && npm install && npm run dev + +# Full stack +docker compose up --build +``` + +## Stack + +- **API:** Rust, Axum, SQLx, PostgreSQL, DashMap, jsonwebtoken, bcrypt +- **Frontend:** Vue 3, Vite, @nychthemeron/library (dark mode default) +- **Infra:** Docker multi-stage build, docker compose diff --git a/dev.sh b/dev.sh new file mode 100755 index 0000000..b959777 --- /dev/null +++ b/dev.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +cd $SCRIPT_DIR/ui/ && bun i + +cd "$SCRIPT_DIR" + +cleanup() { + docker compose down +} +trap cleanup INT TERM + +docker compose up --build diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml new file mode 100644 index 0000000..96aa935 --- /dev/null +++ b/docker-compose.dev.yml @@ -0,0 +1,4 @@ +# Reserved for future dev overrides. +# Port mapping omitted — dev.sh connects to the container's internal IP directly +# to avoid Docker Desktop WSL2 port-forwarding limitations. +services: {} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..d80bc76 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,34 @@ +services: + db: + image: postgres:16-alpine + environment: + POSTGRES_USER: mercury + POSTGRES_PASSWORD: mercury + POSTGRES_DB: mercury + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U mercury"] + interval: 5s + timeout: 5s + retries: 5 + + api: + build: . + ports: + - "3000:3000" + environment: + DATABASE_URL: postgres://mercury:mercury@db:5432/mercury + JWT_SECRET: ${JWT_SECRET:-change_me_in_production} + JWT_EXPIRY_SECS: ${JWT_EXPIRY_SECS:-3600} + CACHE_MAX_CAPACITY: ${CACHE_MAX_CAPACITY:-10000} + CACHE_IDLE_TIMEOUT_SECS: ${CACHE_IDLE_TIMEOUT_SECS:-300} + CACHE_SWEEP_INTERVAL_SECS: ${CACHE_SWEEP_INTERVAL_SECS:-60} + depends_on: + db: + condition: service_healthy + mem_limit: 512m + mem_reservation: 256m + +volumes: + postgres_data: diff --git a/docs/superpowers/plans/2026-06-16-mercury-implementation.md b/docs/superpowers/plans/2026-06-16-mercury-implementation.md new file mode 100644 index 0000000..98a116f --- /dev/null +++ b/docs/superpowers/plans/2026-06-16-mercury-implementation.md @@ -0,0 +1,3438 @@ +# Mercury Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build Mercury — a monolithic Rust API with dynamic CRUD, a JWT bitmask permission system, a query registry cache, an admin suite, and a Vue 3 frontend — runnable via a single `docker compose up`. + +**Architecture:** Axum handles HTTP routing behind two middleware layers: a glob-based blacklist check and a JWT permission-bit validator. The CRUD engine auto-generates parameterized SQL from route + HTTP method, caches templates in a DashMap with TTI eviction, and persists named queries in PostgreSQL. Vue 3 is built by Vite and served as static files by `tower-http::ServeDir`. + +**Tech Stack:** Rust 1.75+, Axum 0.7, SQLx 0.7, PostgreSQL 16, DashMap 5, glob 0.3, jsonwebtoken 9, bcrypt 0.15, Vue 3, Vite, @nychthemeron/library, tower-http 0.5, Docker multi-stage build. + +--- + +## File Map + +``` +Mercury/ + Cargo.toml + .env.example + Dockerfile + docker-compose.yml + README.md + src/ + main.rs startup: config, pool, caches, router, static files + config.rs Config struct from env vars + state.rs AppState, QueryCache, BlacklistCache types + auth/ + mod.rs JWT Claims, encode/decode helpers + middleware.rs RequirePermission extractor + cache/ + mod.rs pub use re-exports + query_cache.rs DashMap + sweep task + hit/miss counters + blacklist_cache.rs Arc>> + reload fn + db/ + mod.rs pub use re-exports + pool.rs PgPool init + run migrations + migrations/ + 001_initial.sql schema, seed permissions, seed blacklist + models/ + mod.rs pub use re-exports + user.rs User, CreateUser, UpdateUser + permission.rs Permission, CreatePermission, UpdatePermission + query.rs StoredQuery, CreateQuery, UpdateQuery + blacklist.rs BlacklistEntry, CreateBlacklistEntry, UpdateBlacklistEntry + routes/ + mod.rs pub use re-exports + auth.rs POST /auth/login + crud.rs generic /api/{table} + query builder + row→JSON + admin/ + mod.rs admin Router assembly + queries.rs query registry CRUD + cache.rs cache stats + flush + users.rs user management + grant/revoke + permissions.rs permission definitions CRUD + blacklist.rs blacklist CRUD + trigger reload + ui/ + .npmrc + package.json + vite.config.ts + src/ + main.ts + App.vue + router/index.ts + stores/auth.ts + views/ + Login.vue + admin/ + Layout.vue + Queries.vue + Users.vue + Permissions.vue + Blacklist.vue + Cache.vue + tests/ + integration/ + auth_test.rs + crud_test.rs + admin_test.rs +``` + +--- + +## Task 1: Cargo.toml + project skeleton + +**Files:** +- Create: `Cargo.toml` +- Create: `src/main.rs` (stub) + +- [ ] **Step 1: Write Cargo.toml** + +```toml +[package] +name = "mercury" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "mercury" +path = "src/main.rs" + +[dependencies] +axum = { version = "0.7", features = ["macros"] } +tokio = { version = "1", features = ["full"] } +sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono", "migrate"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +jsonwebtoken = "9" +bcrypt = "0.15" +dashmap = "5" +glob = "0.3" +tower-http = { version = "0.5", features = ["fs", "cors"] } +tower = { version = "0.4", features = ["util"] } +uuid = { version = "1", features = ["v4", "serde"] } +chrono = { version = "0.4", features = ["serde"] } +dotenvy = "0.15" +anyhow = "1" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } + +[dev-dependencies] +tower = { version = "0.4", features = ["util"] } +http-body-util = "0.1" +``` + +- [ ] **Step 2: Write src/main.rs stub** + +```rust +#[tokio::main] +async fn main() { + println!("Mercury starting..."); +} +``` + +- [ ] **Step 3: Verify it compiles** + +```bash +cargo build +``` +Expected: `Compiling mercury v0.1.0` then `Finished`. + +- [ ] **Step 4: Commit** + +```bash +git add Cargo.toml src/main.rs +git commit -m "chore: init Mercury project scaffold" +``` + +--- + +## Task 2: Config + +**Files:** +- Create: `src/config.rs` +- Create: `.env.example` + +- [ ] **Step 1: Write failing test** + +In `src/config.rs`: + +```rust +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_config_defaults() { + std::env::set_var("DATABASE_URL", "postgres://test"); + std::env::set_var("JWT_SECRET", "secret"); + let cfg = Config::from_env().unwrap(); + assert_eq!(cfg.jwt_expiry_secs, 3600); + assert_eq!(cfg.cache_max_capacity, 10_000); + assert_eq!(cfg.cache_idle_timeout_secs, 300); + assert_eq!(cfg.cache_sweep_interval_secs, 60); + } +} +``` + +- [ ] **Step 2: Run test — expect compile failure** + +```bash +cargo test config +``` +Expected: `error[E0433]: failed to resolve: use of undeclared crate or module` + +- [ ] **Step 3: Implement Config** + +```rust +use anyhow::Result; + +#[derive(Clone, Debug)] +pub struct Config { + pub database_url: String, + pub jwt_secret: String, + pub jwt_expiry_secs: u64, + pub cache_max_capacity: usize, + pub cache_idle_timeout_secs: u64, + pub cache_sweep_interval_secs: u64, +} + +impl Config { + pub fn from_env() -> Result { + Ok(Self { + database_url: std::env::var("DATABASE_URL")?, + jwt_secret: std::env::var("JWT_SECRET")?, + jwt_expiry_secs: std::env::var("JWT_EXPIRY_SECS") + .unwrap_or_else(|_| "3600".into()) + .parse()?, + cache_max_capacity: std::env::var("CACHE_MAX_CAPACITY") + .unwrap_or_else(|_| "10000".into()) + .parse()?, + cache_idle_timeout_secs: std::env::var("CACHE_IDLE_TIMEOUT_SECS") + .unwrap_or_else(|_| "300".into()) + .parse()?, + cache_sweep_interval_secs: std::env::var("CACHE_SWEEP_INTERVAL_SECS") + .unwrap_or_else(|_| "60".into()) + .parse()?, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_config_defaults() { + std::env::set_var("DATABASE_URL", "postgres://test"); + std::env::set_var("JWT_SECRET", "secret"); + let cfg = Config::from_env().unwrap(); + assert_eq!(cfg.jwt_expiry_secs, 3600); + assert_eq!(cfg.cache_max_capacity, 10_000); + assert_eq!(cfg.cache_idle_timeout_secs, 300); + assert_eq!(cfg.cache_sweep_interval_secs, 60); + } +} +``` + +- [ ] **Step 4: Add to main.rs and run test** + +Add `mod config;` to `src/main.rs`. Then: + +```bash +cargo test config +``` +Expected: `test config::tests::test_config_defaults ... ok` + +- [ ] **Step 5: Write .env.example** + +```env +DATABASE_URL=postgres://mercury:mercury@db:5432/mercury +JWT_SECRET=change_me_in_production +JWT_EXPIRY_SECS=3600 +CACHE_MAX_CAPACITY=10000 +CACHE_IDLE_TIMEOUT_SECS=300 +CACHE_SWEEP_INTERVAL_SECS=60 +``` + +- [ ] **Step 6: Commit** + +```bash +git add src/config.rs src/main.rs .env.example +git commit -m "feat: add Config struct loaded from env vars" +``` + +--- + +## Task 3: Models + +**Files:** +- Create: `src/models/mod.rs` +- Create: `src/models/user.rs` +- Create: `src/models/permission.rs` +- Create: `src/models/query.rs` +- Create: `src/models/blacklist.rs` + +- [ ] **Step 1: Write src/models/user.rs** + +```rust +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct User { + pub id: i32, + pub username: String, + #[serde(skip_serializing)] + pub password_hash: String, + pub permissions_mask: String, + pub created_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateUser { + pub username: String, + pub password: String, + pub permissions_mask: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateUser { + pub username: Option, + pub password: Option, + pub permissions_mask: Option, +} + +#[derive(Debug, Deserialize)] +pub struct LoginRequest { + pub username: String, + pub password: String, +} +``` + +- [ ] **Step 2: Write src/models/permission.rs** + +```rust +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct Permission { + pub id: i32, + pub name: String, + pub bit_value: String, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct CreatePermission { + pub name: String, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdatePermission { + pub name: Option, + pub description: Option, +} +``` + +- [ ] **Step 3: Write src/models/query.rs** + +```rust +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct StoredQuery { + pub id: Uuid, + pub identifier: String, + pub sql_template: String, + pub description: Option, + pub created_at: DateTime, + pub updated_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateQuery { + pub identifier: String, + pub sql_template: String, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateQuery { + pub sql_template: Option, + pub description: Option, +} +``` + +- [ ] **Step 4: Write src/models/blacklist.rs** + +```rust +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct BlacklistEntry { + pub id: i32, + pub pattern: String, + pub method: Option, + pub reason: Option, + pub active: bool, + pub created_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateBlacklistEntry { + pub pattern: String, + pub method: Option, + pub reason: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateBlacklistEntry { + pub pattern: Option, + pub method: Option, + pub reason: Option, + pub active: Option, +} +``` + +- [ ] **Step 5: Write src/models/mod.rs** + +```rust +pub mod blacklist; +pub mod permission; +pub mod query; +pub mod user; +``` + +- [ ] **Step 6: Add mod to main.rs and compile** + +Add `mod models;` to `src/main.rs`. + +```bash +cargo build +``` +Expected: `Finished` with no errors. + +- [ ] **Step 7: Commit** + +```bash +git add src/models/ +git commit -m "feat: add domain models for user, permission, query, blacklist" +``` + +--- + +## Task 4: Database pool + migration + +**Files:** +- Create: `src/db/mod.rs` +- Create: `src/db/pool.rs` +- Create: `src/db/migrations/001_initial.sql` + +- [ ] **Step 1: Write src/db/migrations/001_initial.sql** + +```sql +CREATE EXTENSION IF NOT EXISTS pgcrypto; + +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + username VARCHAR(255) UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + permissions_mask TEXT NOT NULL DEFAULT '0', + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE permissions ( + id SERIAL PRIMARY KEY, + name VARCHAR(255) UNIQUE NOT NULL, + bit_value TEXT UNIQUE NOT NULL, + description TEXT +); + +CREATE TABLE queries ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + identifier VARCHAR(255) UNIQUE NOT NULL, + sql_template TEXT NOT NULL, + description TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE blacklist ( + id SERIAL PRIMARY KEY, + pattern VARCHAR(500) NOT NULL, + method VARCHAR(10), + reason TEXT, + active BOOLEAN NOT NULL DEFAULT true, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Seed permissions +INSERT INTO permissions (name, bit_value, description) VALUES + ('READ', '1', 'Can read via CRUD endpoints'), + ('WRITE', '2', 'Can insert/update via CRUD'), + ('DELETE', '4', 'Can delete via CRUD'), + ('ADMIN_QUERY', '8', 'Can manage query registry'), + ('ADMIN_CACHE', '16', 'Can manage cache'), + ('SUPER_ADMIN', '32', 'Full access'); + +-- Seed blacklist (users and permissions tables are admin-only) +INSERT INTO blacklist (pattern, method, reason, active) VALUES + ('/api/users/**', NULL, 'admin-only table', true), + ('/api/permissions/**', NULL, 'admin-only table', true); +``` + +- [ ] **Step 2: Write src/db/pool.rs** + +```rust +use anyhow::Result; +use sqlx::{postgres::PgPoolOptions, PgPool}; + +pub async fn create_pool(database_url: &str) -> Result { + let pool = PgPoolOptions::new() + .max_connections(10) + .connect(database_url) + .await?; + sqlx::migrate!("src/db/migrations").run(&pool).await?; + Ok(pool) +} +``` + +- [ ] **Step 3: Write src/db/mod.rs** + +```rust +pub mod pool; +pub use pool::create_pool; +``` + +- [ ] **Step 4: Add mod to main.rs and compile** + +Add `mod db;` to `src/main.rs`. + +```bash +cargo build +``` +Expected: `Finished` with no errors. + +- [ ] **Step 5: Commit** + +```bash +git add src/db/ +git commit -m "feat: add database pool and initial migration" +``` + +--- + +## Task 5: AppState + +**Files:** +- Create: `src/state.rs` + +- [ ] **Step 1: Write src/state.rs** + +```rust +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, +}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use dashmap::DashMap; +use glob::Pattern; +use sqlx::PgPool; +use tokio::sync::RwLock; + +use crate::config::Config; +use crate::models::blacklist::BlacklistEntry; + +pub fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() +} + +#[derive(Clone)] +pub struct AppState { + pub pool: PgPool, + pub query_cache: QueryCache, + pub blacklist_cache: BlacklistCache, + pub config: Arc, +} + +#[derive(Clone)] +pub struct QueryCache { + pub map: Arc>, + pub hits: Arc, + pub misses: Arc, +} + +#[derive(Clone, Debug)] +pub struct CacheEntry { + pub sql: String, + pub param_order: Vec, + pub last_accessed_secs: Arc, +} + +impl CacheEntry { + pub fn new(sql: String, param_order: Vec) -> Self { + Self { + sql, + param_order, + last_accessed_secs: Arc::new(AtomicU64::new(unix_now())), + } + } + + pub fn touch(&self) { + self.last_accessed_secs.store(unix_now(), Ordering::Relaxed); + } + + pub fn last_accessed(&self) -> u64 { + self.last_accessed_secs.load(Ordering::Relaxed) + } +} + +impl QueryCache { + pub fn new() -> Self { + Self { + map: Arc::new(DashMap::new()), + hits: Arc::new(AtomicU64::new(0)), + misses: Arc::new(AtomicU64::new(0)), + } + } + + pub fn get(&self, key: &str) -> Option { + if let Some(entry) = self.map.get(key) { + entry.touch(); + self.hits.fetch_add(1, Ordering::Relaxed); + Some(entry.clone()) + } else { + self.misses.fetch_add(1, Ordering::Relaxed); + None + } + } + + pub fn insert(&self, key: String, entry: CacheEntry, max_capacity: usize) { + if self.map.len() >= max_capacity { + let oldest_key = self + .map + .iter() + .min_by_key(|e| e.last_accessed()) + .map(|e| e.key().clone()); + if let Some(k) = oldest_key { + self.map.remove(&k); + } + } + self.map.insert(key, entry); + } + + pub fn remove(&self, key: &str) { + self.map.remove(key); + } + + pub fn hits(&self) -> u64 { + self.hits.load(Ordering::Relaxed) + } + + pub fn misses(&self) -> u64 { + self.misses.load(Ordering::Relaxed) + } + + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn flush(&self) { + self.map.clear(); + } +} + +#[derive(Clone)] +pub struct BlacklistCache { + pub inner: Arc>>, +} + +#[derive(Clone)] +pub struct CompiledEntry { + pub entry: BlacklistEntry, + pub pattern: Pattern, +} + +impl BlacklistCache { + pub fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(Vec::new())), + } + } + + pub async fn load(&self, entries: Vec) { + let compiled: Vec = entries + .into_iter() + .filter_map(|e| { + Pattern::new(&e.pattern) + .ok() + .map(|pattern| CompiledEntry { entry: e, pattern }) + }) + .collect(); + let mut guard = self.inner.write().await; + *guard = compiled; + } + + pub async fn is_blocked(&self, method: &str, path: &str) -> bool { + let guard = self.inner.read().await; + guard.iter().any(|compiled| { + if !compiled.entry.active { + return false; + } + let method_matches = compiled + .entry + .method + .as_deref() + .map(|m| m.eq_ignore_ascii_case(method)) + .unwrap_or(true); + method_matches && compiled.pattern.matches(path) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_cache_insert_and_get() { + let cache = QueryCache::new(); + let entry = CacheEntry::new("SELECT 1".into(), vec![]); + cache.insert("key1".into(), entry, 100); + let got = cache.get("key1"); + assert!(got.is_some()); + assert_eq!(got.unwrap().sql, "SELECT 1"); + assert_eq!(cache.hits(), 1); + assert_eq!(cache.misses(), 0); + } + + #[test] + fn test_cache_miss() { + let cache = QueryCache::new(); + let got = cache.get("missing"); + assert!(got.is_none()); + assert_eq!(cache.misses(), 1); + } + + #[test] + fn test_cache_capacity_evicts_oldest() { + let cache = QueryCache::new(); + let e1 = CacheEntry::new("SELECT 1".into(), vec![]); + // force e1 to be older + e1.last_accessed_secs.store(1, Ordering::Relaxed); + cache.map.insert("old".into(), e1); + let e2 = CacheEntry::new("SELECT 2".into(), vec![]); + cache.insert("new".into(), e2, 1); // capacity=1, should evict "old" + assert!(cache.map.get("old").is_none()); + assert!(cache.map.get("new").is_some()); + } + + #[tokio::test] + async fn test_blacklist_blocks_pattern() { + use chrono::Utc; + let cache = BlacklistCache::new(); + let entry = BlacklistEntry { + id: 1, + pattern: "/api/users/**".into(), + method: None, + reason: None, + active: true, + created_at: Utc::now(), + }; + cache.load(vec![entry]).await; + assert!(cache.is_blocked("GET", "/api/users/42").await); + assert!(!cache.is_blocked("GET", "/api/orders/1").await); + } + + #[tokio::test] + async fn test_blacklist_method_specific() { + use chrono::Utc; + let cache = BlacklistCache::new(); + let entry = BlacklistEntry { + id: 2, + pattern: "/api/secrets".into(), + method: Some("GET".into()), + reason: None, + active: true, + created_at: Utc::now(), + }; + cache.load(vec![entry]).await; + assert!(cache.is_blocked("GET", "/api/secrets").await); + assert!(!cache.is_blocked("POST", "/api/secrets").await); + } +} +``` + +- [ ] **Step 2: Add mod to main.rs** + +Add `mod state;` to `src/main.rs`. + +- [ ] **Step 3: Run tests** + +```bash +cargo test state +``` +Expected: 4 tests pass. + +- [ ] **Step 4: Commit** + +```bash +git add src/state.rs src/main.rs +git commit -m "feat: add AppState with QueryCache and BlacklistCache" +``` + +--- + +## Task 6: Cache sweep background task + +**Files:** +- Create: `src/cache/mod.rs` +- Create: `src/cache/sweep.rs` + +- [ ] **Step 1: Write src/cache/sweep.rs** + +```rust +use std::time::Duration; +use crate::state::QueryCache; + +pub fn spawn_sweep_task(cache: QueryCache, idle_timeout_secs: u64, sweep_interval_secs: u64) { + tokio::spawn(async move { + let interval = Duration::from_secs(sweep_interval_secs); + loop { + tokio::time::sleep(interval).await; + let now = crate::state::unix_now(); + cache.map.retain(|_, entry| { + now.saturating_sub(entry.last_accessed()) < idle_timeout_secs + }); + } + }); +} +``` + +- [ ] **Step 2: Write src/cache/mod.rs** + +```rust +pub mod sweep; +pub use sweep::spawn_sweep_task; +``` + +- [ ] **Step 3: Add mod to main.rs and compile** + +Add `mod cache;` to `src/main.rs`. + +```bash +cargo build +``` +Expected: `Finished` with no errors. + +- [ ] **Step 4: Commit** + +```bash +git add src/cache/ +git commit -m "feat: add cache sweep background task for TTI eviction" +``` + +--- + +## Task 7: JWT auth module + +**Files:** +- Create: `src/auth/mod.rs` + +- [ ] **Step 1: Write failing tests** + +```rust +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_encode_decode_roundtrip() { + let secret = "test_secret"; + let token = encode_jwt("alice", 63u128, secret, 3600).unwrap(); + let claims = decode_jwt(&token, secret).unwrap(); + assert_eq!(claims.sub, "alice"); + assert_eq!(claims.permissions_mask(), 63u128); + } + + #[test] + fn test_expired_token_rejected() { + let secret = "test_secret"; + let token = encode_jwt("alice", 1u128, secret, 0).unwrap(); + // exp=0 means already expired + let result = decode_jwt(&token, secret); + assert!(result.is_err()); + } +} +``` + +- [ ] **Step 2: Run test — expect compile failure** + +```bash +cargo test auth +``` + +- [ ] **Step 3: Implement src/auth/mod.rs** + +```rust +pub mod middleware; + +use anyhow::Result; +use chrono::Utc; +use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; +use serde::{Deserialize, Serialize}; + +pub mod permissions { + pub const READ: u128 = 1; + pub const WRITE: u128 = 2; + pub const DELETE: u128 = 4; + pub const ADMIN_QUERY: u128 = 8; + pub const ADMIN_CACHE: u128 = 16; + pub const SUPER_ADMIN: u128 = 32; +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Claims { + pub sub: String, + pub permissions: String, // u128 stored as decimal string + pub exp: usize, +} + +impl Claims { + pub fn permissions_mask(&self) -> u128 { + self.permissions.parse().unwrap_or(0) + } + + pub fn has_permission(&self, bit: u128) -> bool { + self.permissions_mask() & bit != 0 + } +} + +pub fn encode_jwt(username: &str, mask: u128, secret: &str, expiry_secs: u64) -> Result { + let exp = (Utc::now().timestamp() as u64 + expiry_secs) as usize; + let claims = Claims { + sub: username.to_string(), + permissions: mask.to_string(), + exp, + }; + let token = encode( + &Header::default(), + &claims, + &EncodingKey::from_secret(secret.as_bytes()), + )?; + Ok(token) +} + +pub fn decode_jwt(token: &str, secret: &str) -> Result { + let data = decode::( + token, + &DecodingKey::from_secret(secret.as_bytes()), + &Validation::default(), + )?; + Ok(data.claims) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_encode_decode_roundtrip() { + let secret = "test_secret"; + let token = encode_jwt("alice", 63u128, secret, 3600).unwrap(); + let claims = decode_jwt(&token, secret).unwrap(); + assert_eq!(claims.sub, "alice"); + assert_eq!(claims.permissions_mask(), 63u128); + } + + #[test] + fn test_has_permission() { + let claims = Claims { + sub: "bob".into(), + permissions: "9".into(), // READ (1) + ADMIN_QUERY (8) + exp: 9999999999, + }; + assert!(claims.has_permission(permissions::READ)); + assert!(claims.has_permission(permissions::ADMIN_QUERY)); + assert!(!claims.has_permission(permissions::SUPER_ADMIN)); + } +} +``` + +- [ ] **Step 4: Create stub for middleware (needed for mod declaration)** + +Create `src/auth/middleware.rs` as an empty stub: + +```rust +// filled in Task 8 +``` + +- [ ] **Step 5: Add mod to main.rs and run tests** + +Add `mod auth;` to `src/main.rs`. + +```bash +cargo test auth::tests +``` +Expected: 2 tests pass (`test_encode_decode_roundtrip`, `test_has_permission`). + +- [ ] **Step 6: Commit** + +```bash +git add src/auth/ +git commit -m "feat: add JWT encode/decode with u128 bitmask permissions" +``` + +--- + +## Task 8: Auth middleware + blacklist middleware + +**Files:** +- Modify: `src/auth/middleware.rs` + +- [ ] **Step 1: Write src/auth/middleware.rs** + +```rust +use axum::{ + extract::{Request, State}, + http::StatusCode, + middleware::Next, + response::Response, +}; + +use crate::{auth::decode_jwt, state::AppState}; + +pub async fn blacklist_layer( + State(state): State, + req: Request, + next: Next, +) -> Result { + let method = req.method().as_str().to_uppercase(); + let path = req.uri().path().to_string(); + if state.blacklist_cache.is_blocked(&method, &path).await { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub fn extract_bearer(req: &Request) -> Option { + req.headers() + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(|s| s.to_string()) +} + +pub async fn require_auth( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = decode_jwt(&token, &state.config.jwt_secret) + .map_err(|_| StatusCode::UNAUTHORIZED)?; + req.extensions_mut().insert(claims); + Ok(next.run(req).await) +} + +pub async fn require_super_admin( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = decode_jwt(&token, &state.config.jwt_secret) + .map_err(|_| StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::SUPER_ADMIN) { + return Err(StatusCode::FORBIDDEN); + } + req.extensions_mut().insert(claims); + Ok(next.run(req).await) +} + +pub async fn require_admin_query( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = decode_jwt(&token, &state.config.jwt_secret) + .map_err(|_| StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_QUERY) { + return Err(StatusCode::FORBIDDEN); + } + req.extensions_mut().insert(claims); + Ok(next.run(req).await) +} + +pub async fn require_admin_cache( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = decode_jwt(&token, &state.config.jwt_secret) + .map_err(|_| StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_CACHE) { + return Err(StatusCode::FORBIDDEN); + } + req.extensions_mut().insert(claims); + Ok(next.run(req).await) +} +``` + +- [ ] **Step 2: Compile** + +```bash +cargo build +``` +Expected: `Finished` with no errors. + +- [ ] **Step 3: Commit** + +```bash +git add src/auth/middleware.rs +git commit -m "feat: add blacklist and JWT permission middlewares" +``` + +--- + +## Task 9: Auth login route + +**Files:** +- Create: `src/routes/mod.rs` +- Create: `src/routes/auth.rs` + +- [ ] **Step 1: Write src/routes/auth.rs** + +```rust +use axum::{extract::State, http::StatusCode, Json}; +use serde_json::{json, Value}; + +use crate::{ + auth::encode_jwt, + models::user::LoginRequest, + state::AppState, +}; + +pub async fn login( + State(state): State, + Json(body): Json, +) -> Result, StatusCode> { + let user = sqlx::query_as!( + crate::models::user::User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE username = $1", + body.username + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::UNAUTHORIZED)?; + + let valid = bcrypt::verify(&body.password, &user.password_hash) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + if !valid { + return Err(StatusCode::UNAUTHORIZED); + } + + let mask: u128 = user.permissions_mask.parse().unwrap_or(0); + let token = encode_jwt(&user.username, mask, &state.config.jwt_secret, state.config.jwt_expiry_secs) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + Ok(Json(json!({ "token": token }))) +} +``` + +- [ ] **Step 2: Write src/routes/mod.rs** + +```rust +pub mod admin; +pub mod auth; +pub mod crud; +``` + +- [ ] **Step 3: Create stub files to satisfy mod declarations** + +Create `src/routes/crud.rs`: +```rust +// filled in Task 10 +``` + +Create `src/routes/admin/mod.rs`: +```rust +// filled in Task 15 +``` + +- [ ] **Step 4: Add mod to main.rs and compile** + +Add `mod routes;` to `src/main.rs`. + +```bash +cargo build +``` +Expected: `Finished`. + +- [ ] **Step 5: Commit** + +```bash +git add src/routes/ +git commit -m "feat: add /auth/login route with bcrypt verification" +``` + +--- + +## Task 10: CRUD route + query builder + +**Files:** +- Modify: `src/routes/crud.rs` + +- [ ] **Step 1: Write failing test** + +In `src/routes/crud.rs`: + +```rust +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_build_select_all() { + let (sql, params, key) = build_query("GET", "orders", None, &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders"); + assert!(params.is_empty()); + assert_eq!(key, "GET:orders:"); + } + + #[test] + fn test_build_select_by_id() { + let (sql, params, key) = build_query("GET", "orders", Some("42"), &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders WHERE id = $1"); + assert_eq!(params, vec!["42".to_string()]); + assert_eq!(key, "GET:orders:by_id"); + } + + #[test] + fn test_build_insert() { + let cols = vec![("email".into(), "a@b.com".into()), ("name".into(), "Alice".into())]; + let (sql, params, key) = build_query("POST", "users", None, &cols, &[]).unwrap(); + assert_eq!(sql, "INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *"); + assert_eq!(params, vec!["a@b.com", "Alice"]); + assert_eq!(key, "POST:users:email,name"); + } + + #[test] + fn test_build_update() { + let cols = vec![("name".into(), "Bob".into())]; + let (sql, params, key) = build_query("PUT", "users", Some("7"), &cols, &[]).unwrap(); + assert_eq!(sql, "UPDATE users SET name = $1 WHERE id = $2 RETURNING *"); + assert_eq!(params, vec!["Bob", "7"]); + assert_eq!(key, "PUT:users:name:by_id"); + } + + #[test] + fn test_build_delete() { + let (sql, params, key) = build_query("DELETE", "users", Some("3"), &[], &[]).unwrap(); + assert_eq!(sql, "DELETE FROM users WHERE id = $1"); + assert_eq!(params, vec!["3"]); + assert_eq!(key, "DELETE:users:by_id"); + } + + #[test] + fn test_build_select_with_filters() { + let filters = vec![("status".into(), "active".into()), ("role".into(), "admin".into())]; + let (sql, params, key) = build_query("GET", "users", None, &[], &filters).unwrap(); + assert_eq!(sql, "SELECT * FROM users WHERE role = $1 AND status = $2"); + assert_eq!(params, vec!["admin", "active"]); + assert_eq!(key, "GET:users:role,status"); + } + + #[test] + fn test_rejects_invalid_table_name() { + let result = build_query("GET", "users; DROP TABLE users--", None, &[], &[]); + assert!(result.is_err()); + } +} +``` + +- [ ] **Step 2: Run test — expect compile failure** + +```bash +cargo test crud +``` + +- [ ] **Step 3: Implement src/routes/crud.rs** + +```rust +use anyhow::{anyhow, Result}; +use axum::{ + extract::{Path, Query, State}, + http::{Method, StatusCode}, + Json, +}; +use serde_json::Value; +use sqlx::postgres::PgRow; +use sqlx::Row; +use std::collections::HashMap; + +use crate::state::{AppState, CacheEntry}; + +fn validate_identifier(name: &str) -> Result<()> { + if name.chars().all(|c| c.is_alphanumeric() || c == '_') { + Ok(()) + } else { + Err(anyhow!("invalid identifier: {}", name)) + } +} + +/// Returns (sql, ordered_param_values, cache_key) +/// body_cols: sorted (col, val) pairs from request body +/// filter_cols: sorted (col, val) pairs from query params +pub fn build_query( + method: &str, + table: &str, + id: Option<&str>, + body_cols: &[(String, String)], + filter_cols: &[(String, String)], +) -> Result<(String, Vec, String)> { + validate_identifier(table)?; + for (col, _) in body_cols.iter().chain(filter_cols.iter()) { + validate_identifier(col)?; + } + + let mut sorted_body = body_cols.to_vec(); + sorted_body.sort_by(|a, b| a.0.cmp(&b.0)); + let mut sorted_filters = filter_cols.to_vec(); + sorted_filters.sort_by(|a, b| a.0.cmp(&b.0)); + + match method.to_uppercase().as_str() { + "GET" => { + if let Some(id_val) = id { + let sql = format!("SELECT * FROM {} WHERE id = $1", table); + let key = format!("GET:{}:by_id", table); + Ok((sql, vec![id_val.to_string()], key)) + } else if sorted_filters.is_empty() { + let sql = format!("SELECT * FROM {}", table); + let key = format!("GET:{}:", table); + Ok((sql, vec![], key)) + } else { + let col_names: Vec = sorted_filters.iter().map(|(c, _)| c.clone()).collect(); + let where_clause: Vec = col_names + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let sql = format!("SELECT * FROM {} WHERE {}", table, where_clause.join(" AND ")); + let params: Vec = sorted_filters.iter().map(|(_, v)| v.clone()).collect(); + let key = format!("GET:{}:{}", table, col_names.join(",")); + Ok((sql, params, key)) + } + } + "POST" => { + if sorted_body.is_empty() { + return Err(anyhow!("POST requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let placeholders: Vec = (1..=cols.len()).map(|i| format!("${}", i)).collect(); + let sql = format!( + "INSERT INTO {} ({}) VALUES ({}) RETURNING *", + table, + cols.join(", "), + placeholders.join(", ") + ); + let params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + let key = format!("POST:{}:{}", table, cols.join(",")); + Ok((sql, params, key)) + } + "PUT" => { + let id_val = id.ok_or_else(|| anyhow!("PUT requires an id"))?; + if sorted_body.is_empty() { + return Err(anyhow!("PUT requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let set_clause: Vec = cols + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let id_placeholder = cols.len() + 1; + let sql = format!( + "UPDATE {} SET {} WHERE id = ${} RETURNING *", + table, + set_clause.join(", "), + id_placeholder + ); + let mut params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + params.push(id_val.to_string()); + let key = format!("PUT:{}:{}:by_id", table, cols.join(",")); + Ok((sql, params, key)) + } + "DELETE" => { + let id_val = id.ok_or_else(|| anyhow!("DELETE requires an id"))?; + let sql = format!("DELETE FROM {} WHERE id = $1", table); + let key = format!("DELETE:{}:by_id", table); + Ok((sql, vec![id_val.to_string()], key)) + } + m => Err(anyhow!("unsupported method: {}", m)), + } +} + +pub fn pg_row_to_json(row: PgRow) -> Value { + let columns = row.columns(); + let mut map = serde_json::Map::new(); + for col in columns { + let name = col.name().to_string(); + let type_name = col.type_info().name(); + let val = match type_name { + "INT2" | "INT4" | "INT8" | "SERIAL" => row + .try_get::(col.ordinal()) + .map(|v| Value::Number(v.into())) + .unwrap_or(Value::Null), + "FLOAT4" | "FLOAT8" => row + .try_get::(col.ordinal()) + .ok() + .and_then(|v| serde_json::Number::from_f64(v)) + .map(Value::Number) + .unwrap_or(Value::Null), + "BOOL" => row + .try_get::(col.ordinal()) + .map(Value::Bool) + .unwrap_or(Value::Null), + "UUID" => row + .try_get::(col.ordinal()) + .map(|v| Value::String(v.to_string())) + .unwrap_or(Value::Null), + "TIMESTAMPTZ" | "TIMESTAMP" => row + .try_get::, _>(col.ordinal()) + .map(|v| Value::String(v.to_rfc3339())) + .unwrap_or(Value::Null), + _ => row + .try_get::(col.ordinal()) + .map(Value::String) + .unwrap_or(Value::Null), + }; + map.insert(name, val); + } + Value::Object(map) +} + +pub async fn handle_crud( + State(state): State, + method: Method, + Path(params): Path>, + Query(query_params): Query>, + body: Option>>, +) -> Result, StatusCode> { + let table = params.get("table").ok_or(StatusCode::BAD_REQUEST)?; + let id = params.get("id").map(|s| s.as_str()); + let method_str = method.as_str(); + + let body_cols: Vec<(String, String)> = body + .map(|Json(b)| { + b.into_iter() + .filter_map(|(k, v)| match v { + Value::String(s) => Some((k, s)), + Value::Number(n) => Some((k, n.to_string())), + Value::Bool(b) => Some((k, b.to_string())), + _ => None, + }) + .collect() + }) + .unwrap_or_default(); + + let filter_cols: Vec<(String, String)> = query_params.into_iter().collect(); + + let (sql, params_vals, cache_key) = + build_query(method_str, table, id, &body_cols, &filter_cols) + .map_err(|_| StatusCode::BAD_REQUEST)?; + + let cached = state.query_cache.get(&cache_key); + let _entry = if cached.is_none() { + let entry = CacheEntry::new(sql.clone(), vec![]); + state + .query_cache + .insert(cache_key, entry.clone(), state.config.cache_max_capacity); + entry + } else { + cached.unwrap() + }; + + let mut q = sqlx::query(&sql); + for val in ¶ms_vals { + q = q.bind(val.as_str()); + } + + match method_str.to_uppercase().as_str() { + "GET" => { + let rows = q + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let json_rows: Vec = rows.into_iter().map(pg_row_to_json).collect(); + Ok(Json(Value::Array(json_rows))) + } + "POST" | "PUT" => { + let row = q + .fetch_one(&state.pool) + .await + .map_err(|e| { + if e.to_string().contains("no rows") { + StatusCode::NOT_FOUND + } else { + StatusCode::INTERNAL_SERVER_ERROR + } + })?; + Ok(Json(pg_row_to_json(row))) + } + "DELETE" => { + q.execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(serde_json::json!({ "deleted": true }))) + } + _ => Err(StatusCode::METHOD_NOT_ALLOWED), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_build_select_all() { + let (sql, params, key) = build_query("GET", "orders", None, &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders"); + assert!(params.is_empty()); + assert_eq!(key, "GET:orders:"); + } + + #[test] + fn test_build_select_by_id() { + let (sql, params, key) = build_query("GET", "orders", Some("42"), &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders WHERE id = $1"); + assert_eq!(params, vec!["42".to_string()]); + assert_eq!(key, "GET:orders:by_id"); + } + + #[test] + fn test_build_insert() { + let cols = vec![("email".into(), "a@b.com".into()), ("name".into(), "Alice".into())]; + let (sql, params, key) = build_query("POST", "users", None, &cols, &[]).unwrap(); + assert_eq!(sql, "INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *"); + assert_eq!(params, vec!["a@b.com", "Alice"]); + assert_eq!(key, "POST:users:email,name"); + } + + #[test] + fn test_build_update() { + let cols = vec![("name".into(), "Bob".into())]; + let (sql, params, key) = build_query("PUT", "users", Some("7"), &cols, &[]).unwrap(); + assert_eq!(sql, "UPDATE users SET name = $1 WHERE id = $2 RETURNING *"); + assert_eq!(params, vec!["Bob", "7"]); + assert_eq!(key, "PUT:users:name:by_id"); + } + + #[test] + fn test_build_delete() { + let (sql, params, key) = build_query("DELETE", "users", Some("3"), &[], &[]).unwrap(); + assert_eq!(sql, "DELETE FROM users WHERE id = $1"); + assert_eq!(params, vec!["3"]); + assert_eq!(key, "DELETE:users:by_id"); + } + + #[test] + fn test_build_select_with_filters() { + let filters = vec![("status".into(), "active".into()), ("role".into(), "admin".into())]; + let (sql, params, key) = build_query("GET", "users", None, &[], &filters).unwrap(); + assert_eq!(sql, "SELECT * FROM users WHERE role = $1 AND status = $2"); + assert_eq!(params, vec!["admin", "active"]); + assert_eq!(key, "GET:users:role,status"); + } + + #[test] + fn test_rejects_invalid_table_name() { + let result = build_query("GET", "users; DROP TABLE users--", None, &[], &[]); + assert!(result.is_err()); + } +} +``` + +- [ ] **Step 4: Run tests** + +```bash +cargo test crud::tests +``` +Expected: 7 tests pass. + +- [ ] **Step 5: Commit** + +```bash +git add src/routes/crud.rs +git commit -m "feat: add dynamic CRUD query builder with cache integration" +``` + +--- + +## Task 11: Admin routes — queries + +**Files:** +- Create: `src/routes/admin/queries.rs` + +- [ ] **Step 1: Write src/routes/admin/queries.rs** + +```rust +use axum::{ + extract::{Extension, Path, Query, State}, + http::StatusCode, + Json, +}; +use serde_json::{json, Value}; +use std::collections::HashMap; + +use crate::{ + auth::Claims, + models::query::{CreateQuery, StoredQuery, UpdateQuery}, + state::AppState, +}; + +pub async fn list_queries( + State(state): State, + Extension(_claims): Extension, +) -> Result>, StatusCode> { + let queries = sqlx::query_as!( + StoredQuery, + "SELECT id, identifier, sql_template, description, created_at, updated_at FROM queries ORDER BY created_at DESC" + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(queries)) +} + +pub async fn get_query( + State(state): State, + Extension(_claims): Extension, + Path(identifier): Path, +) -> Result, StatusCode> { + let q = sqlx::query_as!( + StoredQuery, + "SELECT id, identifier, sql_template, description, created_at, updated_at FROM queries WHERE identifier = $1", + identifier + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + Ok(Json(q)) +} + +pub async fn create_query( + State(state): State, + Extension(_claims): Extension, + Json(body): Json, +) -> Result, StatusCode> { + let q = sqlx::query_as!( + StoredQuery, + "INSERT INTO queries (identifier, sql_template, description) VALUES ($1, $2, $3) RETURNING id, identifier, sql_template, description, created_at, updated_at", + body.identifier, + body.sql_template, + body.description + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(q)) +} + +pub async fn update_query( + State(state): State, + Extension(_claims): Extension, + Path(identifier): Path, + Json(body): Json, +) -> Result, StatusCode> { + let existing = sqlx::query_as!( + StoredQuery, + "SELECT id, identifier, sql_template, description, created_at, updated_at FROM queries WHERE identifier = $1", + identifier + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let new_sql = body.sql_template.as_deref().unwrap_or(&existing.sql_template); + let new_desc = body.description.as_deref().or(existing.description.as_deref()); + + let q = sqlx::query_as!( + StoredQuery, + "UPDATE queries SET sql_template = $1, description = $2, updated_at = now() WHERE identifier = $3 RETURNING id, identifier, sql_template, description, created_at, updated_at", + new_sql, + new_desc, + identifier + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + state.query_cache.remove(&identifier); + Ok(Json(q)) +} + +pub async fn delete_query( + State(state): State, + Extension(_claims): Extension, + Path(identifier): Path, +) -> Result, StatusCode> { + sqlx::query!("DELETE FROM queries WHERE identifier = $1", identifier) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state.query_cache.remove(&identifier); + Ok(Json(json!({ "deleted": true }))) +} + +pub async fn execute_query( + State(state): State, + Extension(_claims): Extension, + Path(identifier): Path, + Query(params): Query>, +) -> Result, StatusCode> { + let stored = sqlx::query_as!( + StoredQuery, + "SELECT id, identifier, sql_template, description, created_at, updated_at FROM queries WHERE identifier = $1", + identifier + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let mut sql = stored.sql_template.clone(); + let mut bound_vals: Vec = Vec::new(); + let mut idx = 1usize; + let mut sorted_params: Vec<(String, String)> = params.into_iter().collect(); + sorted_params.sort_by(|a, b| a.0.cmp(&b.0)); + for (name, val) in &sorted_params { + let placeholder = format!(":{}", name); + if sql.contains(&placeholder) { + sql = sql.replace(&placeholder, &format!("${}", idx)); + bound_vals.push(val.clone()); + idx += 1; + } + } + + let mut q = sqlx::query(&sql); + for val in &bound_vals { + q = q.bind(val.as_str()); + } + + let rows = q + .fetch_all(&state.pool) + .await + .map_err(|e| { + tracing::error!("query execution error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + let json_rows: Vec = rows + .into_iter() + .map(crate::routes::crud::pg_row_to_json) + .collect(); + + Ok(Json(Value::Array(json_rows))) +} +``` + +- [ ] **Step 2: Compile** + +```bash +cargo build +``` +Expected: `Finished`. + +- [ ] **Step 3: Commit** + +```bash +git add src/routes/admin/queries.rs +git commit -m "feat: add admin query registry CRUD routes" +``` + +--- + +## Task 12: Admin routes — cache, users, permissions, blacklist + +**Files:** +- Create: `src/routes/admin/cache.rs` +- Create: `src/routes/admin/users.rs` +- Create: `src/routes/admin/permissions.rs` +- Create: `src/routes/admin/blacklist.rs` +- Modify: `src/routes/admin/mod.rs` + +- [ ] **Step 1: Write src/routes/admin/cache.rs** + +```rust +use axum::{extract::State, http::StatusCode, Json}; +use serde_json::{json, Value}; + +use crate::{auth::Claims, state::AppState}; +use axum::extract::Extension; + +pub async fn cache_stats( + State(state): State, + Extension(_claims): Extension, +) -> Json { + Json(json!({ + "size": state.query_cache.len(), + "hits": state.query_cache.hits(), + "misses": state.query_cache.misses(), + })) +} + +pub async fn flush_cache( + State(state): State, + Extension(_claims): Extension, +) -> Result, StatusCode> { + state.query_cache.flush(); + Ok(Json(json!({ "flushed": true }))) +} +``` + +- [ ] **Step 2: Write src/routes/admin/users.rs** + +```rust +use axum::{ + extract::{Extension, Path, State}, + http::StatusCode, + Json, +}; +use serde_json::{json, Value}; + +use crate::{ + auth::{encode_jwt, Claims}, + models::user::{CreateUser, UpdateUser, User}, + state::AppState, +}; + +pub async fn list_users( + State(state): State, + Extension(_claims): Extension, +) -> Result>, StatusCode> { + let users = sqlx::query_as!( + User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users ORDER BY id" + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(users)) +} + +pub async fn get_user( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, +) -> Result, StatusCode> { + let user = sqlx::query_as!( + User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + Ok(Json(user)) +} + +pub async fn create_user( + State(state): State, + Extension(_claims): Extension, + Json(body): Json, +) -> Result, StatusCode> { + let hash = bcrypt::hash(&body.password, bcrypt::DEFAULT_COST) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let mask = body.permissions_mask.unwrap_or_else(|| "0".into()); + let user = sqlx::query_as!( + User, + "INSERT INTO users (username, password_hash, permissions_mask) VALUES ($1, $2, $3) RETURNING id, username, password_hash, permissions_mask, created_at", + body.username, + hash, + mask + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(user)) +} + +pub async fn update_user( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, + Json(body): Json, +) -> Result, StatusCode> { + let existing = sqlx::query_as!( + User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let new_username = body.username.as_deref().unwrap_or(&existing.username); + let new_hash = if let Some(pw) = &body.password { + bcrypt::hash(pw, bcrypt::DEFAULT_COST).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + } else { + existing.password_hash.clone() + }; + let new_mask = body.permissions_mask.as_deref().unwrap_or(&existing.permissions_mask); + + let user = sqlx::query_as!( + User, + "UPDATE users SET username = $1, password_hash = $2, permissions_mask = $3 WHERE id = $4 RETURNING id, username, password_hash, permissions_mask, created_at", + new_username, + new_hash, + new_mask, + id + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(user)) +} + +pub async fn delete_user( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, +) -> Result, StatusCode> { + sqlx::query!("DELETE FROM users WHERE id = $1", id) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(json!({ "deleted": true }))) +} + +pub async fn grant_permission( + State(state): State, + Extension(_claims): Extension, + Path((id, bit_value)): Path<(i32, String)>, +) -> Result, StatusCode> { + let user = sqlx::query_as!( + User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let current: u128 = user.permissions_mask.parse().unwrap_or(0); + let bit: u128 = bit_value.parse().map_err(|_| StatusCode::BAD_REQUEST)?; + let new_mask = (current | bit).to_string(); + + let updated = sqlx::query_as!( + User, + "UPDATE users SET permissions_mask = $1 WHERE id = $2 RETURNING id, username, password_hash, permissions_mask, created_at", + new_mask, + id + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(updated)) +} + +pub async fn revoke_permission( + State(state): State, + Extension(_claims): Extension, + Path((id, bit_value)): Path<(i32, String)>, +) -> Result, StatusCode> { + let user = sqlx::query_as!( + User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let current: u128 = user.permissions_mask.parse().unwrap_or(0); + let bit: u128 = bit_value.parse().map_err(|_| StatusCode::BAD_REQUEST)?; + let new_mask = (current & !bit).to_string(); + + let updated = sqlx::query_as!( + User, + "UPDATE users SET permissions_mask = $1 WHERE id = $2 RETURNING id, username, password_hash, permissions_mask, created_at", + new_mask, + id + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(updated)) +} +``` + +- [ ] **Step 3: Write src/routes/admin/permissions.rs** + +```rust +use axum::{ + extract::{Extension, Path, State}, + http::StatusCode, + Json, +}; +use serde_json::{json, Value}; + +use crate::{ + auth::Claims, + models::permission::{CreatePermission, Permission, UpdatePermission}, + state::AppState, +}; + +pub async fn list_permissions( + State(state): State, + Extension(_claims): Extension, +) -> Result>, StatusCode> { + let perms = sqlx::query_as!( + Permission, + "SELECT id, name, bit_value, description FROM permissions ORDER BY id" + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(perms)) +} + +pub async fn create_permission( + State(state): State, + Extension(_claims): Extension, + Json(body): Json, +) -> Result, StatusCode> { + let existing: Vec = sqlx::query_scalar!("SELECT bit_value FROM permissions") + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .into_iter() + .flatten() + .collect(); + + let next_bit = (0u128..) + .map(|i| 1u128 << i) + .find(|bit| !existing.contains(&bit.to_string())) + .ok_or(StatusCode::INSUFFICIENT_STORAGE)?; + + let perm = sqlx::query_as!( + Permission, + "INSERT INTO permissions (name, bit_value, description) VALUES ($1, $2, $3) RETURNING id, name, bit_value, description", + body.name, + next_bit.to_string(), + body.description + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(perm)) +} + +pub async fn update_permission( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, + Json(body): Json, +) -> Result, StatusCode> { + let existing = sqlx::query_as!( + Permission, + "SELECT id, name, bit_value, description FROM permissions WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let new_name = body.name.as_deref().unwrap_or(&existing.name); + let new_desc = body.description.as_deref().or(existing.description.as_deref()); + + let perm = sqlx::query_as!( + Permission, + "UPDATE permissions SET name = $1, description = $2 WHERE id = $3 RETURNING id, name, bit_value, description", + new_name, + new_desc, + id + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(perm)) +} + +pub async fn delete_permission( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, +) -> Result, StatusCode> { + sqlx::query!("DELETE FROM permissions WHERE id = $1", id) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(json!({ "deleted": true }))) +} +``` + +- [ ] **Step 4: Write src/routes/admin/blacklist.rs** + +```rust +use axum::{ + extract::{Extension, Path, State}, + http::StatusCode, + Json, +}; +use serde_json::{json, Value}; + +use crate::{ + auth::Claims, + models::blacklist::{BlacklistEntry, CreateBlacklistEntry, UpdateBlacklistEntry}, + state::AppState, +}; + +async fn reload_blacklist(state: &AppState) -> Result<(), StatusCode> { + let entries = sqlx::query_as!( + BlacklistEntry, + "SELECT id, pattern, method, reason, active, created_at FROM blacklist ORDER BY id" + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state.blacklist_cache.load(entries).await; + Ok(()) +} + +pub async fn list_blacklist( + State(state): State, + Extension(_claims): Extension, +) -> Result>, StatusCode> { + let entries = sqlx::query_as!( + BlacklistEntry, + "SELECT id, pattern, method, reason, active, created_at FROM blacklist ORDER BY id" + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(entries)) +} + +pub async fn create_blacklist_entry( + State(state): State, + Extension(_claims): Extension, + Json(body): Json, +) -> Result, StatusCode> { + let entry = sqlx::query_as!( + BlacklistEntry, + "INSERT INTO blacklist (pattern, method, reason) VALUES ($1, $2, $3) RETURNING id, pattern, method, reason, active, created_at", + body.pattern, + body.method, + body.reason + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + reload_blacklist(&state).await?; + Ok(Json(entry)) +} + +pub async fn update_blacklist_entry( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, + Json(body): Json, +) -> Result, StatusCode> { + let existing = sqlx::query_as!( + BlacklistEntry, + "SELECT id, pattern, method, reason, active, created_at FROM blacklist WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let new_pattern = body.pattern.as_deref().unwrap_or(&existing.pattern); + let new_method = body.method.as_deref().or(existing.method.as_deref()); + let new_reason = body.reason.as_deref().or(existing.reason.as_deref()); + let new_active = body.active.unwrap_or(existing.active); + + let entry = sqlx::query_as!( + BlacklistEntry, + "UPDATE blacklist SET pattern = $1, method = $2, reason = $3, active = $4 WHERE id = $5 RETURNING id, pattern, method, reason, active, created_at", + new_pattern, + new_method, + new_reason, + new_active, + id + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + reload_blacklist(&state).await?; + Ok(Json(entry)) +} + +pub async fn delete_blacklist_entry( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, +) -> Result, StatusCode> { + sqlx::query!("DELETE FROM blacklist WHERE id = $1", id) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + reload_blacklist(&state).await?; + Ok(Json(json!({ "deleted": true }))) +} +``` + +- [ ] **Step 5: Write src/routes/admin/mod.rs** + +```rust +pub mod blacklist; +pub mod cache; +pub mod permissions; +pub mod queries; +pub mod users; + +use axum::{ + middleware, + routing::{delete, get, post, put}, + Router, +}; + +use crate::{ + auth::middleware::{require_admin_cache, require_admin_query, require_super_admin}, + state::AppState, +}; + +pub fn admin_router(state: AppState) -> Router { + let query_routes = Router::new() + .route("/", get(queries::list_queries).post(queries::create_query)) + .route( + "/:identifier", + get(queries::get_query) + .put(queries::update_query) + .delete(queries::delete_query), + ) + .route("/:identifier/execute", get(queries::execute_query)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_admin_query, + )); + + let cache_routes = Router::new() + .route("/stats", get(cache::cache_stats)) + .route("/", delete(cache::flush_cache)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_admin_cache, + )); + + let super_routes = Router::new() + .route("/users", get(users::list_users).post(users::create_user)) + .route( + "/users/:id", + get(users::get_user) + .put(users::update_user) + .delete(users::delete_user), + ) + .route( + "/users/:id/permissions/grant/:bit_value", + post(users::grant_permission), + ) + .route( + "/users/:id/permissions/revoke/:bit_value", + delete(users::revoke_permission), + ) + .route( + "/permissions", + get(permissions::list_permissions).post(permissions::create_permission), + ) + .route( + "/permissions/:id", + put(permissions::update_permission).delete(permissions::delete_permission), + ) + .route( + "/blacklist", + get(blacklist::list_blacklist).post(blacklist::create_blacklist_entry), + ) + .route( + "/blacklist/:id", + put(blacklist::update_blacklist_entry).delete(blacklist::delete_blacklist_entry), + ) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_super_admin, + )); + + Router::new() + .nest("/queries", query_routes) + .nest("/cache", cache_routes) + .merge(super_routes) +} +``` + +- [ ] **Step 6: Compile** + +```bash +cargo build +``` +Expected: `Finished`. + +- [ ] **Step 7: Commit** + +```bash +git add src/routes/admin/ +git commit -m "feat: add admin routes for cache, users, permissions, and blacklist" +``` + +--- + +## Task 13: main.rs — full wiring + +**Files:** +- Modify: `src/main.rs` + +- [ ] **Step 1: Write full src/main.rs** + +```rust +mod auth; +mod cache; +mod config; +mod db; +mod models; +mod routes; +mod state; + +use std::sync::Arc; + +use axum::{middleware, routing::{delete, get, post, put}, Router}; +use tower_http::{cors::CorsLayer, services::ServeDir}; +use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; + +use crate::{ + auth::middleware::blacklist_layer, + cache::spawn_sweep_task, + config::Config, + db::create_pool, + models::blacklist::BlacklistEntry, + routes::{ + admin::admin_router, + auth::login, + crud::handle_crud, + }, + state::{AppState, BlacklistCache, QueryCache}, +}; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + dotenvy::dotenv().ok(); + + tracing_subscriber::registry() + .with(tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "mercury=info".into())) + .with(tracing_subscriber::fmt::layer()) + .init(); + + let config = Arc::new(Config::from_env()?); + let pool = create_pool(&config.database_url).await?; + + // Seed admin user if not present + let count: i64 = sqlx::query_scalar!("SELECT COUNT(*) FROM users WHERE username = 'admin'") + .fetch_one(&pool) + .await? + .unwrap_or(0); + if count == 0 { + let hash = bcrypt::hash("admin", bcrypt::DEFAULT_COST)?; + sqlx::query!( + "INSERT INTO users (username, password_hash, permissions_mask) VALUES ('admin', $1, '63')", + hash + ) + .execute(&pool) + .await?; + tracing::info!("seeded admin user"); + } + + let query_cache = QueryCache::new(); + let blacklist_cache = BlacklistCache::new(); + + // Load blacklist from DB into memory + let entries = sqlx::query_as!( + BlacklistEntry, + "SELECT id, pattern, method, reason, active, created_at FROM blacklist ORDER BY id" + ) + .fetch_all(&pool) + .await?; + blacklist_cache.load(entries).await; + + // Start cache sweep + spawn_sweep_task( + query_cache.clone(), + config.cache_idle_timeout_secs, + config.cache_sweep_interval_secs, + ); + + let state = AppState { + pool, + query_cache, + blacklist_cache, + config: config.clone(), + }; + + let crud_routes = Router::new() + .route("/api/:table", get(handle_crud).post(handle_crud)) + .route("/api/:table/:id", get(handle_crud).put(handle_crud).delete(handle_crud)) + .route_layer(middleware::from_fn_with_state(state.clone(), blacklist_layer)); + + let app = Router::new() + .route("/auth/login", post(login)) + .merge(crud_routes) + .nest("/admin", admin_router(state.clone())) + .nest_service("/", ServeDir::new("ui/dist")) + .layer(CorsLayer::permissive()) + .with_state(state); + + let addr = std::net::SocketAddr::from(([0, 0, 0, 0], 3000)); + tracing::info!("listening on {}", addr); + let listener = tokio::net::TcpListener::bind(addr).await?; + axum::serve(listener, app).await?; + Ok(()) +} +``` + +- [ ] **Step 2: Compile** + +```bash +cargo build +``` +Expected: `Finished`. + +- [ ] **Step 3: Commit** + +```bash +git add src/main.rs +git commit -m "feat: wire full Axum router with middleware, CRUD, admin, and static file serving" +``` + +--- + +## Task 14: Docker setup + +**Files:** +- Create: `Dockerfile` +- Create: `docker-compose.yml` + +- [ ] **Step 1: Write Dockerfile** + +```dockerfile +# Stage 1: Build Vue UI +FROM node:20-alpine AS ui-builder +WORKDIR /ui +COPY ui/.npmrc . +COPY ui/package*.json . +RUN npm install +COPY ui/ . +RUN npm run build + +# Stage 2: Build Rust API +FROM rust:1.75-slim AS api-builder +RUN apt-get update && apt-get install -y pkg-config libssl-dev && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY Cargo.toml Cargo.lock ./ +COPY src/ src/ +RUN cargo build --release + +# Stage 3: Final image +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y ca-certificates libssl3 && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY --from=api-builder /app/target/release/mercury . +COPY --from=ui-builder /ui/dist ./ui/dist +EXPOSE 3000 +CMD ["./mercury"] +``` + +- [ ] **Step 2: Write docker-compose.yml** + +```yaml +services: + db: + image: postgres:16-alpine + environment: + POSTGRES_USER: mercury + POSTGRES_PASSWORD: mercury + POSTGRES_DB: mercury + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U mercury"] + interval: 5s + timeout: 5s + retries: 5 + + api: + build: . + ports: + - "3000:3000" + environment: + DATABASE_URL: postgres://mercury:mercury@db:5432/mercury + JWT_SECRET: ${JWT_SECRET:-change_me_in_production} + JWT_EXPIRY_SECS: ${JWT_EXPIRY_SECS:-3600} + CACHE_MAX_CAPACITY: ${CACHE_MAX_CAPACITY:-10000} + CACHE_IDLE_TIMEOUT_SECS: ${CACHE_IDLE_TIMEOUT_SECS:-300} + CACHE_SWEEP_INTERVAL_SECS: ${CACHE_SWEEP_INTERVAL_SECS:-60} + depends_on: + db: + condition: service_healthy + mem_limit: 512m + mem_reservation: 256m + +volumes: + postgres_data: +``` + +- [ ] **Step 3: Commit** + +```bash +git add Dockerfile docker-compose.yml +git commit -m "feat: add multi-stage Dockerfile and docker-compose" +``` + +--- + +## Task 15: Vue UI scaffold + +**Files:** +- Create: `ui/.npmrc` +- Create: `ui/package.json` +- Create: `ui/vite.config.ts` +- Create: `ui/src/main.ts` +- Create: `ui/src/App.vue` +- Create: `ui/src/router/index.ts` +- Create: `ui/src/stores/auth.ts` + +- [ ] **Step 1: Write ui/.npmrc** + +``` +@nychthemeron:registry=https://git.mcpeakdev.com/api/packages/McPeakDev/npm/ +``` + +- [ ] **Step 2: Write ui/package.json** + +```json +{ + "name": "mercury-ui", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@nychthemeron/library": "latest", + "pinia": "^2.1.0", + "vue": "^3.4.0", + "vue-router": "^4.3.0" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^5.0.0", + "typescript": "^5.3.0", + "vite": "^5.0.0", + "vue-tsc": "^2.0.0" + } +} +``` + +- [ ] **Step 3: Write ui/vite.config.ts** + +```typescript +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' + +export default defineConfig({ + plugins: [vue()], + server: { + proxy: { + '/api': 'http://localhost:3000', + '/auth': 'http://localhost:3000', + '/admin': 'http://localhost:3000', + }, + }, + build: { + outDir: 'dist', + }, +}) +``` + +- [ ] **Step 4: Write ui/src/stores/auth.ts** + +```typescript +import { defineStore } from 'pinia' +import { ref, computed } from 'vue' + +interface Claims { + sub: string + permissions: string + exp: number +} + +function parseJwt(token: string): Claims | null { + try { + const payload = token.split('.')[1] + return JSON.parse(atob(payload)) as Claims + } catch { + return null + } +} + +export const useAuthStore = defineStore('auth', () => { + const token = ref(localStorage.getItem('mercury_token')) + const claims = computed(() => + token.value ? parseJwt(token.value) : null + ) + const isAuthenticated = computed(() => { + if (!claims.value) return false + return claims.value.exp * 1000 > Date.now() + }) + const username = computed(() => claims.value?.sub ?? '') + + function hasPermission(bit: bigint): boolean { + if (!claims.value) return false + const mask = BigInt(claims.value.permissions) + return (mask & bit) !== 0n + } + + const isSuperAdmin = computed(() => hasPermission(32n)) + + async function login(username: string, password: string): Promise { + const res = await fetch('/auth/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + }) + if (!res.ok) throw new Error('Invalid credentials') + const data = await res.json() + token.value = data.token + localStorage.setItem('mercury_token', data.token) + } + + function logout() { + token.value = null + localStorage.removeItem('mercury_token') + } + + function authHeaders(): Record { + return token.value ? { Authorization: `Bearer ${token.value}` } : {} + } + + return { token, claims, isAuthenticated, username, isSuperAdmin, hasPermission, login, logout, authHeaders } +}) +``` + +- [ ] **Step 5: Write ui/src/router/index.ts** + +```typescript +import { createRouter, createWebHistory } from 'vue-router' +import { useAuthStore } from '../stores/auth' + +const router = createRouter({ + history: createWebHistory(), + routes: [ + { path: '/login', component: () => import('../views/Login.vue') }, + { + path: '/admin', + component: () => import('../views/admin/Layout.vue'), + children: [ + { path: 'queries', component: () => import('../views/admin/Queries.vue') }, + { path: 'users', component: () => import('../views/admin/Users.vue') }, + { path: 'permissions', component: () => import('../views/admin/Permissions.vue') }, + { path: 'blacklist', component: () => import('../views/admin/Blacklist.vue') }, + { path: 'cache', component: () => import('../views/admin/Cache.vue') }, + ], + meta: { requiresAuth: true }, + }, + { path: '/', redirect: '/admin/queries' }, + ], +}) + +router.beforeEach((to) => { + const auth = useAuthStore() + if (to.meta.requiresAuth && !auth.isAuthenticated) { + return '/login' + } + if (to.path === '/login' && auth.isAuthenticated) { + return '/admin/queries' + } +}) + +export default router +``` + +- [ ] **Step 6: Write ui/src/main.ts** + +```typescript +import { createApp } from 'vue' +import { createPinia } from 'pinia' +import NychthemeronLibrary from '@nychthemeron/library' +import App from './App.vue' +import router from './router' + +const app = createApp(App) +app.use(createPinia()) +app.use(router) +app.use(NychthemeronLibrary, { theme: 'dark' }) +app.mount('#app') +``` + +- [ ] **Step 7: Write ui/src/App.vue** + +```vue + +``` + +- [ ] **Step 8: Create ui/src/views/Login.vue** + +```vue + + + + + +``` + +- [ ] **Step 9: Commit** + +```bash +git add ui/ +git commit -m "feat: scaffold Vue 3 UI with auth store, router, and login view" +``` + +--- + +## Task 16: Admin views + +**Files:** +- Create: `ui/src/views/admin/Layout.vue` +- Create: `ui/src/views/admin/Queries.vue` +- Create: `ui/src/views/admin/Users.vue` +- Create: `ui/src/views/admin/Permissions.vue` +- Create: `ui/src/views/admin/Blacklist.vue` +- Create: `ui/src/views/admin/Cache.vue` + +- [ ] **Step 1: Write ui/src/views/admin/Layout.vue** + +```vue + + + + + +``` + +- [ ] **Step 2: Write ui/src/views/admin/Queries.vue** + +```vue + + + +``` + +- [ ] **Step 3: Write ui/src/views/admin/Users.vue** + +```vue + + + +``` + +- [ ] **Step 4: Write ui/src/views/admin/Permissions.vue** + +```vue + + + +``` + +- [ ] **Step 5: Write ui/src/views/admin/Blacklist.vue** + +```vue + + + +``` + +- [ ] **Step 6: Write ui/src/views/admin/Cache.vue** + +```vue + + + + + +``` + +- [ ] **Step 7: Commit** + +```bash +git add ui/src/views/ +git commit -m "feat: add admin views for queries, users, permissions, blacklist, cache" +``` + +--- + +## Task 17: README update + +**Files:** +- Modify: `README.md` + +- [ ] **Step 1: Write README.md** + +```markdown +# Mercury + +A high-performance, monolithic Rust API with a dynamic CRUD engine, query registry cache, JWT bitmask permissions, and a Vue 3 admin frontend. + +## Quick Start + +```bash +cp .env.example .env # set JWT_SECRET +docker compose up --build +``` + +API: http://localhost:3000/api +Admin UI: http://localhost:3000 +Default credentials: `admin` / `admin` + +--- + +## API Contract + +### Authentication + +``` +POST /auth/login +Body: { "username": "...", "password": "..." } +Returns: { "token": "" } +``` + +All admin routes require `Authorization: Bearer `. + +--- + +### CRUD — Dynamic Table Access + +Requests are mapped to the named PostgreSQL table. The SQL is generated, cached, and executed automatically. + +``` +GET /api/{table} List all rows (supports ?col=val filters) +GET /api/{table}/{id} Get row by id +POST /api/{table} Insert row (JSON body) +PUT /api/{table}/{id} Update row by id (JSON body) +DELETE /api/{table}/{id} Delete row by id +``` + +**Notes:** +- `users` and `permissions` tables are blacklisted from public CRUD — use the admin suite. +- Filters are ANDed together: `GET /api/orders?status=open&priority=high` + +--- + +### Admin — Query Registry + +Requires JWT with `ADMIN_QUERY` permission (bit 8). + +``` +GET /admin/queries List all registered queries +POST /admin/queries Register a raw SQL template +GET /admin/queries/{identifier} Get query by slug +PUT /admin/queries/{identifier} Update SQL template or description +DELETE /admin/queries/{identifier} Remove query (evicts from cache) +GET /admin/queries/{identifier}/execute Execute query with ?param=val bindings +``` + +SQL templates use `:param_name` placeholders: +```sql +SELECT * FROM orders WHERE user_id = :user_id AND status = :status +``` + +--- + +### Admin — Cache + +Requires JWT with `ADMIN_CACHE` permission (bit 16). + +``` +GET /admin/cache/stats Cache size, hit count, miss count +DELETE /admin/cache Flush entire cache +``` + +--- + +### Admin — Users + +Requires JWT with `SUPER_ADMIN` permission (bit 32). + +``` +GET /admin/users List users +POST /admin/users Create user +GET /admin/users/{id} Get user +PUT /admin/users/{id} Update user +DELETE /admin/users/{id} Delete user +POST /admin/users/{id}/permissions/grant/{bit} OR bit into permissions mask +DELETE /admin/users/{id}/permissions/revoke/{bit} AND NOT bit from permissions mask +``` + +--- + +### Admin — Permissions + +Requires JWT with `SUPER_ADMIN` permission (bit 32). + +``` +GET /admin/permissions List permission definitions +POST /admin/permissions Create custom permission (auto-assigns next bit) +PUT /admin/permissions/{id} Update name/description +DELETE /admin/permissions/{id} Remove permission +``` + +--- + +### Admin — Route Blacklist + +Requires JWT with `SUPER_ADMIN` permission (bit 32). Changes take effect immediately in memory. + +``` +GET /admin/blacklist List all entries +POST /admin/blacklist Add glob pattern +PUT /admin/blacklist/{id} Update entry (set active: false to disable) +DELETE /admin/blacklist/{id} Remove entry +``` + +Pattern syntax: `*` matches one path segment, `**` matches many. +Example: `/api/sensitive/**` blocks all methods under that path. + +--- + +## Permission Bitmask + +| Name | Bit | Value | +|-------------|-----|-------| +| READ | 0 | 1 | +| WRITE | 1 | 2 | +| DELETE | 2 | 4 | +| ADMIN_QUERY | 3 | 8 | +| ADMIN_CACHE | 4 | 16 | +| SUPER_ADMIN | 5 | 32 | + +Custom permissions are added via the admin suite and assigned the next available power-of-2 bit. Masks support up to 128 bits (u128). + +--- + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `DATABASE_URL` | required | PostgreSQL connection string | +| `JWT_SECRET` | required | HMAC-HS256 signing secret | +| `JWT_EXPIRY_SECS` | 3600 | Token lifetime in seconds | +| `CACHE_MAX_CAPACITY` | 10000 | Max query templates in memory | +| `CACHE_IDLE_TIMEOUT_SECS` | 300 | Evict after N seconds idle | +| `CACHE_SWEEP_INTERVAL_SECS` | 60 | Sweep interval for eviction task | + +--- + +## Development + +```bash +# API only (requires local Postgres) +cargo run + +# UI dev server (proxies to local API) +cd ui && npm install && npm run dev + +# Full stack +docker compose up --build +``` + +## Stack + +- **API:** Rust, Axum, SQLx, PostgreSQL, DashMap, jsonwebtoken, bcrypt +- **Frontend:** Vue 3, Vite, @nychthemeron/library (dark mode default) +- **Infra:** Docker multi-stage build, docker compose +``` + +- [ ] **Step 2: Commit** + +```bash +git add README.md +git commit -m "docs: update README with full API contract and configuration" +``` + +--- + +## Self-Review Checklist + +### Spec Coverage + +| Spec requirement | Task | +|---|---| +| Axum + SQLx + PostgreSQL | Task 1, 4 | +| Config from env vars | Task 2 | +| DashMap TTI cache with sweep | Task 5, 6 | +| Blacklist in-memory with glob | Task 5 | +| JWT with u128 bitmask | Task 7 | +| Auth + blacklist middleware | Task 8 | +| CRUD query builder | Task 10 | +| /auth/login | Task 9 | +| Admin query registry CRUD | Task 11 | +| Admin cache stats + flush | Task 12 | +| Admin user management | Task 12 | +| Admin permission definitions | Task 12 | +| Admin blacklist CRUD + reload | Task 12 | +| Router assembly + main.rs | Task 13 | +| Dockerfile multi-stage | Task 14 | +| docker-compose with mem_limit | Task 14 | +| Admin seeded in migration | Task 4 (schema) + Task 13 (seed on startup) | +| Vue 3 + @nychthemeron/library | Task 15 | +| Dark mode default | Task 15 (main.ts) | +| Login view | Task 15 | +| Admin views (5 pages) | Task 16 | +| README with API contract | Task 17 | +| `users`/`permissions` blacklisted | Task 4 (migration seed) | +| Blacklist reloads on write | Task 12 (blacklist.rs) | +| Permission grant/revoke endpoints | Task 12 (users.rs) | +| Custom permissions auto-assign bit | Task 12 (permissions.rs) | + +All spec requirements covered. No gaps found. diff --git a/docs/superpowers/plans/2026-06-17-security-fixes.md b/docs/superpowers/plans/2026-06-17-security-fixes.md new file mode 100644 index 0000000..0c7736d --- /dev/null +++ b/docs/superpowers/plans/2026-06-17-security-fixes.md @@ -0,0 +1,1072 @@ +# Security Fixes Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Fix all Critical, Important, and Minor security/robustness issues identified in the June 2026 code review. + +**Architecture:** Fixes are applied in dependency order — shared utilities first, then middleware, then handlers, then startup. No new crates required except `rpassword` is intentionally avoided (plain stdin for first-user prompt is acceptable). + +**Tech Stack:** Rust, Axum 0.7, SQLx 0.7, jsonwebtoken 9, bcrypt 0.15, DashMap 5, tower-http 0.5 + +--- + +## File Map + +| File | Changes | +|------|---------| +| `src/state.rs` | Fix `unix_now()` panic | +| `src/routes/mod.rs` | Add shared `is_valid_identifier()` | +| `src/routes/admin/tables.rs` | Use shared validator, add `PROTECTED_TABLES` denylist | +| `src/routes/admin/queries.rs` | Sort params longest-first before substitution | +| `src/routes/crud.rs` | Fix cache key, drop NULL_SENTINEL, enforce R/W/D bits, use shared validator | +| `src/auth/middleware.rs` | Stash Claims in extensions in `blacklist_layer`; add `authenticate()` helper | +| `src/config.rs` | Add `cors_origins: Vec` field | +| `src/main.rs` | First-user interactive prompt, body size limit, configured CORS | + +--- + +## Task 1: Fix `unix_now()` panic on sub-epoch clock + +**Files:** +- Modify: `src/state.rs:16-19` + +- [ ] **Step 1: Apply the fix** + +Change `src/state.rs`: +```rust +pub fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} +``` + +- [ ] **Step 2: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 3: Commit** + +```bash +git add src/state.rs +git commit -m "fix: don't panic in unix_now() when clock is before epoch" +``` + +--- + +## Task 2: Fix stored query prefix-substitution bug + +**Files:** +- Modify: `src/routes/admin/queries.rs:29-30` + +**The bug:** When sorted alphabetically, `:user` is replaced before `:username`, turning `:username` into `$1name` — invalid SQL. + +- [ ] **Step 1: Write a failing test** + +Add to `src/routes/admin/queries.rs` (at the bottom, inside a `#[cfg(test)]` block — create the block if it doesn't exist): + +```rust +#[cfg(test)] +mod tests { + #[test] + fn test_prefix_param_substitution_order() { + // Simulate the substitution logic with a prefix-conflicting pair. + let template = "SELECT * FROM t WHERE user_id = :user_id AND username = :username"; + let mut params: Vec<(String, String)> = vec![ + ("user_id".into(), "42".into()), + ("username".into(), "alice".into()), + ]; + // Sort longest-first (the fix) + params.sort_by(|a, b| b.0.len().cmp(&a.0.len())); + let mut sql = template.to_string(); + for (i, (name, _)) in params.iter().enumerate() { + sql = sql.replace(&format!(":{}", name), &format!("${}", i + 1)); + } + assert!(sql.contains("$1") && sql.contains("$2"), "sql: {}", sql); + assert!(!sql.contains(":username"), "placeholder not replaced: {}", sql); + assert!(!sql.contains(":user_id"), "placeholder not replaced: {}", sql); + // username (len 8) should be $1, user_id (len 7) should be $2 + assert_eq!(sql, "SELECT * FROM t WHERE user_id = $2 AND username = $1"); + } +} +``` + +- [ ] **Step 2: Run test to confirm it fails before the fix** + +```bash +cargo test test_prefix_param_substitution_order +``` +Expected: FAIL (currently sorts alphabetically, not by length). + +- [ ] **Step 3: Apply the fix in `execute_query`** + +In `src/routes/admin/queries.rs`, change line 30 from: +```rust +sorted_params.sort_by(|a, b| a.0.cmp(&b.0)); +``` +to: +```rust +sorted_params.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then(a.0.cmp(&b.0))); +``` + +- [ ] **Step 4: Run test to confirm it passes** + +```bash +cargo test test_prefix_param_substitution_order +``` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add src/routes/admin/queries.rs +git commit -m "fix: sort stored query params longest-first to prevent prefix substitution corruption" +``` + +--- + +## Task 3: Fix cache key collision between by-id lookup and column filter + +**Files:** +- Modify: `src/routes/crud.rs:48` + +**The bug:** `GET /api/users/by_id` and `GET /api/users?by_id=foo` both produce key `"GET:users:by_id"`. Tilde (`~`) is not a valid identifier character so `"~id"` can never collide with a column name. + +- [ ] **Step 1: Update the existing test to expect the new key** + +In `src/routes/crud.rs` tests, change `test_build_select_by_id`: +```rust +#[test] +fn test_build_select_by_id() { + let (sql, params, key) = build_query("GET", "orders", Some("42"), &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders WHERE id = $1"); + assert_eq!(params, vec![Value::String("42".into())]); + assert_eq!(key, "GET:orders:~id"); +} +``` + +> Note: `params` type changes to `Vec` in Task 6. For now, keep as `Vec` and update `"by_id"` → `"~id"` only. +> +> If doing this task before Task 6, the test assertion for params stays `vec!["42".to_string()]`. Just change the key assertion to `"GET:orders:~id"`. + +- [ ] **Step 2: Apply the fix** + +In `src/routes/crud.rs:48`, change: +```rust +let key = format!("GET:{}:by_id", table); +``` +to: +```rust +let key = format!("GET:{}:~id", table); +``` + +- [ ] **Step 3: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 4: Commit** + +```bash +git add src/routes/crud.rs +git commit -m "fix: change by-id cache key to ~id to prevent column name collision" +``` + +--- + +## Task 4: Extract shared `is_valid_identifier` to eliminate duplication + +**Files:** +- Modify: `src/routes/mod.rs` +- Modify: `src/routes/crud.rs:16-22` +- Modify: `src/routes/admin/tables.rs:17-23` + +- [ ] **Step 1: Add the shared function to `src/routes/mod.rs`** + +Replace the current content of `src/routes/mod.rs`: +```rust +pub mod admin; +pub mod auth; +pub mod crud; + +/// Returns true if `name` is a safe SQL identifier (non-empty, alphanumeric + underscore only). +pub fn is_valid_identifier(name: &str) -> bool { + !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') +} +``` + +- [ ] **Step 2: Update `src/routes/crud.rs` to use the shared function** + +Remove the local `validate_identifier` (lines 16-22): +```rust +// DELETE this function entirely: +fn validate_identifier(name: &str) -> Result<()> { + if name.chars().all(|c| c.is_alphanumeric() || c == '_') { + Ok(()) + } else { + Err(anyhow!("invalid identifier: {}", name)) + } +} +``` + +Replace the two call sites in `build_query`: +```rust +// Line 34 — was: validate_identifier(table)?; +if !crate::routes::is_valid_identifier(table) { + return Err(anyhow!("invalid identifier: {}", table)); +} +// Line 35-37 — was: for (col, _) in ... { validate_identifier(col)?; } +for (col, _) in body_cols.iter().chain(filter_cols.iter()) { + if !crate::routes::is_valid_identifier(col) { + return Err(anyhow!("invalid identifier: {}", col)); + } +} +``` + +- [ ] **Step 3: Update `src/routes/admin/tables.rs` to use the shared function** + +Remove the local `validate_identifier` (lines 17-23): +```rust +// DELETE this function entirely: +fn validate_identifier(name: &str) -> Result<(), StatusCode> { + if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') { + Ok(()) + } else { + Err(StatusCode::BAD_REQUEST) + } +} +``` + +Replace all three call sites: +```rust +// In get_table_preview, create_table, drop_table — replace validate_identifier(&name)? with: +if !crate::routes::is_valid_identifier(&name) { + return Err(StatusCode::BAD_REQUEST); +} +// In create_table column loop — replace validate_identifier(&col.name)? with: +if !crate::routes::is_valid_identifier(&col.name) { + return Err(StatusCode::BAD_REQUEST); +} +``` + +- [ ] **Step 4: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 5: Commit** + +```bash +git add src/routes/mod.rs src/routes/crud.rs src/routes/admin/tables.rs +git commit -m "refactor: extract shared is_valid_identifier to eliminate duplication" +``` + +--- + +## Task 5: Add protected-table denylist to DDL operations + +**Files:** +- Modify: `src/routes/admin/tables.rs` + +- [ ] **Step 1: Write failing tests** + +Add to `src/routes/admin/tables.rs` at the bottom: + +```rust +#[cfg(test)] +mod tests { + use super::PROTECTED_TABLES; + + #[test] + fn test_protected_tables_list() { + assert!(PROTECTED_TABLES.contains(&"users")); + assert!(PROTECTED_TABLES.contains(&"blacklist")); + assert!(PROTECTED_TABLES.contains(&"api_keys")); + assert!(PROTECTED_TABLES.contains(&"queries")); + assert!(PROTECTED_TABLES.contains(&"permissions")); + } + + #[test] + fn test_is_protected() { + assert!(is_protected("users")); + assert!(is_protected("USERS")); // case-insensitive + assert!(!is_protected("orders")); + } +} +``` + +- [ ] **Step 2: Run test to confirm it fails** + +```bash +cargo test test_protected_tables_list test_is_protected +``` +Expected: FAIL — `PROTECTED_TABLES` and `is_protected` not defined yet. + +- [ ] **Step 3: Add the denylist and helper** + +At the top of `src/routes/admin/tables.rs`, after the `use` imports, add: + +```rust +const PROTECTED_TABLES: &[&str] = &["users", "blacklist", "api_keys", "queries", "permissions"]; + +fn is_protected(name: &str) -> bool { + let lower = name.to_lowercase(); + PROTECTED_TABLES.iter().any(|&t| t == lower) +} +``` + +- [ ] **Step 4: Guard `drop_table`** + +In `drop_table`, after `validate_identifier(&name)?;`, add: +```rust +if is_protected(&name) { + return Err(StatusCode::FORBIDDEN); +} +``` + +- [ ] **Step 5: Guard `create_table`** + +In `create_table`, after `validate_identifier(&body.name)?;`, add: +```rust +if is_protected(&body.name) { + return Err(StatusCode::FORBIDDEN); +} +``` + +- [ ] **Step 6: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 7: Commit** + +```bash +git add src/routes/admin/tables.rs +git commit -m "fix: block DDL operations on protected system tables" +``` + +--- + +## Task 6: Eliminate NULL_SENTINEL — thread `serde_json::Value` through `build_query` + +**Files:** +- Modify: `src/routes/crud.rs` (signature of `build_query`, binding loop, password hashing) + +**The bug:** `"\x00NULL"` is an in-band sentinel — a real string field containing those bytes would be silently written as SQL NULL. + +- [ ] **Step 1: Update `build_query` signature and return type** + +Change the function signature and all `Vec` params returns to `Vec`. Full new function (replace lines 27-114): + +```rust +/// Returns (sql, ordered_param_values, cache_key) +pub fn build_query( + method: &str, + table: &str, + id: Option<&str>, + body_cols: &[(String, Value)], + filter_cols: &[(String, String)], +) -> Result<(String, Vec, String)> { + if !crate::routes::is_valid_identifier(table) { + return Err(anyhow!("invalid identifier: {}", table)); + } + for (col, _) in body_cols.iter() { + if !crate::routes::is_valid_identifier(col) { + return Err(anyhow!("invalid identifier: {}", col)); + } + } + for (col, _) in filter_cols.iter() { + if !crate::routes::is_valid_identifier(col) { + return Err(anyhow!("invalid identifier: {}", col)); + } + } + + let mut sorted_body = body_cols.to_vec(); + sorted_body.sort_by(|a, b| a.0.cmp(&b.0)); + let mut sorted_filters = filter_cols.to_vec(); + sorted_filters.sort_by(|a, b| a.0.cmp(&b.0)); + + match method.to_uppercase().as_str() { + "GET" => { + if let Some(id_val) = id { + let sql = format!("SELECT * FROM {} WHERE id = $1", table); + let key = format!("GET:{}:~id", table); + Ok((sql, vec![Value::String(id_val.to_string())], key)) + } else if sorted_filters.is_empty() { + let sql = format!("SELECT * FROM {}", table); + let key = format!("GET:{}:", table); + Ok((sql, vec![], key)) + } else { + let col_names: Vec = sorted_filters.iter().map(|(c, _)| c.clone()).collect(); + let where_clause: Vec = col_names + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let sql = format!("SELECT * FROM {} WHERE {}", table, where_clause.join(" AND ")); + let params: Vec = sorted_filters.iter().map(|(_, v)| Value::String(v.clone())).collect(); + let key = format!("GET:{}:{}", table, col_names.join(",")); + Ok((sql, params, key)) + } + } + "POST" => { + if sorted_body.is_empty() { + return Err(anyhow!("POST requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let placeholders: Vec = (1..=cols.len()).map(|i| format!("${}", i)).collect(); + let sql = format!( + "INSERT INTO {} ({}) VALUES ({}) RETURNING *", + table, + cols.join(", "), + placeholders.join(", ") + ); + let params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + let key = format!("POST:{}:{}", table, cols.join(",")); + Ok((sql, params, key)) + } + "PUT" => { + let id_val = id.ok_or_else(|| anyhow!("PUT requires an id"))?; + if sorted_body.is_empty() { + return Err(anyhow!("PUT requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let set_clause: Vec = cols + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let id_placeholder = cols.len() + 1; + let sql = format!( + "UPDATE {} SET {} WHERE id = ${} RETURNING *", + table, + set_clause.join(", "), + id_placeholder + ); + let mut params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + params.push(Value::String(id_val.to_string())); + let key = format!("PUT:{}:{}:by_id", table, cols.join(",")); + Ok((sql, params, key)) + } + "DELETE" => { + let id_val = id.ok_or_else(|| anyhow!("DELETE requires an id"))?; + let sql = format!("DELETE FROM {} WHERE id = $1", table); + let key = format!("DELETE:{}:by_id", table); + Ok((sql, vec![Value::String(id_val.to_string())], key)) + } + m => Err(anyhow!("unsupported method: {}", m)), + } +} +``` + +- [ ] **Step 2: Update `handle_crud` — simplify body collection and remove sentinel** + +Replace the body collection block (lines 206-234) in `handle_crud`: + +```rust +// Body params: collect as typed Values directly +let mut body_cols: Vec<(String, Value)> = body + .map(|Json(b)| b.into_iter().collect()) + .unwrap_or_default(); + +// Hash the password field for the users table before building the query. +if table == "users" && matches!(method_str.to_uppercase().as_str(), "POST" | "PUT") { + if let Some(pos) = body_cols.iter().position(|(k, _)| k == "password") { + let (_, val) = body_cols.remove(pos); + if let Value::String(plaintext) = val { + let hash = bcrypt::hash(&plaintext, bcrypt::DEFAULT_COST) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + body_cols.push(("password_hash".to_string(), Value::String(hash))); + } + } +} +``` + +- [ ] **Step 3: Update the binding loop in `handle_crud`** + +Replace the binding loop (after `let mut q = sqlx::query(&sql);`): + +```rust +let mut q = sqlx::query(&sql); +for val in ¶ms_vals { + match val { + Value::Null => q = q.bind(Option::::None), + Value::Bool(b) => q = q.bind(*b), + Value::Number(n) => { + if let Some(i) = n.as_i64() { + q = q.bind(i); + } else if let Some(f) = n.as_f64() { + q = q.bind(f); + } else { + q = q.bind(n.to_string()); + } + } + Value::String(s) => q = q.bind(s.as_str()), + other => q = q.bind(other.to_string()), + } +} +``` + +- [ ] **Step 4: Update unit tests for `build_query` to use `Value`** + +In the `#[cfg(test)]` block at the bottom of `src/routes/crud.rs`, update all `build_query` calls (the signature now takes `&[(String, Value)]` for body_cols and returns `Vec`). + +Update `test_build_insert`: +```rust +#[test] +fn test_build_insert() { + let cols = vec![ + ("email".into(), Value::String("a@b.com".into())), + ("name".into(), Value::String("Alice".into())), + ]; + let (sql, params, key) = build_query("POST", "users", None, &cols, &[]).unwrap(); + assert_eq!(sql, "INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *"); + assert_eq!(params, vec![Value::String("a@b.com".into()), Value::String("Alice".into())]); + assert_eq!(key, "POST:users:email,name"); +} +``` + +Update `test_build_update`: +```rust +#[test] +fn test_build_update() { + let cols = vec![("name".into(), Value::String("Bob".into()))]; + let (sql, params, key) = build_query("PUT", "users", Some("7"), &cols, &[]).unwrap(); + assert_eq!(sql, "UPDATE users SET name = $1 WHERE id = $2 RETURNING *"); + assert_eq!(params, vec![Value::String("Bob".into()), Value::String("7".into())]); + assert_eq!(key, "PUT:users:name:by_id"); +} +``` + +Update `test_build_select_by_id` (already changed key in Task 3): +```rust +#[test] +fn test_build_select_by_id() { + let (sql, params, key) = build_query("GET", "orders", Some("42"), &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders WHERE id = $1"); + assert_eq!(params, vec![Value::String("42".into())]); + assert_eq!(key, "GET:orders:~id"); +} +``` + +Update `test_build_delete`: +```rust +#[test] +fn test_build_delete() { + let (sql, params, key) = build_query("DELETE", "users", Some("3"), &[], &[]).unwrap(); + assert_eq!(sql, "DELETE FROM users WHERE id = $1"); + assert_eq!(params, vec![Value::String("3".into())]); + assert_eq!(key, "DELETE:users:by_id"); +} +``` + +Update `test_build_select_all` (no body/filter params, just check it compiles): +```rust +#[test] +fn test_build_select_all() { + let (sql, params, key) = build_query("GET", "orders", None, &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders"); + assert!(params.is_empty()); + assert_eq!(key, "GET:orders:"); +} +``` + +Update `test_build_select_with_filters`: +```rust +#[test] +fn test_build_select_with_filters() { + let filters = vec![("status".into(), "active".into()), ("role".into(), "admin".into())]; + let (sql, params, key) = build_query("GET", "users", None, &[], &filters).unwrap(); + assert_eq!(sql, "SELECT * FROM users WHERE role = $1 AND status = $2"); + assert_eq!(params, vec![Value::String("admin".into()), Value::String("active".into())]); + assert_eq!(key, "GET:users:role,status"); +} +``` + +`test_rejects_invalid_table_name` needs no change. + +- [ ] **Step 5: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 6: Commit** + +```bash +git add src/routes/crud.rs +git commit -m "fix: eliminate NULL_SENTINEL by threading serde_json::Value through build_query" +``` + +--- + +## Task 7: Stash Claims in `blacklist_layer` to eliminate double DB hit + +**Files:** +- Modify: `src/auth/middleware.rs` + +**The fix:** Add an `authenticate()` helper. `blacklist_layer` stashes resolved `Claims` in request extensions. All `require_*` functions check extensions first, skipping the DB call if already authenticated. + +- [ ] **Step 1: Rewrite `src/auth/middleware.rs`** + +Replace the entire file: + +```rust +use axum::{ + extract::{Request, State}, + http::StatusCode, + middleware::Next, + response::Response, +}; + +use crate::{auth::{decode_jwt, resolve_api_key, Claims}, state::AppState}; + +/// Resolves a Bearer token to Claims, trying JWT then API key. +/// On success, inserts Claims into request extensions so downstream middleware +/// can reuse them without hitting the database again. +async fn authenticate( + token: &str, + state: &AppState, + req: &mut Request, +) -> Option { + if let Some(existing) = req.extensions().get::().cloned() { + return Some(existing); + } + let claims = if let Ok(c) = decode_jwt(token, &state.config.jwt_secret) { + c + } else { + resolve_api_key(token, &state.pool).await? + }; + req.extensions_mut().insert(claims.clone()); + Some(claims) +} + +pub async fn blacklist_layer( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let method = req.method().as_str().to_uppercase(); + let path = req.uri().path().to_string(); + let caller_mask = if let Some(token) = extract_bearer(&req) { + authenticate(&token, &state, &mut req) + .await + .map(|c| c.permissions_mask()) + .unwrap_or(0) + } else { + 0 + }; + if state.blacklist_cache.is_blocked(&method, &path, caller_mask).await { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub fn extract_bearer(req: &Request) -> Option { + req.headers() + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(|s| s.to_string()) +} + +pub async fn require_auth( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + Ok(next.run(req).await) +} + +pub async fn require_super_admin( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::SUPER_ADMIN) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub async fn require_admin_query( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_QUERY) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub async fn require_admin_cache( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_CACHE) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} +``` + +- [ ] **Step 2: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 3: Commit** + +```bash +git add src/auth/middleware.rs +git commit -m "fix: stash Claims in request extensions to eliminate double DB hit per API key request" +``` + +--- + +## Task 8: Enforce READ/WRITE/DELETE permission bits in CRUD handler + +**Files:** +- Modify: `src/routes/crud.rs` + +- [ ] **Step 1: Add `Extension(claims)` to `handle_crud` and check permissions** + +Change the `handle_crud` signature to extract `Claims`: + +```rust +pub async fn handle_crud( + State(state): State, + method: Method, + Extension(claims): Extension, + Path(params): Path>, + Query(query_params): Query>, + body: Option>>, +) -> Result, StatusCode> { +``` + +Then add permission check immediately after extracting `method_str`: + +```rust +let method_str = method.as_str(); + +// Enforce permission bits before doing any work. +let required_bit = match method_str.to_uppercase().as_str() { + "GET" => crate::auth::permissions::READ, + "POST" | "PUT" => crate::auth::permissions::WRITE, + "DELETE" => crate::auth::permissions::DELETE, + _ => return Err(StatusCode::METHOD_NOT_ALLOWED), +}; +if !claims.has_permission(required_bit) { + return Err(StatusCode::FORBIDDEN); +} +``` + +- [ ] **Step 2: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. (`build_query` unit tests don't call `handle_crud`, so they're unaffected.) + +- [ ] **Step 3: Commit** + +```bash +git add src/routes/crud.rs +git commit -m "fix: enforce READ/WRITE/DELETE permission bits in CRUD handler" +``` + +--- + +## Task 9: Add configurable CORS and body size limit + +**Files:** +- Modify: `src/config.rs` +- Modify: `src/main.rs` + +- [ ] **Step 1: Add `cors_origins` to `Config`** + +In `src/config.rs`, add the field and parsing: + +```rust +use anyhow::Result; + +#[derive(Clone, Debug)] +pub struct Config { + pub database_url: String, + pub jwt_secret: String, + pub jwt_expiry_secs: u64, + pub cache_max_capacity: usize, + pub cache_idle_timeout_secs: u64, + pub cache_sweep_interval_secs: u64, + /// Comma-separated list of allowed CORS origins, or "*" for permissive. + /// If empty, no CORS headers are added. + pub cors_origins: Vec, +} + +impl Config { + pub fn from_env() -> Result { + Ok(Self { + database_url: std::env::var("DATABASE_URL")?, + jwt_secret: std::env::var("JWT_SECRET")?, + jwt_expiry_secs: std::env::var("JWT_EXPIRY_SECS") + .unwrap_or_else(|_| "3600".into()) + .parse()?, + cache_max_capacity: std::env::var("CACHE_MAX_CAPACITY") + .unwrap_or_else(|_| "10000".into()) + .parse()?, + cache_idle_timeout_secs: std::env::var("CACHE_IDLE_TIMEOUT_SECS") + .unwrap_or_else(|_| "300".into()) + .parse()?, + cache_sweep_interval_secs: std::env::var("CACHE_SWEEP_INTERVAL_SECS") + .unwrap_or_else(|_| "60".into()) + .parse()?, + cors_origins: std::env::var("CORS_ORIGINS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(), + }) + } +} +``` + +- [ ] **Step 2: Update `.env.example`** + +Add `CORS_ORIGINS=` (empty, no CORS by default) to `.env.example`. + +- [ ] **Step 3: Update `src/main.rs` imports and app builder** + +Add imports at the top of `src/main.rs`: +```rust +use axum::extract::DefaultBodyLimit; +use axum::http::{header, HeaderValue, Method}; +use tower_http::cors::{Any, CorsLayer}; +``` + +Replace `CorsLayer::permissive()` in the app builder with a configured layer. The CRUD routes also get a body size limit. Replace the `crud_routes` and `app` blocks: + +```rust +let crud_routes = Router::new() + .route("/api/:table", get(handle_crud).post(handle_crud)) + .route("/api/:table/", get(handle_crud).post(handle_crud)) + .route("/api/:table/:id", get(handle_crud).put(handle_crud).delete(handle_crud)) + .route("/api/:table/:id/", get(handle_crud).put(handle_crud).delete(handle_crud)) + .layer(DefaultBodyLimit::max(1 * 1024 * 1024)) // 1 MB + .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)) + .route_layer(middleware::from_fn_with_state(state.clone(), blacklist_layer)); + +let cors_layer = build_cors(&config.cors_origins); + +let app = Router::new() + .route("/auth/login", post(login)) + .merge(crud_routes) + .nest("/api/admin", admin_router(state.clone())) + .nest_service("/", ServeDir::new("ui/dist").fallback(ServeFile::new("ui/dist/index.html"))) + .layer(cors_layer) + .with_state(state); +``` + +Add the `build_cors` helper function (before `main`): + +```rust +fn build_cors(origins: &[String]) -> CorsLayer { + if origins.is_empty() { + return CorsLayer::new(); + } + if origins.iter().any(|o| o == "*") { + return CorsLayer::permissive(); + } + let parsed: Vec = origins + .iter() + .filter_map(|o| o.parse().ok()) + .collect(); + CorsLayer::new() + .allow_origin(parsed) + .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE, Method::OPTIONS]) + .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION]) +} +``` + +- [ ] **Step 4: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 5: Commit** + +```bash +git add src/config.rs src/main.rs .env.example +git commit -m "fix: replace permissive CORS with configured origins; add 1MB body size limit" +``` + +--- + +## Task 10: First-user interactive setup (replace hardcoded admin/admin) + +**Files:** +- Modify: `src/main.rs` + +**Behavior:** On startup, if no users exist in the database, the server prompts on stdin for a username and password, creates that user with full permissions (mask=63), then starts serving. Routes are locked down by auth from the first request — there is no magic credential. + +- [ ] **Step 1: Add `use std::io::Write;` import to `src/main.rs`** + +In `src/main.rs` imports, add: +```rust +use std::io::{self, Write}; +``` + +- [ ] **Step 2: Replace the admin seed block** + +Remove lines 42-56 in `src/main.rs` (the current admin seed): +```rust +// DELETE all of this: +let count: i64 = sqlx::query_scalar::<_, Option>("SELECT COUNT(*) FROM users WHERE username = 'admin'") + .fetch_one(&pool) + .await? + .unwrap_or(0); +if count == 0 { + let hash = bcrypt::hash("admin", bcrypt::DEFAULT_COST)?; + sqlx::query( + "INSERT INTO users (username, password_hash, permissions_mask) VALUES ('admin', $1, '63')" + ) + .bind(hash) + .execute(&pool) + .await?; + tracing::info!("seeded admin user"); +} +``` + +Replace with: +```rust +// If no users exist, prompt to create the first admin. +let user_count: i64 = sqlx::query_scalar::<_, Option>("SELECT COUNT(*) FROM users") + .fetch_one(&pool) + .await? + .unwrap_or(0); +if user_count == 0 { + println!("\nNo users found. Create the first admin account."); + print!("Username: "); + io::stdout().flush()?; + let mut username = String::new(); + io::stdin().read_line(&mut username)?; + let username = username.trim().to_string(); + if username.is_empty() { + anyhow::bail!("username cannot be empty"); + } + + print!("Password: "); + io::stdout().flush()?; + let mut password = String::new(); + io::stdin().read_line(&mut password)?; + let password = password.trim().to_string(); + if password.is_empty() { + anyhow::bail!("password cannot be empty"); + } + + let hash = bcrypt::hash(&password, bcrypt::DEFAULT_COST)?; + sqlx::query( + "INSERT INTO users (username, password_hash, permissions_mask) VALUES ($1, $2, '63')", + ) + .bind(&username) + .bind(hash) + .execute(&pool) + .await?; + tracing::info!("created first admin user: {}", username); + println!("Admin user '{}' created. Starting server...\n", username); +} +``` + +- [ ] **Step 3: Run tests** + +```bash +cargo test +``` +Expected: all tests pass (this is startup logic, not unit-testable without a DB). + +- [ ] **Step 4: Commit** + +```bash +git add src/main.rs +git commit -m "fix: replace hardcoded admin/admin seed with interactive first-user setup on empty DB" +``` + +--- + +## Task 11: Remove spurious `mut` on `body_cols_typed` + +> **Note:** After Task 6, `body_cols_typed` no longer exists — this was eliminated when the body collection was simplified. Verify the `mut` warning is gone. + +- [ ] **Step 1: Confirm no `mut` warning** + +```bash +cargo build 2>&1 | grep "unused_mut\|body_cols_typed" +``` +Expected: no output (variable was removed in Task 6). + +If the warning still appears for another variable, find and remove the `mut`: +```bash +cargo build 2>&1 | grep "warning.*mut" +``` +Fix any remaining spurious `mut` annotations. + +- [ ] **Step 2: Commit if any change was needed** + +```bash +git add src/routes/crud.rs +git commit -m "fix: remove spurious mut annotations" +``` + +--- + +## Self-Review + +**Spec coverage check:** +- C1 (CRUD permissions) → Task 8 ✓ +- C2 (admin/admin seed) → Task 10 ✓ +- C3 (protected tables) → Task 5 ✓ +- C4 (prefix substitution) → Task 2 ✓ +- I1 (cache key collision) → Task 3 ✓ +- I2 (double DB hit) → Task 7 ✓ +- I3 (NULL_SENTINEL) → Task 6 ✓ +- I4 (unix_now panic) → Task 1 ✓ +- M1 (duplicate validator) → Task 4 ✓ +- M3 (permissive CORS) → Task 9 ✓ +- M5 (body size limit) → Task 9 ✓ +- M6 (spurious mut) → Task 11 ✓ + +**Dependency order:** +- Task 4 (shared validator) must run before Task 5 (it uses `is_valid_identifier`) +- Task 6 (Value params) must run before Task 8 (handle_crud signature stabilizes) +- Task 7 (stash Claims) must run before Task 8 (handle_crud reads claims from extensions) +- All other tasks are independent + +**Type consistency check:** +- `build_query` returns `Vec` after Task 6; all callers updated in the same task ✓ +- `is_valid_identifier` returns `bool` (added Task 4); callers in Tasks 4 and 5 check `!is_valid_identifier(...)` ✓ +- `authenticate()` returns `Option` (Task 7); all require_* callers use `.ok_or(UNAUTHORIZED)?` ✓ diff --git a/docs/superpowers/specs/2026-06-16-mercury-design.md b/docs/superpowers/specs/2026-06-16-mercury-design.md new file mode 100644 index 0000000..b5a1549 --- /dev/null +++ b/docs/superpowers/specs/2026-06-16-mercury-design.md @@ -0,0 +1,323 @@ +# Mercury — Design Spec +**Date:** 2026-06-16 + +## Overview + +Mercury is a monolithic, high-performance universal CRUD API written in Rust. It accepts HTTP requests, maps them to PostgreSQL tables, generates and caches SQL dynamically, and exposes an admin suite (with a Vue 3 frontend) for managing queries, users, permissions, and route security. A JWT-based bitmask permission system gates all admin operations. + +--- + +## Architecture + +``` +HTTP Request + ↓ + Blacklist Middleware (in-memory glob match) + ↓ + Auth Middleware (JWT decode + permission bit check, admin routes only) + ↓ + Axum Router + ↓ + Query Cache (DashMap) + ↓ cache miss + Query Registry (PostgreSQL: queries table) + ↓ query not yet registered + Query Builder (auto-generates SQL from route + HTTP method) + ↓ + PostgreSQL (sqlx PgPool) +``` + +**Stack:** +- `axum` — async HTTP framework (tokio-native) +- `sqlx` — async PostgreSQL driver, raw query support, compile-time checked migrations +- `DashMap` — concurrent hashmap for the query cache +- `glob` — compiled pattern matching for the route blacklist +- `jsonwebtoken` — JWT encode/decode +- Vue 3 + Vite + `@nychthemeron/library` — frontend, served as static files by Rust +- `tower-http::ServeDir` — serves `ui/dist/` at `/` + +--- + +## Endpoints + +### Public + +``` +POST /auth/login → returns JWT +``` + +### CRUD (no auth, blacklist-checked) + +``` +GET /api/{table} → SELECT * FROM {table} [?col=val filters] +GET /api/{table}/{id} → SELECT * FROM {table} WHERE id = {id} +POST /api/{table} → INSERT INTO {table} +PUT /api/{table}/{id} → UPDATE {table} WHERE id = {id} +DELETE /api/{table}/{id} → DELETE FROM {table} WHERE id = {id} +``` + +`users` and `permissions` are blacklisted by default — only accessible via the admin suite. + +### Admin — Query Registry (JWT + `ADMIN_QUERY` bit) + +``` +GET /admin/queries → list all registered queries +POST /admin/queries → register raw SQL template +GET /admin/queries/{identifier} → get query by slug identifier +PUT /admin/queries/{identifier} → update SQL template or metadata +DELETE /admin/queries/{identifier} → remove from registry + evict from cache +GET /admin/queries/{identifier}/execute → execute query with ?param=val bindings +``` + +`{identifier}` is the human-readable slug (e.g. `get-user-orders`), not the internal UUID. The UUID is used internally only. + +### Admin — Cache (JWT + `ADMIN_CACHE` bit) + +``` +GET /admin/cache/stats → current size, hit count, miss count +DELETE /admin/cache → flush entire cache +``` + +### Admin — Users (JWT + `SUPER_ADMIN` bit) + +``` +GET /admin/users → list users +POST /admin/users → create user +GET /admin/users/{id} → get user +PUT /admin/users/{id} → update user +DELETE /admin/users/{id} → delete user +POST /admin/users/{id}/permissions/grant/{bit_value} → OR bit into mask +DELETE /admin/users/{id}/permissions/revoke/{bit_value} → AND NOT bit from mask +``` + +### Admin — Permissions (JWT + `SUPER_ADMIN` bit) + +``` +GET /admin/permissions → list all permission definitions +POST /admin/permissions → create custom permission (auto-assigns next available bit_value) +PUT /admin/permissions/{id} → update name/description +DELETE /admin/permissions/{id} → remove permission definition +``` + +### Admin — Blacklist (JWT + `SUPER_ADMIN` bit) + +``` +GET /admin/blacklist → list all entries +POST /admin/blacklist → add route pattern +PUT /admin/blacklist/{id} → update entry +DELETE /admin/blacklist/{id} → remove entry +``` + +Any write to the blacklist immediately reloads the in-memory blacklist from the DB. + +### Frontend (served by Rust) + +``` +GET / → serves ui/dist/index.html (SPA entry) +GET /assets/* → static assets +``` + +--- + +## Database Schema + +### `users` +| column | type | notes | +|---|---|---| +| id | SERIAL PRIMARY KEY | | +| username | VARCHAR UNIQUE NOT NULL | | +| password_hash | TEXT NOT NULL | bcrypt | +| permissions_mask | NUMERIC NOT NULL DEFAULT 0 | u128 bitmask | +| created_at | TIMESTAMPTZ NOT NULL DEFAULT now() | | + +### `permissions` +| column | type | notes | +|---|---|---| +| id | SERIAL PRIMARY KEY | | +| name | VARCHAR UNIQUE NOT NULL | e.g. `READ` | +| bit_value | NUMERIC UNIQUE NOT NULL | power of 2, up to 2^127 | +| description | TEXT | | + +### `queries` +| column | type | notes | +|---|---|---| +| id | UUID PRIMARY KEY DEFAULT gen_random_uuid() | | +| identifier | VARCHAR UNIQUE NOT NULL | human-readable slug | +| sql_template | TEXT NOT NULL | raw SQL with :param placeholders | +| description | TEXT | | +| created_at | TIMESTAMPTZ NOT NULL DEFAULT now() | | +| updated_at | TIMESTAMPTZ NOT NULL DEFAULT now() | | + +### `blacklist` +| column | type | notes | +|---|---|---| +| id | SERIAL PRIMARY KEY | | +| pattern | VARCHAR NOT NULL | glob-style, e.g. `/api/users/**` | +| method | VARCHAR | NULL = all methods | +| reason | TEXT | | +| active | BOOLEAN NOT NULL DEFAULT true | | +| created_at | TIMESTAMPTZ NOT NULL DEFAULT now() | | + +### Seed Data (migration) +Default permission definitions: + +| name | bit_value | +|---|---| +| READ | 1 | +| WRITE | 2 | +| DELETE | 4 | +| ADMIN_QUERY | 8 | +| ADMIN_CACHE | 16 | +| SUPER_ADMIN | 32 | + +Default user: `admin` / `admin`, `permissions_mask = 63` (all bits set). + +Default blacklist entries: `/api/users/**` and `/api/permissions/**` (method: NULL). + +--- + +## Query Cache + +**Structure:** `DashMap` + +- Key: deterministic string derived from `{METHOD}:{table}:{params}` for auto-generated queries, or query `identifier` for named queries +- Value: the compiled query + timestamp of last access +- Hit/miss counters: two `AtomicU64` values on the shared state struct + +**Eviction:** a tokio background task runs every `CACHE_SWEEP_INTERVAL_SECS`. It iterates the map and removes entries where `last_accessed.elapsed() > CACHE_IDLE_TIMEOUT_SECS`. + +**Capacity:** before inserting a new entry, if `cache.len() >= CACHE_MAX_CAPACITY`, the entry with the oldest `last_accessed` is evicted first. + +**Cache invalidation:** deleting or updating a query via the admin suite immediately removes it from the DashMap. + +--- + +## Blacklist Cache + +**Structure:** `Arc>>` + +- Loaded from DB at startup +- Reloaded (write lock, full rebuild from DB) on any admin write to the `blacklist` table +- Checked in middleware on every request before routing: if any active entry matches `(method, path)`, return `403 Forbidden` + +--- + +## Permission System + +Permissions are u128 bitmasks. The JWT claims embed the user's current `permissions_mask`. Middleware extracts the JWT and performs a bitwise AND check — no DB lookup per request. + +``` +READ = 1 +WRITE = 2 +DELETE = 4 +ADMIN_QUERY = 8 +ADMIN_CACHE = 16 +SUPER_ADMIN = 32 +``` + +Custom permissions auto-assign the next unused power-of-2 bit_value. Up to 128 distinct permission bits supported. + +`permissions_mask` stored as PostgreSQL `NUMERIC` (arbitrary precision), converted to/from `u128` in the Rust data layer. + +--- + +## JWT + +- Algorithm: HS256 +- Claims: `sub` (username), `permissions` (u128 as string), `exp` +- Secret: `JWT_SECRET` env var +- Passed as `Authorization: Bearer ` header +- Token expiry: configurable via `JWT_EXPIRY_SECS` + +--- + +## Configuration (env vars) + +```env +DATABASE_URL=postgres://mercury:mercury@db:5432/mercury +JWT_SECRET=changeme +JWT_EXPIRY_SECS=3600 +CACHE_MAX_CAPACITY=10000 +CACHE_IDLE_TIMEOUT_SECS=300 +CACHE_SWEEP_INTERVAL_SECS=60 +``` + +--- + +## Project Structure + +``` +Mercury/ + src/ + main.rs -- startup: config, DB pool, cache init, router mount + config.rs -- Config struct loaded from env + auth/ + mod.rs -- JWT encode/decode, Claims struct + middleware.rs -- axum middleware: validate JWT, check permission bit + cache/ + query_cache.rs -- DashMap cache + sweep task + hit/miss counters + blacklist_cache.rs -- Arc> + glob::Pattern, reload fn + db/ + pool.rs -- sqlx PgPool init + migrations/ -- .sql files, run via sqlx::migrate!() + 001_initial.sql -- all tables + seed data + routes/ + crud.rs -- generic /api/{table} handler + query builder + auth.rs -- /auth/login + admin/ + queries.rs + cache.rs + users.rs + permissions.rs + blacklist.rs + models/ + query.rs + user.rs + permission.rs + blacklist.rs + ui/ + .npmrc -- @nychthemeron:registry=https://git.mcpeakdev.com/api/packages/McPeakDev/npm/ + package.json + vite.config.ts + src/ + main.ts -- dark mode default, router, pinia init + App.vue + router/index.ts -- route guards: redirect /login if no JWT + stores/auth.ts -- JWT storage, permissions bitmask helpers + views/ + Login.vue + admin/ + Queries.vue + Users.vue + Permissions.vue + Blacklist.vue + Cache.vue + Cargo.toml + docker-compose.yml + Dockerfile -- multi-stage: Node build UI, Rust build API + .env.example +``` + +--- + +## Docker + +**Multi-stage Dockerfile:** +1. Stage 1 (node): install `@nychthemeron/library`, run `vite build` → `ui/dist/` +2. Stage 2 (rust): compile API, copy `ui/dist/` into final image +3. Final image runs the Rust binary; `tower-http::ServeDir` serves `ui/dist/` at `/` + +**docker-compose.yml:** +- `db` service: `postgres:16-alpine`, persistent volume, health check +- `api` service: built from Dockerfile, depends on `db`, `mem_limit` set, env vars from `.env` +- Migrations run at API startup via `sqlx::migrate!()` + +--- + +## Frontend Contract + +- Dark mode is the default; set via `@nychthemeron/library` theme config in `main.ts` +- Login page at `/login` calls `POST /auth/login`, stores JWT in `localStorage` +- All admin views require `SUPER_ADMIN` bit in JWT; route guard redirects to `/login` if absent +- Permission bitmask helpers in `stores/auth.ts`: `hasPermission(bit: number): boolean` +- Admin views wire directly to their respective admin endpoints diff --git a/pics/Mercury-Login.png b/pics/Mercury-Login.png new file mode 100644 index 0000000..7cbda99 Binary files /dev/null and b/pics/Mercury-Login.png differ diff --git a/pics/Mercury.png b/pics/Mercury.png new file mode 100644 index 0000000..4d04cf8 Binary files /dev/null and b/pics/Mercury.png differ diff --git a/src/auth/middleware.rs b/src/auth/middleware.rs new file mode 100644 index 0000000..6f9dcc0 --- /dev/null +++ b/src/auth/middleware.rs @@ -0,0 +1,106 @@ +use axum::{ + extract::{Request, State}, + http::StatusCode, + middleware::Next, + response::Response, +}; + +use crate::{auth::{decode_jwt, resolve_api_key, Claims}, state::AppState}; + +/// Resolves a Bearer token to Claims, trying JWT then API key. +/// Inserts Claims into request extensions on success so downstream +/// middleware can reuse them without an additional DB round-trip. +async fn authenticate( + token: &str, + state: &AppState, + req: &mut Request, +) -> Option { + if let Some(existing) = req.extensions().get::().cloned() { + return Some(existing); + } + let claims = if let Ok(c) = decode_jwt(token, &state.config.jwt_secret) { + c + } else { + resolve_api_key(token, &state.pool).await? + }; + req.extensions_mut().insert(claims.clone()); + Some(claims) +} + +pub async fn blacklist_layer( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let method = req.method().as_str().to_uppercase(); + let path = req.uri().path().to_string(); + let caller_mask = if let Some(token) = extract_bearer(&req) { + authenticate(&token, &state, &mut req) + .await + .map(|c| c.permissions_mask()) + .unwrap_or(0) + } else { + 0 + }; + if state.blacklist_cache.is_blocked(&method, &path, caller_mask).await { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub fn extract_bearer(req: &Request) -> Option { + req.headers() + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(|s| s.to_string()) +} + +pub async fn require_auth( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + Ok(next.run(req).await) +} + +pub async fn require_super_admin( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::SUPER_ADMIN) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub async fn require_admin_query( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_QUERY) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub async fn require_admin_cache( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_CACHE) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} diff --git a/src/auth/mod.rs b/src/auth/mod.rs new file mode 100644 index 0000000..fb6a7df --- /dev/null +++ b/src/auth/mod.rs @@ -0,0 +1,123 @@ +pub mod middleware; + +use anyhow::Result; +use chrono::Utc; +use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +#[allow(dead_code)] +pub mod permissions { + pub const READ: u128 = 1; + pub const WRITE: u128 = 2; + pub const DELETE: u128 = 4; + pub const ADMIN_QUERY: u128 = 8; + pub const ADMIN_CACHE: u128 = 16; + pub const SUPER_ADMIN: u128 = 32; +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Claims { + pub sub: String, + pub permissions: String, // u128 stored as decimal string + pub exp: usize, +} + +impl Claims { + pub fn permissions_mask(&self) -> u128 { + self.permissions.parse().unwrap_or(0) + } + + pub fn has_permission(&self, bit: u128) -> bool { + self.permissions_mask() & bit != 0 + } +} + +pub fn encode_jwt(username: &str, mask: u128, secret: &str, expiry_secs: u64) -> Result { + let exp = (Utc::now().timestamp() as u64 + expiry_secs) as usize; + let claims = Claims { + sub: username.to_string(), + permissions: mask.to_string(), + exp, + }; + let token = encode( + &Header::default(), + &claims, + &EncodingKey::from_secret(secret.as_bytes()), + )?; + Ok(token) +} + +/// Generates a new API key: `mrc_<32 random hex chars>`. +/// Returns `(plain_key, key_prefix, key_hash)`. +pub fn generate_api_key() -> (String, String, String) { + let raw = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple()); + let key = format!("mrc_{}", raw); + let prefix = raw[..8].to_string(); + let hash = hash_api_key(&key); + (key, prefix, hash) +} + +pub fn hash_api_key(key: &str) -> String { + format!("{:x}", Sha256::digest(key.as_bytes())) +} + +/// Resolves an API key token against the database. +/// Updates `last_used_at` on success. +pub async fn resolve_api_key(token: &str, pool: &sqlx::PgPool) -> Option { + if !token.starts_with("mrc_") { + return None; + } + let hash = hash_api_key(token); + let row: (String, String) = sqlx::query_as( + "UPDATE api_keys SET last_used_at = now() + WHERE key_hash = $1 AND (expires_at IS NULL OR expires_at > now()) + RETURNING name, permissions_mask", + ) + .bind(&hash) + .fetch_optional(pool) + .await + .ok()??; + + Some(Claims { + sub: row.0, + permissions: row.1, + exp: usize::MAX, + }) +} + +pub fn decode_jwt(token: &str, secret: &str) -> Result { + let data = decode::( + token, + &DecodingKey::from_secret(secret.as_bytes()), + &Validation::default(), + )?; + Ok(data.claims) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_encode_decode_roundtrip() { + let secret = "test_secret"; + let token = encode_jwt("alice", 63u128, secret, 3600).unwrap(); + let claims = decode_jwt(&token, secret).unwrap(); + assert_eq!(claims.sub, "alice"); + assert_eq!(claims.permissions_mask(), 63u128); + } + + #[test] + fn test_has_permission() { + let claims = Claims { + sub: "bob".into(), + permissions: "9".into(), // READ (1) + ADMIN_QUERY (8) + exp: 9999999999, + }; + assert!(claims.has_permission(permissions::READ)); + assert!(claims.has_permission(permissions::ADMIN_QUERY)); + assert!(!claims.has_permission(permissions::SUPER_ADMIN)); + } +} diff --git a/src/cache/mod.rs b/src/cache/mod.rs new file mode 100644 index 0000000..a1ca063 --- /dev/null +++ b/src/cache/mod.rs @@ -0,0 +1,2 @@ +pub mod sweep; +pub use sweep::spawn_sweep_task; diff --git a/src/cache/sweep.rs b/src/cache/sweep.rs new file mode 100644 index 0000000..01b2f52 --- /dev/null +++ b/src/cache/sweep.rs @@ -0,0 +1,15 @@ +use std::time::Duration; +use crate::state::QueryCache; + +pub fn spawn_sweep_task(cache: QueryCache, idle_timeout_secs: u64, sweep_interval_secs: u64) { + tokio::spawn(async move { + let interval = Duration::from_secs(sweep_interval_secs); + loop { + tokio::time::sleep(interval).await; + let now = crate::state::unix_now(); + cache.map.retain(|_, entry| { + now.saturating_sub(entry.last_accessed()) < idle_timeout_secs + }); + } + }); +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..8970d6a --- /dev/null +++ b/src/config.rs @@ -0,0 +1,57 @@ +use anyhow::Result; + +#[derive(Clone, Debug)] +pub struct Config { + pub database_url: String, + pub jwt_secret: String, + pub jwt_expiry_secs: u64, + pub cache_max_capacity: usize, + pub cache_idle_timeout_secs: u64, + pub cache_sweep_interval_secs: u64, + /// Comma-separated allowed CORS origins, or "*" for permissive. Empty = no CORS headers. + pub cors_origins: Vec, +} + +impl Config { + pub fn from_env() -> Result { + Ok(Self { + database_url: std::env::var("DATABASE_URL")?, + jwt_secret: std::env::var("JWT_SECRET")?, + jwt_expiry_secs: std::env::var("JWT_EXPIRY_SECS") + .unwrap_or_else(|_| "3600".into()) + .parse()?, + cache_max_capacity: std::env::var("CACHE_MAX_CAPACITY") + .unwrap_or_else(|_| "10000".into()) + .parse()?, + cache_idle_timeout_secs: std::env::var("CACHE_IDLE_TIMEOUT_SECS") + .unwrap_or_else(|_| "300".into()) + .parse()?, + cache_sweep_interval_secs: std::env::var("CACHE_SWEEP_INTERVAL_SECS") + .unwrap_or_else(|_| "60".into()) + .parse()?, + cors_origins: std::env::var("CORS_ORIGINS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_config_defaults() { + std::env::set_var("DATABASE_URL", "postgres://test"); + std::env::set_var("JWT_SECRET", "secret"); + let cfg = Config::from_env().unwrap(); + assert_eq!(cfg.jwt_expiry_secs, 3600); + assert_eq!(cfg.cache_max_capacity, 10_000); + assert_eq!(cfg.cache_idle_timeout_secs, 300); + assert_eq!(cfg.cache_sweep_interval_secs, 60); + assert!(cfg.cors_origins.is_empty()); + } +} diff --git a/src/db/migrations/001_initial.sql b/src/db/migrations/001_initial.sql new file mode 100644 index 0000000..e2b3711 --- /dev/null +++ b/src/db/migrations/001_initial.sql @@ -0,0 +1,48 @@ +CREATE EXTENSION IF NOT EXISTS pgcrypto; + +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + username VARCHAR(255) UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + permissions_mask TEXT NOT NULL DEFAULT '0', + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE permissions ( + id SERIAL PRIMARY KEY, + name VARCHAR(255) UNIQUE NOT NULL, + bit_value TEXT UNIQUE NOT NULL, + description TEXT +); + +CREATE TABLE queries ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + identifier VARCHAR(255) UNIQUE NOT NULL, + sql_template TEXT NOT NULL, + description TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE blacklist ( + id SERIAL PRIMARY KEY, + pattern VARCHAR(500) NOT NULL, + method VARCHAR(10), + reason TEXT, + active BOOLEAN NOT NULL DEFAULT true, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Seed permissions +INSERT INTO permissions (name, bit_value, description) VALUES + ('READ', '1', 'Can read via CRUD endpoints'), + ('WRITE', '2', 'Can insert/update via CRUD'), + ('DELETE', '4', 'Can delete via CRUD'), + ('ADMIN_QUERY', '8', 'Can manage query registry'), + ('ADMIN_CACHE', '16', 'Can manage cache'), + ('SUPER_ADMIN', '32', 'Full access'); + +-- Seed blacklist (users and permissions tables are admin-only) +INSERT INTO blacklist (pattern, method, reason, active) VALUES + ('/api/users/**', NULL, 'admin-only table', true), + ('/api/permissions/**', NULL, 'admin-only table', true); diff --git a/src/db/migrations/002_blacklist_system_tables.sql b/src/db/migrations/002_blacklist_system_tables.sql new file mode 100644 index 0000000..8823f83 --- /dev/null +++ b/src/db/migrations/002_blacklist_system_tables.sql @@ -0,0 +1,9 @@ +-- Block PostgreSQL system catalog tables from the public CRUD API. +-- The pg_ prefix covers pg_tables, pg_class, pg_user, pg_shadow, pg_authid, etc. +-- information_schema columns contain dots so they're already rejected by the +-- identifier validator, but we block them here for defense in depth. +INSERT INTO blacklist (pattern, method, reason, active) VALUES + ('/api/pg_*', NULL, 'postgresql system catalog', true), + ('/api/pg_*/**', NULL, 'postgresql system catalog', true), + ('/api/information_schema', NULL, 'postgresql information schema', true), + ('/api/information_schema/**', NULL, 'postgresql information schema', true); diff --git a/src/db/migrations/003_blacklist_bypass_permission.sql b/src/db/migrations/003_blacklist_bypass_permission.sql new file mode 100644 index 0000000..2efe878 --- /dev/null +++ b/src/db/migrations/003_blacklist_bypass_permission.sql @@ -0,0 +1,32 @@ +-- Allow blacklist entries to be bypassed by callers who hold a specific permission bit. +-- bypass_mask NULL means the rule blocks everyone unconditionally. +ALTER TABLE blacklist ADD COLUMN bypass_mask TEXT; + +-- Existing user/permission rules: SUPER_ADMIN (bit 32) can bypass them so the +-- admin UI can reach these tables via the generic /api/:table CRUD endpoint. +UPDATE blacklist +SET bypass_mask = '32' +WHERE pattern IN ('/api/users/**', '/api/permissions/**'); + +-- Add rules for queries and blacklist tables, which also need admin-only CRUD access. +INSERT INTO blacklist (pattern, method, reason, active, bypass_mask) VALUES + ('/api/users', NULL, 'admin-only table', true, '32'), + ('/api/permissions', NULL, 'admin-only table', true, '32'), + ('/api/queries', NULL, 'admin-only table', true, '32'), + ('/api/queries/**', NULL, 'admin-only table', true, '32'), + ('/api/blacklist', NULL, 'admin-only table', true, '32'), + ('/api/blacklist/**', NULL, 'admin-only table', true, '32'); + +-- Automatically update updated_at on queries mutations so the generic CRUD +-- endpoint doesn't need to know about that column. +CREATE OR REPLACE FUNCTION update_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER queries_updated_at + BEFORE UPDATE ON queries + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); diff --git a/src/db/migrations/004_blacklist_method_text.sql b/src/db/migrations/004_blacklist_method_text.sql new file mode 100644 index 0000000..b9582b5 --- /dev/null +++ b/src/db/migrations/004_blacklist_method_text.sql @@ -0,0 +1,2 @@ +-- Widen method column to support comma-separated multi-method values e.g. "GET,POST" +ALTER TABLE blacklist ALTER COLUMN method TYPE TEXT; diff --git a/src/db/migrations/005_api_keys.sql b/src/db/migrations/005_api_keys.sql new file mode 100644 index 0000000..75ef167 --- /dev/null +++ b/src/db/migrations/005_api_keys.sql @@ -0,0 +1,12 @@ +CREATE TABLE api_keys ( + id SERIAL PRIMARY KEY, + name VARCHAR(255) NOT NULL, + key_prefix VARCHAR(16) NOT NULL, + key_hash TEXT NOT NULL UNIQUE, + permissions_mask TEXT NOT NULL DEFAULT '0', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ, + last_used_at TIMESTAMPTZ +); + +CREATE INDEX idx_api_keys_hash ON api_keys(key_hash); diff --git a/src/db/migrations/006_seed_api_keys_blacklist.sql b/src/db/migrations/006_seed_api_keys_blacklist.sql new file mode 100644 index 0000000..1ddf16c --- /dev/null +++ b/src/db/migrations/006_seed_api_keys_blacklist.sql @@ -0,0 +1,5 @@ +-- Prevent raw CRUD access to the api_keys table (would expose key_hash). +-- The proper endpoints live at /api/admin/api-keys and are guarded by require_super_admin. +INSERT INTO blacklist (pattern, method, reason, active) VALUES + ('/api/api_keys', NULL, 'api key hashes must not be exposed via generic CRUD', true), + ('/api/api_keys/**', NULL, 'api key hashes must not be exposed via generic CRUD', true); diff --git a/src/db/mod.rs b/src/db/mod.rs new file mode 100644 index 0000000..620c68e --- /dev/null +++ b/src/db/mod.rs @@ -0,0 +1,2 @@ +pub mod pool; +pub use pool::create_pool; diff --git a/src/db/pool.rs b/src/db/pool.rs new file mode 100644 index 0000000..d2c4790 --- /dev/null +++ b/src/db/pool.rs @@ -0,0 +1,11 @@ +use anyhow::Result; +use sqlx::{postgres::PgPoolOptions, PgPool}; + +pub async fn create_pool(database_url: &str) -> Result { + let pool = PgPoolOptions::new() + .max_connections(10) + .connect(database_url) + .await?; + sqlx::migrate!("src/db/migrations").run(&pool).await?; + Ok(pool) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..6accdf5 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,148 @@ +mod auth; +mod cache; +mod config; +mod db; +mod models; +mod routes; +mod state; + +use std::io::{self, Write}; +use std::sync::Arc; + +use axum::{extract::DefaultBodyLimit, http::{header, HeaderValue, Method}, middleware, routing::{get, post}, Router}; +use tower_http::{cors::CorsLayer, services::{ServeDir, ServeFile}}; +use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; + +use crate::{ + auth::middleware::{blacklist_layer, require_auth}, + cache::spawn_sweep_task, + config::Config, + db::create_pool, + models::blacklist::BlacklistEntry, + routes::{ + admin::admin_router, + auth::login, + crud::handle_crud, + }, + state::{AppState, BlacklistCache, QueryCache}, +}; + +fn build_cors(origins: &[String]) -> CorsLayer { + if origins.is_empty() { + return CorsLayer::new(); + } + if origins.iter().any(|o| o == "*") { + return CorsLayer::permissive(); + } + let parsed: Vec = origins + .iter() + .filter_map(|o| o.parse().ok()) + .collect(); + CorsLayer::new() + .allow_origin(parsed) + .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE, Method::OPTIONS]) + .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION]) +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + dotenvy::dotenv().ok(); + + tracing_subscriber::registry() + .with(tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "mercury=info".into())) + .with(tracing_subscriber::fmt::layer()) + .init(); + + let config = Arc::new(Config::from_env()?); + let pool = create_pool(&config.database_url).await?; + + // If no users exist, prompt to create the first admin interactively. + let user_count: i64 = sqlx::query_scalar::<_, Option>("SELECT COUNT(*) FROM users") + .fetch_one(&pool) + .await? + .unwrap_or(0); + if user_count == 0 { + println!("\nNo users found. Create the first admin account."); + print!("Username: "); + io::stdout().flush()?; + let mut username = String::new(); + io::stdin().read_line(&mut username)?; + let username = username.trim().to_string(); + if username.is_empty() { + anyhow::bail!("username cannot be empty"); + } + + print!("Password: "); + io::stdout().flush()?; + let mut password = String::new(); + io::stdin().read_line(&mut password)?; + let password = password.trim().to_string(); + if password.is_empty() { + anyhow::bail!("password cannot be empty"); + } + + let hash = bcrypt::hash(&password, bcrypt::DEFAULT_COST)?; + sqlx::query( + "INSERT INTO users (username, password_hash, permissions_mask) VALUES ($1, $2, '63')", + ) + .bind(&username) + .bind(hash) + .execute(&pool) + .await?; + tracing::info!("created first admin user: {}", username); + println!("Admin user '{}' created. Starting server...\n", username); + } + + let query_cache = QueryCache::new(); + let blacklist_cache = BlacklistCache::new(); + + // Load blacklist from DB into memory + let entries = sqlx::query_as::<_, BlacklistEntry>( + "SELECT id, pattern, method, reason, active, bypass_mask, created_at FROM blacklist ORDER BY id" + ) + .fetch_all(&pool) + .await?; + blacklist_cache.load(entries).await; + + // Start cache sweep + spawn_sweep_task( + query_cache.clone(), + config.cache_idle_timeout_secs, + config.cache_sweep_interval_secs, + ); + + let state = AppState { + pool, + query_cache, + blacklist_cache, + config: config.clone(), + }; + + let crud_routes = Router::new() + .route("/api/:table", get(handle_crud).post(handle_crud)) + .route("/api/:table/", get(handle_crud).post(handle_crud)) + .route("/api/:table/:id", get(handle_crud).put(handle_crud).delete(handle_crud)) + .route("/api/:table/:id/", get(handle_crud).put(handle_crud).delete(handle_crud)) + .layer(DefaultBodyLimit::max(1 * 1024 * 1024)) + // require_auth is inner (added first); blacklist_layer is outer (added last, runs first). + // Order: blacklist check → auth check → handler. + .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)) + .route_layer(middleware::from_fn_with_state(state.clone(), blacklist_layer)); + + let cors_layer = build_cors(&config.cors_origins); + + let app = Router::new() + .route("/auth/login", post(login)) + .merge(crud_routes) + .nest("/api/admin", admin_router(state.clone())) + .nest_service("/", ServeDir::new("ui/dist").fallback(ServeFile::new("ui/dist/index.html"))) + .layer(cors_layer) + .with_state(state); + + let addr = std::net::SocketAddr::from(([0, 0, 0, 0], 3000)); + tracing::info!("listening on {}", addr); + let listener = tokio::net::TcpListener::bind(addr).await?; + axum::serve(listener, app).await?; + Ok(()) +} diff --git a/src/models/api_key.rs b/src/models/api_key.rs new file mode 100644 index 0000000..1981c74 --- /dev/null +++ b/src/models/api_key.rs @@ -0,0 +1,20 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct ApiKey { + pub id: i32, + pub name: String, + pub key_prefix: String, + pub permissions_mask: String, + pub created_at: DateTime, + pub expires_at: Option>, + pub last_used_at: Option>, +} + +#[derive(Debug, Deserialize)] +pub struct CreateApiKey { + pub name: String, + pub permissions_mask: Option, + pub expires_at: Option>, +} diff --git a/src/models/blacklist.rs b/src/models/blacklist.rs new file mode 100644 index 0000000..1ac312d --- /dev/null +++ b/src/models/blacklist.rs @@ -0,0 +1,28 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct BlacklistEntry { + pub id: i32, + pub pattern: String, + pub method: Option, + pub reason: Option, + pub active: bool, + pub bypass_mask: Option, + pub created_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateBlacklistEntry { + pub pattern: String, + pub method: Option, + pub reason: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateBlacklistEntry { + pub pattern: Option, + pub method: Option, + pub reason: Option, + pub active: Option, +} diff --git a/src/models/mod.rs b/src/models/mod.rs new file mode 100644 index 0000000..a83bc1d --- /dev/null +++ b/src/models/mod.rs @@ -0,0 +1,5 @@ +pub mod api_key; +pub mod blacklist; +pub mod permission; +pub mod query; +pub mod user; diff --git a/src/models/permission.rs b/src/models/permission.rs new file mode 100644 index 0000000..6383c89 --- /dev/null +++ b/src/models/permission.rs @@ -0,0 +1,21 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct Permission { + pub id: i32, + pub name: String, + pub bit_value: String, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct CreatePermission { + pub name: String, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdatePermission { + pub name: Option, + pub description: Option, +} diff --git a/src/models/query.rs b/src/models/query.rs new file mode 100644 index 0000000..07e469c --- /dev/null +++ b/src/models/query.rs @@ -0,0 +1,26 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct StoredQuery { + pub id: Uuid, + pub identifier: String, + pub sql_template: String, + pub description: Option, + pub created_at: DateTime, + pub updated_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateQuery { + pub identifier: String, + pub sql_template: String, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateQuery { + pub sql_template: Option, + pub description: Option, +} diff --git a/src/models/user.rs b/src/models/user.rs new file mode 100644 index 0000000..49b45d0 --- /dev/null +++ b/src/models/user.rs @@ -0,0 +1,32 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct User { + pub id: i32, + pub username: String, + #[serde(skip_serializing)] + pub password_hash: String, + pub permissions_mask: String, + pub created_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateUser { + pub username: String, + pub password: String, + pub permissions_mask: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateUser { + pub username: Option, + pub password: Option, + pub permissions_mask: Option, +} + +#[derive(Debug, Deserialize)] +pub struct LoginRequest { + pub username: String, + pub password: String, +} diff --git a/src/routes/admin/api_keys.rs b/src/routes/admin/api_keys.rs new file mode 100644 index 0000000..f937917 --- /dev/null +++ b/src/routes/admin/api_keys.rs @@ -0,0 +1,72 @@ +use axum::{ + extract::{Path, State}, + http::StatusCode, + Json, +}; +use serde_json::{json, Value}; + +use crate::{ + auth::generate_api_key, + models::api_key::{ApiKey, CreateApiKey}, + state::AppState, +}; + +pub async fn list_api_keys( + State(state): State, +) -> Result>, StatusCode> { + let keys = sqlx::query_as::<_, ApiKey>( + "SELECT id, name, key_prefix, permissions_mask, created_at, expires_at, last_used_at + FROM api_keys ORDER BY created_at DESC", + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(keys)) +} + +pub async fn create_api_key( + State(state): State, + Json(body): Json, +) -> Result, StatusCode> { + let (plain_key, key_prefix, key_hash) = generate_api_key(); + let mask = body.permissions_mask.unwrap_or_else(|| "0".into()); + + sqlx::query( + "INSERT INTO api_keys (name, key_prefix, key_hash, permissions_mask, expires_at) + VALUES ($1, $2, $3, $4, $5)", + ) + .bind(&body.name) + .bind(&key_prefix) + .bind(&key_hash) + .bind(&mask) + .bind(body.expires_at) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + Ok(Json(json!({ + "key": plain_key, + "prefix": key_prefix, + "name": body.name, + "permissions_mask": mask, + "note": "Store this key securely — it will not be shown again." + }))) +} + +pub async fn revoke_api_key( + State(state): State, + Path(id): Path, +) -> Result { + let rows = sqlx::query("DELETE FROM api_keys WHERE id = $1") + .bind(id) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .rows_affected(); + + if rows == 0 { + Err(StatusCode::NOT_FOUND) + } else { + Ok(StatusCode::NO_CONTENT) + } +} diff --git a/src/routes/admin/cache.rs b/src/routes/admin/cache.rs new file mode 100644 index 0000000..ca7dc11 --- /dev/null +++ b/src/routes/admin/cache.rs @@ -0,0 +1,24 @@ +use axum::{extract::State, http::StatusCode, Json}; +use serde_json::{json, Value}; +use axum::extract::Extension; + +use crate::{auth::Claims, state::AppState}; + +pub async fn cache_stats( + State(state): State, + Extension(_claims): Extension, +) -> Json { + Json(json!({ + "size": state.query_cache.len(), + "hits": state.query_cache.hits(), + "misses": state.query_cache.misses(), + })) +} + +pub async fn flush_cache( + State(state): State, + Extension(_claims): Extension, +) -> Result, StatusCode> { + state.query_cache.flush(); + Ok(Json(json!({ "flushed": true }))) +} diff --git a/src/routes/admin/mod.rs b/src/routes/admin/mod.rs new file mode 100644 index 0000000..049ec20 --- /dev/null +++ b/src/routes/admin/mod.rs @@ -0,0 +1,53 @@ +pub mod api_keys; +pub mod cache; +pub mod queries; +pub mod tables; + +use axum::{ + middleware, + routing::{delete, get}, + Router, +}; + +use crate::{ + auth::middleware::{require_admin_cache, require_admin_query, require_super_admin}, + state::AppState, +}; + +pub fn admin_router(state: AppState) -> Router { + let query_routes = Router::new() + .route("/:identifier/execute", get(queries::execute_query)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_admin_query, + )); + + let cache_routes = Router::new() + .route("/stats", get(cache::cache_stats)) + .route("/", delete(cache::flush_cache)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_admin_cache, + )); + + let super_routes = Router::new() + .route("/tables", get(tables::list_tables).post(tables::create_table)) + .route( + "/tables/:name", + get(tables::get_table_preview).delete(tables::drop_table), + ) + .route( + "/api-keys", + get(api_keys::list_api_keys).post(api_keys::create_api_key), + ) + .route("/api-keys/:id", delete(api_keys::revoke_api_key)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_super_admin, + )); + + Router::new() + .nest("/queries", query_routes) + .nest("/cache", cache_routes) + .merge(super_routes) +} diff --git a/src/routes/admin/queries.rs b/src/routes/admin/queries.rs new file mode 100644 index 0000000..483651b --- /dev/null +++ b/src/routes/admin/queries.rs @@ -0,0 +1,80 @@ +use axum::{ + extract::{Extension, Path, Query, State}, + http::StatusCode, + Json, +}; +use serde_json::Value; +use std::collections::HashMap; + +use crate::{auth::Claims, models::query::StoredQuery, state::AppState}; + +pub async fn execute_query( + State(state): State, + Extension(_claims): Extension, + Path(identifier): Path, + Query(params): Query>, +) -> Result, StatusCode> { + let stored = sqlx::query_as::<_, StoredQuery>( + "SELECT id, identifier, sql_template, description, created_at, updated_at FROM queries WHERE identifier = $1" + ) + .bind(&identifier) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let mut sql = stored.sql_template.clone(); + let mut bound_vals: Vec = Vec::new(); + let mut idx = 1usize; + let mut sorted_params: Vec<(String, String)> = params.into_iter().collect(); + sorted_params.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then(a.0.cmp(&b.0))); + for (name, val) in &sorted_params { + let placeholder = format!(":{}", name); + if sql.contains(&placeholder) { + sql = sql.replace(&placeholder, &format!("${}", idx)); + bound_vals.push(val.clone()); + idx += 1; + } + } + + let mut q = sqlx::query(&sql); + for val in &bound_vals { + q = q.bind(val.as_str()); + } + + let rows = q + .fetch_all(&state.pool) + .await + .map_err(|e| { + tracing::error!("query execution error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + let json_rows: Vec = rows + .into_iter() + .map(crate::routes::crud::pg_row_to_json) + .collect(); + + Ok(Json(Value::Array(json_rows))) +} + +#[cfg(test)] +mod tests { + #[test] + fn test_prefix_param_substitution_order() { + let template = "SELECT * FROM t WHERE user_id = :user_id AND username = :username"; + let mut params: Vec<(String, String)> = vec![ + ("user_id".into(), "42".into()), + ("username".into(), "alice".into()), + ]; + params.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then(a.0.cmp(&b.0))); + let mut sql = template.to_string(); + for (i, (name, _)) in params.iter().enumerate() { + sql = sql.replace(&format!(":{}", name), &format!("${}", i + 1)); + } + assert!(!sql.contains(":username"), "placeholder not replaced: {}", sql); + assert!(!sql.contains(":user_id"), "placeholder not replaced: {}", sql); + // username (len 8) comes first → $1; user_id (len 7) → $2 + assert_eq!(sql, "SELECT * FROM t WHERE user_id = $2 AND username = $1"); + } +} diff --git a/src/routes/admin/tables.rs b/src/routes/admin/tables.rs new file mode 100644 index 0000000..375716f --- /dev/null +++ b/src/routes/admin/tables.rs @@ -0,0 +1,239 @@ +use axum::{ + extract::{Extension, Path, State}, + http::StatusCode, + Json, +}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sqlx::Row; + +use crate::{auth::Claims, routes::crud::pg_row_to_json, state::AppState}; + +const ALLOWED_TYPES: &[&str] = &[ + "TEXT", "INTEGER", "BIGINT", "SMALLINT", "BOOLEAN", "NUMERIC", + "FLOAT4", "FLOAT8", "UUID", "TIMESTAMPTZ", "DATE", "JSONB", +]; + +const PROTECTED_TABLES: &[&str] = &["users", "blacklist", "api_keys", "queries", "permissions"]; + +fn is_protected(name: &str) -> bool { + let lower = name.to_lowercase(); + PROTECTED_TABLES.iter().any(|&t| t == lower) +} + + +#[derive(Debug, Deserialize)] +pub struct ColumnDef { + pub name: String, + pub col_type: String, + pub nullable: Option, +} + +#[derive(Debug, Deserialize)] +pub struct CreateTableRequest { + pub name: String, + pub columns: Vec, +} + +#[derive(Debug, Serialize)] +pub struct TableInfo { + pub table_name: String, + pub column_count: i64, +} + +#[derive(Debug, Serialize)] +pub struct ColumnInfo { + pub column_name: String, + pub data_type: String, + pub is_nullable: String, +} + +#[derive(Debug, Serialize)] +pub struct TablePreview { + pub table_name: String, + pub row_count: i64, + pub columns: Vec, + pub sample_rows: Vec, +} + +pub async fn list_tables( + State(state): State, + Extension(_claims): Extension, +) -> Result>, StatusCode> { + let rows = sqlx::query( + r#" + SELECT t.table_name, + COUNT(c.column_name)::bigint AS column_count + FROM information_schema.tables t + LEFT JOIN information_schema.columns c + ON c.table_schema = t.table_schema AND c.table_name = t.table_name + WHERE t.table_schema = 'public' AND t.table_type = 'BASE TABLE' + GROUP BY t.table_name + ORDER BY t.table_name + "#, + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let tables = rows + .into_iter() + .map(|r| TableInfo { + table_name: r.try_get::("table_name").unwrap_or_default(), + column_count: r.try_get::("column_count").unwrap_or(0), + }) + .collect(); + + Ok(Json(tables)) +} + +pub async fn get_table_preview( + State(state): State, + Extension(_claims): Extension, + Path(name): Path, +) -> Result, StatusCode> { + if !crate::routes::is_valid_identifier(&name) { + return Err(StatusCode::BAD_REQUEST); + } + + let col_rows = sqlx::query( + "SELECT column_name, data_type, is_nullable \ + FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = $1 \ + ORDER BY ordinal_position", + ) + .bind(&name) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + if col_rows.is_empty() { + return Err(StatusCode::NOT_FOUND); + } + + let columns: Vec = col_rows + .into_iter() + .map(|r| ColumnInfo { + column_name: r.try_get::("column_name").unwrap_or_default(), + data_type: r.try_get::("data_type").unwrap_or_default(), + is_nullable: r.try_get::("is_nullable").unwrap_or_default(), + }) + .collect(); + + let count_sql = format!("SELECT COUNT(*)::bigint FROM {}", name); + let row_count: i64 = sqlx::query(&count_sql) + .fetch_one(&state.pool) + .await + .map(|r| r.try_get::(0).unwrap_or(0)) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let sample_sql = format!("SELECT * FROM {} LIMIT 10", name); + let sample_rows: Vec = sqlx::query(&sample_sql) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .into_iter() + .map(pg_row_to_json) + .collect(); + + Ok(Json(TablePreview { + table_name: name, + row_count, + columns, + sample_rows, + })) +} + +pub async fn create_table( + State(state): State, + Extension(_claims): Extension, + Json(body): Json, +) -> Result, StatusCode> { + if !crate::routes::is_valid_identifier(&body.name) { + return Err(StatusCode::BAD_REQUEST); + } + if is_protected(&body.name) { + return Err(StatusCode::FORBIDDEN); + } + + if body.columns.is_empty() { + return Err(StatusCode::BAD_REQUEST); + } + + let mut col_defs = vec!["id SERIAL PRIMARY KEY".to_string()]; + + for col in &body.columns { + if !crate::routes::is_valid_identifier(&col.name) { + return Err(StatusCode::BAD_REQUEST); + } + + let upper_type = col.col_type.to_uppercase(); + if !ALLOWED_TYPES.contains(&upper_type.as_str()) { + return Err(StatusCode::UNPROCESSABLE_ENTITY); + } + + let nullable = col.nullable.unwrap_or(true); + let null_clause = if nullable { "" } else { " NOT NULL" }; + col_defs.push(format!("{} {}{}", col.name, upper_type, null_clause)); + } + + let sql = format!("CREATE TABLE {} ({})", body.name, col_defs.join(", ")); + + sqlx::query(&sql) + .execute(&state.pool) + .await + .map_err(|e| { + tracing::error!("create table error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + Ok(Json(TableInfo { + table_name: body.name, + column_count: body.columns.len() as i64 + 1, + })) +} + +pub async fn drop_table( + State(state): State, + Extension(_claims): Extension, + Path(name): Path, +) -> Result, StatusCode> { + if !crate::routes::is_valid_identifier(&name) { + return Err(StatusCode::BAD_REQUEST); + } + if is_protected(&name) { + return Err(StatusCode::FORBIDDEN); + } + + let sql = format!("DROP TABLE IF EXISTS {}", name); + sqlx::query(&sql) + .execute(&state.pool) + .await + .map_err(|e| { + tracing::error!("drop table error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + Ok(Json(serde_json::json!({ "dropped": true }))) +} + +#[cfg(test)] +mod tests { + use super::{is_protected, PROTECTED_TABLES}; + + #[test] + fn test_protected_tables_list() { + assert!(PROTECTED_TABLES.contains(&"users")); + assert!(PROTECTED_TABLES.contains(&"blacklist")); + assert!(PROTECTED_TABLES.contains(&"api_keys")); + assert!(PROTECTED_TABLES.contains(&"queries")); + assert!(PROTECTED_TABLES.contains(&"permissions")); + } + + #[test] + fn test_is_protected() { + assert!(is_protected("users")); + assert!(is_protected("USERS")); + assert!(!is_protected("orders")); + } +} diff --git a/src/routes/auth.rs b/src/routes/auth.rs new file mode 100644 index 0000000..29d2986 --- /dev/null +++ b/src/routes/auth.rs @@ -0,0 +1,35 @@ +use axum::{extract::State, http::StatusCode, Json}; +use serde_json::{json, Value}; + +use crate::{ + auth::encode_jwt, + models::user::LoginRequest, + state::AppState, +}; + +pub async fn login( + State(state): State, + Json(body): Json, +) -> Result, StatusCode> { + let user = sqlx::query_as::<_, crate::models::user::User>( + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE username = $1", + ) + .bind(&body.username) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::UNAUTHORIZED)?; + + let valid = bcrypt::verify(&body.password, &user.password_hash) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + if !valid { + return Err(StatusCode::UNAUTHORIZED); + } + + let mask: u128 = user.permissions_mask.parse().unwrap_or(0); + let token = encode_jwt(&user.username, mask, &state.config.jwt_secret, state.config.jwt_expiry_secs) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + Ok(Json(json!({ "token": token }))) +} diff --git a/src/routes/crud.rs b/src/routes/crud.rs new file mode 100644 index 0000000..46db470 --- /dev/null +++ b/src/routes/crud.rs @@ -0,0 +1,389 @@ +use anyhow::{anyhow, Result}; +use axum::{ + extract::{Extension, Path, Query, State}, + http::{Method, StatusCode}, + Json, +}; +use serde_json::Value; +use sqlx::postgres::PgRow; +use sqlx::Column; +use sqlx::Row; +use sqlx::TypeInfo; +use std::collections::HashMap; + +use crate::{auth::Claims, models::blacklist::BlacklistEntry, state::{AppState, CacheEntry}}; + +/// Returns (sql, ordered_param_values, cache_key). +/// body_cols: (col_name, typed_value) pairs from request body. +/// filter_cols: (col_name, string_value) pairs from query params. +pub fn build_query( + method: &str, + table: &str, + id: Option<&str>, + body_cols: &[(String, Value)], + filter_cols: &[(String, String)], +) -> Result<(String, Vec, String)> { + if !crate::routes::is_valid_identifier(table) { + return Err(anyhow!("invalid identifier: {}", table)); + } + for (col, _) in body_cols.iter() { + if !crate::routes::is_valid_identifier(col) { + return Err(anyhow!("invalid identifier: {}", col)); + } + } + for (col, _) in filter_cols.iter() { + if !crate::routes::is_valid_identifier(col) { + return Err(anyhow!("invalid identifier: {}", col)); + } + } + + let mut sorted_body = body_cols.to_vec(); + sorted_body.sort_by(|a, b| a.0.cmp(&b.0)); + let mut sorted_filters = filter_cols.to_vec(); + sorted_filters.sort_by(|a, b| a.0.cmp(&b.0)); + + match method.to_uppercase().as_str() { + "GET" => { + if let Some(id_val) = id { + let sql = format!("SELECT * FROM {} WHERE id = $1", table); + let key = format!("GET:{}:~id", table); + Ok((sql, vec![Value::String(id_val.to_string())], key)) + } else if sorted_filters.is_empty() { + let sql = format!("SELECT * FROM {}", table); + let key = format!("GET:{}:", table); + Ok((sql, vec![], key)) + } else { + let col_names: Vec = sorted_filters.iter().map(|(c, _)| c.clone()).collect(); + let where_clause: Vec = col_names + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let sql = format!("SELECT * FROM {} WHERE {}", table, where_clause.join(" AND ")); + let params: Vec = sorted_filters.iter().map(|(_, v)| Value::String(v.clone())).collect(); + let key = format!("GET:{}:{}", table, col_names.join(",")); + Ok((sql, params, key)) + } + } + "POST" => { + if sorted_body.is_empty() { + return Err(anyhow!("POST requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let placeholders: Vec = (1..=cols.len()).map(|i| format!("${}", i)).collect(); + let sql = format!( + "INSERT INTO {} ({}) VALUES ({}) RETURNING *", + table, + cols.join(", "), + placeholders.join(", ") + ); + let params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + let key = format!("POST:{}:{}", table, cols.join(",")); + Ok((sql, params, key)) + } + "PUT" => { + let id_val = id.ok_or_else(|| anyhow!("PUT requires an id"))?; + if sorted_body.is_empty() { + return Err(anyhow!("PUT requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let set_clause: Vec = cols + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let id_placeholder = cols.len() + 1; + let sql = format!( + "UPDATE {} SET {} WHERE id = ${} RETURNING *", + table, + set_clause.join(", "), + id_placeholder + ); + let mut params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + params.push(Value::String(id_val.to_string())); + let key = format!("PUT:{}:{}:by_id", table, cols.join(",")); + Ok((sql, params, key)) + } + "DELETE" => { + let id_val = id.ok_or_else(|| anyhow!("DELETE requires an id"))?; + let sql = format!("DELETE FROM {} WHERE id = $1", table); + let key = format!("DELETE:{}:by_id", table); + Ok((sql, vec![Value::String(id_val.to_string())], key)) + } + m => Err(anyhow!("unsupported method: {}", m)), + } +} + +pub fn pg_row_to_json(row: PgRow) -> Value { + let columns = row.columns(); + let mut map = serde_json::Map::new(); + for col in columns { + let name = col.name().to_string(); + let type_name = col.type_info().name(); + let val = match type_name { + "INT2" => row + .try_get::(col.ordinal()) + .map(|v| Value::Number(i64::from(v).into())) + .unwrap_or(Value::Null), + "INT4" | "SERIAL" => row + .try_get::(col.ordinal()) + .map(|v| Value::Number(i64::from(v).into())) + .unwrap_or(Value::Null), + "INT8" => row + .try_get::(col.ordinal()) + .map(|v| Value::Number(v.into())) + .unwrap_or(Value::Null), + "FLOAT4" | "FLOAT8" => row + .try_get::(col.ordinal()) + .ok() + .and_then(|v| serde_json::Number::from_f64(v)) + .map(Value::Number) + .unwrap_or(Value::Null), + "BOOL" => row + .try_get::(col.ordinal()) + .map(Value::Bool) + .unwrap_or(Value::Null), + "UUID" => row + .try_get::(col.ordinal()) + .map(|v| Value::String(v.to_string())) + .unwrap_or(Value::Null), + "TIMESTAMPTZ" | "TIMESTAMP" => row + .try_get::, _>(col.ordinal()) + .map(|v| Value::String(v.to_rfc3339())) + .unwrap_or(Value::Null), + _ => row + .try_get::(col.ordinal()) + .map(Value::String) + .unwrap_or(Value::Null), + }; + map.insert(name, val); + } + Value::Object(map) +} + +async fn reload_blacklist(state: &AppState) -> Result<(), StatusCode> { + let entries = sqlx::query_as::<_, BlacklistEntry>( + "SELECT id, pattern, method, reason, active, bypass_mask, created_at FROM blacklist ORDER BY id", + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state.blacklist_cache.load(entries).await; + Ok(()) +} + +fn strip_password_hash(v: Value) -> Value { + match v { + Value::Object(mut m) => { + m.remove("password_hash"); + Value::Object(m) + } + Value::Array(arr) => Value::Array( + arr.into_iter() + .map(|item| match item { + Value::Object(mut m) => { + m.remove("password_hash"); + Value::Object(m) + } + other => other, + }) + .collect(), + ), + other => other, + } +} + +pub async fn handle_crud( + State(state): State, + method: Method, + Extension(claims): Extension, + Path(params): Path>, + Query(query_params): Query>, + body: Option>>, +) -> Result, StatusCode> { + let table = params.get("table").ok_or(StatusCode::BAD_REQUEST)?.clone(); + let id = params.get("id").map(|s| s.as_str()); + let method_str = method.as_str(); + + // Enforce permission bits before doing any work. + let required_bit = match method_str.to_uppercase().as_str() { + "GET" => crate::auth::permissions::READ, + "POST" | "PUT" => crate::auth::permissions::WRITE, + "DELETE" => crate::auth::permissions::DELETE, + _ => return Err(StatusCode::METHOD_NOT_ALLOWED), + }; + if !claims.has_permission(required_bit) { + return Err(StatusCode::FORBIDDEN); + } + + // Collect body as typed Values directly — no sentinel needed. + let mut body_cols: Vec<(String, Value)> = body + .map(|Json(b)| b.into_iter().collect()) + .unwrap_or_default(); + + // Hash the password field for the users table before building the query. + if table == "users" && matches!(method_str.to_uppercase().as_str(), "POST" | "PUT") { + if let Some(pos) = body_cols.iter().position(|(k, _)| k == "password") { + let (_, val) = body_cols.remove(pos); + if let Value::String(plaintext) = val { + let hash = bcrypt::hash(&plaintext, bcrypt::DEFAULT_COST) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + body_cols.push(("password_hash".to_string(), Value::String(hash))); + } + } + } + + let filter_cols: Vec<(String, String)> = query_params.into_iter().collect(); + + let (sql, params_vals, cache_key) = + build_query(method_str, &table, id, &body_cols, &filter_cols) + .map_err(|_| StatusCode::BAD_REQUEST)?; + + let sql = if let Some(entry) = state.query_cache.get(&cache_key) { + entry.sql.clone() + } else { + let entry = CacheEntry::new(sql.clone()); + state + .query_cache + .insert(cache_key, entry.clone(), state.config.cache_max_capacity); + entry.sql + }; + + let mut q = sqlx::query(&sql); + for val in ¶ms_vals { + match val { + Value::Null => q = q.bind(Option::::None), + Value::Bool(b) => q = q.bind(*b), + Value::Number(n) => { + if let Some(i) = n.as_i64() { + q = q.bind(i); + } else if let Some(f) = n.as_f64() { + q = q.bind(f); + } else { + q = q.bind(n.to_string()); + } + } + Value::String(s) => q = q.bind(s.as_str()), + other => q = q.bind(other.to_string()), + } + } + + let response = match method_str.to_uppercase().as_str() { + "GET" => { + let rows = q + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let mut v = Value::Array(rows.into_iter().map(pg_row_to_json).collect()); + if table == "users" { + v = strip_password_hash(v); + } + v + } + "POST" | "PUT" => { + let row = q + .fetch_one(&state.pool) + .await + .map_err(|e| { + if e.to_string().contains("no rows") { + StatusCode::NOT_FOUND + } else { + StatusCode::INTERNAL_SERVER_ERROR + } + })?; + let mut v = pg_row_to_json(row); + if table == "users" { + v = strip_password_hash(v); + } + v + } + "DELETE" => { + q.execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + serde_json::json!({ "deleted": true }) + } + _ => return Err(StatusCode::METHOD_NOT_ALLOWED), + }; + + // Reload the in-memory blacklist cache after any mutation to the blacklist table. + if table == "blacklist" && method_str != "GET" { + reload_blacklist(&state).await?; + } + + Ok(Json(response)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_build_select_all() { + let (sql, params, key) = build_query("GET", "orders", None, &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders"); + assert!(params.is_empty()); + assert_eq!(key, "GET:orders:"); + } + + #[test] + fn test_build_select_by_id() { + let (sql, params, key) = build_query("GET", "orders", Some("42"), &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders WHERE id = $1"); + assert_eq!(params, vec![Value::String("42".into())]); + assert_eq!(key, "GET:orders:~id"); + } + + #[test] + fn test_build_insert() { + let cols = vec![ + ("email".into(), Value::String("a@b.com".into())), + ("name".into(), Value::String("Alice".into())), + ]; + let (sql, params, key) = build_query("POST", "users", None, &cols, &[]).unwrap(); + assert_eq!(sql, "INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *"); + assert_eq!(params, vec![Value::String("a@b.com".into()), Value::String("Alice".into())]); + assert_eq!(key, "POST:users:email,name"); + } + + #[test] + fn test_build_update() { + let cols = vec![("name".into(), Value::String("Bob".into()))]; + let (sql, params, key) = build_query("PUT", "users", Some("7"), &cols, &[]).unwrap(); + assert_eq!(sql, "UPDATE users SET name = $1 WHERE id = $2 RETURNING *"); + assert_eq!(params, vec![Value::String("Bob".into()), Value::String("7".into())]); + assert_eq!(key, "PUT:users:name:by_id"); + } + + #[test] + fn test_build_delete() { + let (sql, params, key) = build_query("DELETE", "users", Some("3"), &[], &[]).unwrap(); + assert_eq!(sql, "DELETE FROM users WHERE id = $1"); + assert_eq!(params, vec![Value::String("3".into())]); + assert_eq!(key, "DELETE:users:by_id"); + } + + #[test] + fn test_build_select_with_filters() { + let filters = vec![("status".into(), "active".into()), ("role".into(), "admin".into())]; + let (sql, params, key) = build_query("GET", "users", None, &[], &filters).unwrap(); + assert_eq!(sql, "SELECT * FROM users WHERE role = $1 AND status = $2"); + assert_eq!(params, vec![Value::String("admin".into()), Value::String("active".into())]); + assert_eq!(key, "GET:users:role,status"); + } + + #[test] + fn test_build_null_body_value() { + let cols = vec![("note".into(), Value::Null)]; + let (sql, params, key) = build_query("POST", "items", None, &cols, &[]).unwrap(); + assert_eq!(sql, "INSERT INTO items (note) VALUES ($1) RETURNING *"); + assert_eq!(params, vec![Value::Null]); + assert_eq!(key, "POST:items:note"); + } + + #[test] + fn test_rejects_invalid_table_name() { + let result = build_query("GET", "users; DROP TABLE users--", None, &[], &[]); + assert!(result.is_err()); + } +} diff --git a/src/routes/mod.rs b/src/routes/mod.rs new file mode 100644 index 0000000..72d18ab --- /dev/null +++ b/src/routes/mod.rs @@ -0,0 +1,7 @@ +pub mod admin; +pub mod auth; +pub mod crud; + +pub fn is_valid_identifier(name: &str) -> bool { + !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') +} diff --git a/src/state.rs b/src/state.rs new file mode 100644 index 0000000..aaaedb1 --- /dev/null +++ b/src/state.rs @@ -0,0 +1,252 @@ +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, +}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use dashmap::DashMap; +use glob::Pattern; +use sqlx::PgPool; +use tokio::sync::RwLock; + +use crate::config::Config; +use crate::models::blacklist::BlacklistEntry; + +pub fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} + +#[derive(Clone)] +pub struct AppState { + pub pool: PgPool, + pub query_cache: QueryCache, + pub blacklist_cache: BlacklistCache, + pub config: Arc, +} + +#[derive(Clone)] +pub struct QueryCache { + pub map: Arc>, + pub hits: Arc, + pub misses: Arc, +} + +#[derive(Clone, Debug)] +pub struct CacheEntry { + pub sql: String, + pub last_accessed_secs: Arc, +} + +impl CacheEntry { + pub fn new(sql: String) -> Self { + Self { + sql, + last_accessed_secs: Arc::new(AtomicU64::new(unix_now())), + } + } + + pub fn touch(&self) { + self.last_accessed_secs.store(unix_now(), Ordering::Relaxed); + } + + pub fn last_accessed(&self) -> u64 { + self.last_accessed_secs.load(Ordering::Relaxed) + } +} + +impl QueryCache { + pub fn new() -> Self { + Self { + map: Arc::new(DashMap::new()), + hits: Arc::new(AtomicU64::new(0)), + misses: Arc::new(AtomicU64::new(0)), + } + } + + pub fn get(&self, key: &str) -> Option { + if let Some(entry) = self.map.get(key) { + entry.touch(); + self.hits.fetch_add(1, Ordering::Relaxed); + Some(entry.clone()) + } else { + self.misses.fetch_add(1, Ordering::Relaxed); + None + } + } + + pub fn insert(&self, key: String, entry: CacheEntry, max_capacity: usize) { + if self.map.len() >= max_capacity { + let oldest_key = self + .map + .iter() + .min_by_key(|e| e.last_accessed()) + .map(|e| e.key().clone()); + if let Some(k) = oldest_key { + self.map.remove(&k); + } + } + self.map.insert(key, entry); + } + + pub fn remove(&self, key: &str) { + self.map.remove(key); + } + + pub fn hits(&self) -> u64 { + self.hits.load(Ordering::Relaxed) + } + + pub fn misses(&self) -> u64 { + self.misses.load(Ordering::Relaxed) + } + + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn flush(&self) { + self.map.clear(); + } +} + +#[derive(Clone)] +pub struct BlacklistCache { + pub inner: Arc>>, +} + +#[derive(Clone)] +pub struct CompiledEntry { + pub entry: BlacklistEntry, + pub pattern: Pattern, + pub bypass_mask: Option, +} + +impl BlacklistCache { + pub fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(Vec::new())), + } + } + + pub async fn load(&self, entries: Vec) { + let compiled: Vec = entries + .into_iter() + .filter_map(|e| { + let bypass_mask = e + .bypass_mask + .as_deref() + .and_then(|s| s.parse::().ok()); + Pattern::new(&e.pattern) + .ok() + .map(|pattern| CompiledEntry { entry: e, pattern, bypass_mask }) + }) + .collect(); + let mut guard = self.inner.write().await; + *guard = compiled; + } + + /// Returns true if the request should be blocked. + /// `caller_mask` is 0 for unauthenticated requests; bypass only applies + /// when the caller holds the permission bit stored in bypass_mask. + pub async fn is_blocked(&self, method: &str, path: &str, caller_mask: u128) -> bool { + let path = path.trim_end_matches('/'); + let path = if path.is_empty() { "/" } else { path }; + let guard = self.inner.read().await; + guard.iter().any(|compiled| { + if !compiled.entry.active { + return false; + } + let method_matches = compiled + .entry + .method + .as_deref() + .map(|m| m.split(',').any(|part| part.trim().eq_ignore_ascii_case(method))) + .unwrap_or(true); + if !method_matches || !compiled.pattern.matches(path) { + return false; + } + // If caller holds the bypass permission, they are not blocked. + match compiled.bypass_mask { + Some(mask) if caller_mask & mask != 0 => false, + _ => true, + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_cache_insert_and_get() { + let cache = QueryCache::new(); + let entry = CacheEntry::new("SELECT 1".into()); + cache.insert("key1".into(), entry, 100); + let got = cache.get("key1"); + assert!(got.is_some()); + assert_eq!(got.unwrap().sql, "SELECT 1"); + assert_eq!(cache.hits(), 1); + assert_eq!(cache.misses(), 0); + } + + #[test] + fn test_cache_miss() { + let cache = QueryCache::new(); + let got = cache.get("missing"); + assert!(got.is_none()); + assert_eq!(cache.misses(), 1); + } + + #[test] + fn test_cache_capacity_evicts_oldest() { + let cache = QueryCache::new(); + let e1 = CacheEntry::new("SELECT 1".into()); + // force e1 to be older + e1.last_accessed_secs.store(1, Ordering::Relaxed); + cache.map.insert("old".into(), e1); + let e2 = CacheEntry::new("SELECT 2".into()); + cache.insert("new".into(), e2, 1); // capacity=1, should evict "old" + assert!(cache.map.get("old").is_none()); + assert!(cache.map.get("new").is_some()); + } + + #[tokio::test] + async fn test_blacklist_blocks_pattern() { + use chrono::Utc; + let cache = BlacklistCache::new(); + let entry = BlacklistEntry { + id: 1, + pattern: "/api/users/**".into(), + method: None, + reason: None, + active: true, + bypass_mask: None, + created_at: Utc::now(), + }; + cache.load(vec![entry]).await; + assert!(cache.is_blocked("GET", "/api/users/42", 0).await); + assert!(!cache.is_blocked("GET", "/api/orders/1", 0).await); + } + + #[tokio::test] + async fn test_blacklist_method_specific() { + use chrono::Utc; + let cache = BlacklistCache::new(); + let entry = BlacklistEntry { + id: 2, + pattern: "/api/secrets".into(), + method: Some("GET".into()), + reason: None, + active: true, + bypass_mask: None, + created_at: Utc::now(), + }; + cache.load(vec![entry]).await; + assert!(cache.is_blocked("GET", "/api/secrets", 0).await); + assert!(!cache.is_blocked("POST", "/api/secrets", 0).await); + } +} diff --git a/ui/.gitignore b/ui/.gitignore new file mode 100644 index 0000000..edf52b5 --- /dev/null +++ b/ui/.gitignore @@ -0,0 +1,10 @@ +node_modules/ +dist/ + +# vue-tsc emit artifacts (should never appear in src/ — noEmit is set) +src/**/*.vue.js +src/**/*.vue.js.map +src/**/*.vue.d.ts +src/**/*.vue.d.ts.map +src/**/*.ts.js +src/**/*.ts.js.map diff --git a/ui/bun.lock b/ui/bun.lock new file mode 100644 index 0000000..caff4cc --- /dev/null +++ b/ui/bun.lock @@ -0,0 +1,230 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "mercury-ui", + "dependencies": { + "@nychthemeron/library": "latest", + "pinia": "^2.1.0", + "vue": "^3.4.0", + "vue-router": "^4.3.0", + }, + "devDependencies": { + "@vitejs/plugin-vue": "^5.0.0", + "typescript": "^5.3.0", + "vite": "^5.0.0", + "vue-tsc": "^2.0.0", + }, + }, + }, + "packages": { + "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], + + "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], + + "@babel/parser": ["@babel/parser@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="], + + "@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], + + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.21.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="], + + "@esbuild/android-arm": ["@esbuild/android-arm@0.21.5", "", { "os": "android", "cpu": "arm" }, "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg=="], + + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.21.5", "", { "os": "android", "cpu": "arm64" }, "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A=="], + + "@esbuild/android-x64": ["@esbuild/android-x64@0.21.5", "", { "os": "android", "cpu": "x64" }, "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA=="], + + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.21.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ=="], + + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.21.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw=="], + + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.21.5", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g=="], + + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.21.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ=="], + + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.21.5", "", { "os": "linux", "cpu": "arm" }, "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA=="], + + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.21.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q=="], + + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.21.5", "", { "os": "linux", "cpu": "ia32" }, "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg=="], + + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg=="], + + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg=="], + + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.21.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w=="], + + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA=="], + + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.21.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A=="], + + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.21.5", "", { "os": "linux", "cpu": "x64" }, "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ=="], + + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.21.5", "", { "os": "none", "cpu": "x64" }, "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg=="], + + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.21.5", "", { "os": "openbsd", "cpu": "x64" }, "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow=="], + + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.21.5", "", { "os": "sunos", "cpu": "x64" }, "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg=="], + + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.21.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A=="], + + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.21.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA=="], + + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.21.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], + + "@nychthemeron/library": ["@nychthemeron/library@0.0.1", "https://git.mcpeakdev.com/api/packages/McPeakDev/npm/%40nychthemeron%2Flibrary/-/0.0.1/library-0.0.1.tgz", { "peerDependencies": { "primevue": "^4.5.0", "vue": "^3.5.0" } }, "sha512-84pcTnF8Ead8D7TSLhKTS8ACpaOCTS0mylzkWqgGrNs4fnrH9tEJg874nFHegiFy5P1fuKCk4B7Yt/Pjc4NK/Q=="], + + "@primeuix/styled": ["@primeuix/styled@0.7.4", "", { "dependencies": { "@primeuix/utils": "^0.6.1" } }, "sha512-QSO/NpOQg8e9BONWRBx9y8VGMCMYz0J/uKfNJEya/RGEu7ARx0oYW0ugI1N3/KB1AAvyGxzKBzGImbwg0KUiOQ=="], + + "@primeuix/styles": ["@primeuix/styles@2.0.3", "", { "dependencies": { "@primeuix/styled": "^0.7.4" } }, "sha512-2ykAB6BaHzR/6TwF8ShpJTsZrid6cVIEBVlookSdvOdmlWuevGu5vWOScgIwqWwlZcvkFYAGR/SUV3OHCTBMdw=="], + + "@primeuix/utils": ["@primeuix/utils@0.6.4", "", {}, "sha512-pZ5f+vj7wSzRhC7KoEQRU5fvYAe+RP9+m39CTscZ3UywCD1Y2o6Fe1rRgklMPSkzUcty2jzkA0zMYkiJBD1hgg=="], + + "@primevue/core": ["@primevue/core@4.5.5", "", { "dependencies": { "@primeuix/styled": "^0.7.4", "@primeuix/utils": "^0.6.2" }, "peerDependencies": { "vue": "^3.5.0" } }, "sha512-JpkXhq1ddc70JdsC3CC4dM+UbeeWuCW/8DpS9dNBfrOk824TLSlRlMEGFyVKqRMn5WPQvYLiy3xXfLQeNdSqhQ=="], + + "@primevue/icons": ["@primevue/icons@4.5.5", "", { "dependencies": { "@primeuix/utils": "^0.6.2", "@primevue/core": "4.5.5" } }, "sha512-eteOhTdAOXEYE9qW1AOrBBgDxQ2szHJxSkEK1XVdV2TKxGM5FQf03Ovms0VDyZTc16XBIgvwYjXJQS0BPbhPaA=="], + + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.62.0", "", { "os": "android", "cpu": "arm" }, "sha512-IPIQ55ythEHkfEd9jMEi32OQ7SxURsGA43JI22lj01OLZNt2NUbJX8YUHxkVWyQ6daHPNn0truF5nSj3DQp6YQ=="], + + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.62.0", "", { "os": "android", "cpu": "arm64" }, "sha512-M6s9cr10MibETyo8JsOkq+Lo1+lU6hcvb1MApnUql5qte/5hMEgzlN8/ReIKNfRV8rrqX50W1BX9zoUhC192RA=="], + + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.62.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BqCoMoIbn0keKys+dEAdBa70EtOwV1bEsQCUgU9FdiZmmMge/Zk7LlkYGqbrdHR+Frnt0E1FOanly+rlwvvQzw=="], + + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.62.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-SIMzST3VFNXDAbeIWDWiFCNM5qncUBDWaEV7NfE7oZbDt2mgfW4MvbKdbYiGOLoM32gbTv608UMd0XktEYSD7w=="], + + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.62.0", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-ezjfSQMP7ArdUsbBwbQIfwAlhE84I2iVnzQNCFSveqV42q+BmKlzVpf7mxv5EchLcoWU4y6/heFzVg1F+hodUQ=="], + + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.62.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-9+qTWGW9AZRhnUgwtTwzNwcPlL87ngkeN0LA+q1bADvmY9aNvWaF2TFW8BZgnQPYxpDI7+rMVLivcd4V737TAQ=="], + + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.62.0", "", { "os": "linux", "cpu": "arm" }, "sha512-T1dMEQhXA/jkJ/jyMIw9IovK8bSUq7A8kLIlvZTb/6YIVsp2zLavr4F3oyllHWo7eIVJRyE5n3tUjQJEbE1IuQ=="], + + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.62.0", "", { "os": "linux", "cpu": "arm" }, "sha512-2as0LgT7qQpyceQq6VUJYnumUMUrgGQCWIiDIN9DE0/tglsk6o66uCB4f3djRawAltvfCNLyZZrsqbPA6inCsA=="], + + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.62.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-bVURMg+6eNN9C/yc0aVjooZcwTTtYF4YW3xta5pP0//r3o1V8gXEHXWCndj47w/HhwsFroZrFhR+6uQP5T0n0g=="], + + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.62.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-Ful8pM/2yYI83PViWdFdpZhdI8HJ5qsXANe5atypbHDf+KIBBDsZsbyy8hbXnULVvW9NsTh5DHwbcBftyLTfiw=="], + + "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.62.0", "", { "os": "linux", "cpu": "none" }, "sha512-9Gp/DgrkzfUBmNPVTyPTvay+4xEP7M/clXpj3efXBcm6uTIVIgDg4rqUpqKXvLEuFRVuEpSAOkhgNeecvaZ4Cg=="], + + "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.62.0", "", { "os": "linux", "cpu": "none" }, "sha512-m9tsJz54LUXkSYM8+8PG81B9IKK5r+2T0clMq4QrS16xFosufU7firBDAZEsDheDs7wTlP7h3++S7lMsU955HA=="], + + "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.62.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-3UvJ5PNVU16aJf6M3tFI24pWzAl2/ynfbyRN3ICyQajK1lSkrnVYNnLz3v04J32qKa0FczJc22zeToc0lr2A3w=="], + + "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.62.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-vRWUAbYLGHBZS6Q8Msb2sfnf1fvJf+47t8l/TwOerM2qArzy+IeNMTHrYLHXh95h8MoatPHI5hhSZNs+mGXKPg=="], + + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.62.0", "", { "os": "linux", "cpu": "none" }, "sha512-c00T5SYENHAt86cfW47URaP3Us5vLC/4QO7GYud1G5VNRffCwwCuBspwqYrriuJB+5m0WFzClCn9wed0FBjKvg=="], + + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.62.0", "", { "os": "linux", "cpu": "none" }, "sha512-krrCDilhXOwFkSkO3Wm9I/f9H0L92XHHwy2fwxjukxIbh0dem8gZqOW5Y8BsHrpJv5qwlRBV+Wl4ZFyRWhUpwg=="], + + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.62.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-7pfYFSTc4/rUC/FtAI0Qp6QthDBCIi6/AuP1xYqFk5vanI6KnL5dWKP60OM/05LOsbwTmIcvr6eXC4CJuJ75IA=="], + + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.62.0", "", { "os": "linux", "cpu": "x64" }, "sha512-7SDIalKeIpG0Ifogbbdn58HmSotYMlf23K3dCJEmiVd9Fg36Vmni82iPQec27N3wY4Bvbxftkxz6vSx9OcouTg=="], + + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.62.0", "", { "os": "linux", "cpu": "x64" }, "sha512-eRZevouTH2i1HeAVLqJuLnt256krQkGY0TN6WsTmsIhuzbh457HuWDMakKwmi0Cjadux983CoSr8Lim2QhUIFw=="], + + "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.62.0", "", { "os": "openbsd", "cpu": "x64" }, "sha512-3oVS7FLGa4U1qcvao9ylGxrjXZyUQqR8UwxEcnUEyPX53O/C/mKDZegNXTdHCP+h3e6ta/f1EN38Yif1mmZHYg=="], + + "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.62.0", "", { "os": "none", "cpu": "arm64" }, "sha512-yTB9TgfWj5wHe5QgktAgXTLLot1gvEjl1NiPPAUiCs4oPrIWFl5V4nC3GrkNdj9LaAU4s94nVrGbGOCqUpyWsg=="], + + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.62.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-5LOhoaesY3doG1c+ac/2JtgREpKoJr5bUHH8tKY0V8di7+uSV6BwLs2PlR0/yzefGOkR+wE7ZolZphHCsyG5Rw=="], + + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.62.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-yYkWHhmbhRTWTnWos5HC4GcPQfjlzzCNbM9e/+GXrLuaBXYA3qSDR9f0Vgufd5S8yX81U8jPKp7ZnAjZFMtRnw=="], + + "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.62.0", "", { "os": "win32", "cpu": "x64" }, "sha512-SoTb6lPg25xZlA2ibwQ++ahCCnH+FP0qmEuafMJ4gznZKOlXioKEAeJLgCrqjM98ACziXM9V1amFjICVL4IFoA=="], + + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.62.0", "", { "os": "win32", "cpu": "x64" }, "sha512-5L+T1fMX4RIEBoZzT0+sQ0PhTS36NULFmMXtl1TZo44TMAROIMHbZufSOjVWt/Y622BtxgxtaNOokbTDvfsrZA=="], + + "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "@vitejs/plugin-vue": ["@vitejs/plugin-vue@5.2.4", "", { "peerDependencies": { "vite": "^5.0.0 || ^6.0.0", "vue": "^3.2.25" } }, "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA=="], + + "@volar/language-core": ["@volar/language-core@2.4.15", "", { "dependencies": { "@volar/source-map": "2.4.15" } }, "sha512-3VHw+QZU0ZG9IuQmzT68IyN4hZNd9GchGPhbD9+pa8CVv7rnoOZwo7T8weIbrRmihqy3ATpdfXFnqRrfPVK6CA=="], + + "@volar/source-map": ["@volar/source-map@2.4.15", "", {}, "sha512-CPbMWlUN6hVZJYGcU/GSoHu4EnCHiLaXI9n8c9la6RaI9W5JHX+NqG+GSQcB0JdC2FIBLdZJwGsfKyBB71VlTg=="], + + "@volar/typescript": ["@volar/typescript@2.4.15", "", { "dependencies": { "@volar/language-core": "2.4.15", "path-browserify": "^1.0.1", "vscode-uri": "^3.0.8" } }, "sha512-2aZ8i0cqPGjXb4BhkMsPYDkkuc2ZQ6yOpqwAuNwUoncELqoy5fRgOQtLR9gB0g902iS0NAkvpIzs27geVyVdPg=="], + + "@vue/compiler-core": ["@vue/compiler-core@3.5.38", "", { "dependencies": { "@babel/parser": "^7.29.7", "@vue/shared": "3.5.38", "entities": "^7.0.1", "estree-walker": "^2.0.2", "source-map-js": "^1.2.1" } }, "sha512-s99aGxWYig9ErHbct27KXEGhrBYlRI6c4MwAgXErOAbX9xiW37/uMa+XUDO69zLz83dng8UUZ70CTOJrLrYrEQ=="], + + "@vue/compiler-dom": ["@vue/compiler-dom@3.5.38", "", { "dependencies": { "@vue/compiler-core": "3.5.38", "@vue/shared": "3.5.38" } }, "sha512-JTqp25l8aFfJYF7/KmsXZjAxJz7T+SjmTJLoXVjHtc2BrSgSiW2n9Aem/cWq1OPe68A8JL06B3eVdhlP0H4TVw=="], + + "@vue/compiler-sfc": ["@vue/compiler-sfc@3.5.38", "", { "dependencies": { "@babel/parser": "^7.29.7", "@vue/compiler-core": "3.5.38", "@vue/compiler-dom": "3.5.38", "@vue/compiler-ssr": "3.5.38", "@vue/shared": "3.5.38", "estree-walker": "^2.0.2", "magic-string": "^0.30.21", "postcss": "^8.5.15", "source-map-js": "^1.2.1" } }, "sha512-DuA2GiZawSEW442iw/9+Fkol8hTgb4Ke5KkhmSry65QA7YuyMbIdy8p0XZRMvNwJdgRz307W8g1CSzdvS4nuNg=="], + + "@vue/compiler-ssr": ["@vue/compiler-ssr@3.5.38", "", { "dependencies": { "@vue/compiler-dom": "3.5.38", "@vue/shared": "3.5.38" } }, "sha512-7s+W5Gc42FGxZMcuwl8H5B29T8BJPMdBT7KHFE+BbAuZ/iTEdTtv7z2XiMjiaUUw4w3ZcCEdHs36RuYJ2VA7bA=="], + + "@vue/compiler-vue2": ["@vue/compiler-vue2@2.7.16", "", { "dependencies": { "de-indent": "^1.0.2", "he": "^1.2.0" } }, "sha512-qYC3Psj9S/mfu9uVi5WvNZIzq+xnXMhOwbTFKKDD7b1lhpnn71jXSFdTQ+WsIEk0ONCd7VV2IMm7ONl6tbQ86A=="], + + "@vue/devtools-api": ["@vue/devtools-api@6.6.4", "", {}, "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g=="], + + "@vue/language-core": ["@vue/language-core@2.2.12", "", { "dependencies": { "@volar/language-core": "2.4.15", "@vue/compiler-dom": "^3.5.0", "@vue/compiler-vue2": "^2.7.16", "@vue/shared": "^3.5.0", "alien-signals": "^1.0.3", "minimatch": "^9.0.3", "muggle-string": "^0.4.1", "path-browserify": "^1.0.1" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-IsGljWbKGU1MZpBPN+BvPAdr55YPkj2nB/TBNGNC32Vy2qLG25DYu/NBN2vNtZqdRbTRjaoYrahLrToim2NanA=="], + + "@vue/reactivity": ["@vue/reactivity@3.5.38", "", { "dependencies": { "@vue/shared": "3.5.38" } }, "sha512-pG6LV/NDNRbKizcUjFFLAfjaL8mcv4DmR9avNcUw2gDHBzZneuS2TWCmp633ynzxz9YYKNeEPK2I8Wraqy2HUQ=="], + + "@vue/runtime-core": ["@vue/runtime-core@3.5.38", "", { "dependencies": { "@vue/reactivity": "3.5.38", "@vue/shared": "3.5.38" } }, "sha512-iyW8WVfF1CpCXxncZY5Ei6rSd6oZr5DgEom//fUjRBRl56AXPD+s9ATvukRt77ZFTuYlnVA1bxY+dJB94tWVYw=="], + + "@vue/runtime-dom": ["@vue/runtime-dom@3.5.38", "", { "dependencies": { "@vue/reactivity": "3.5.38", "@vue/runtime-core": "3.5.38", "@vue/shared": "3.5.38", "csstype": "^3.2.3" } }, "sha512-apX2wt9sdfDshS+a2xueFZLVpt0GkRJZSoPmrW/SA4yzXTznhfcMVW59gr7h4YQeY0vJhdJkk2rsIDwgfFgC5A=="], + + "@vue/server-renderer": ["@vue/server-renderer@3.5.38", "", { "dependencies": { "@vue/compiler-ssr": "3.5.38", "@vue/shared": "3.5.38" }, "peerDependencies": { "vue": "3.5.38" } }, "sha512-vue8vbf2QlV4quHqzwmJy6dWfmRhP1J8l4wtZg60CL6VoKqcPY2oe7may3+1d9qfpedjK5PRLFqd5k3Isj9mUw=="], + + "@vue/shared": ["@vue/shared@3.5.38", "", {}, "sha512-FTW0AFZNaK5/mOqvGBwVfUlNLU38TiQn4+DQgIFUnrBBJQ1crMJ82yeGQLV5jyKFsO8yRukpbuP7x+nRbH6aug=="], + + "alien-signals": ["alien-signals@1.0.13", "", {}, "sha512-OGj9yyTnJEttvzhTUWuscOvtqxq5vrhF7vL9oS0xJ2mK0ItPYP1/y+vCFebfxoEyAz0++1AIwJ5CMr+Fk3nDmg=="], + + "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], + + "brace-expansion": ["brace-expansion@2.1.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA=="], + + "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + + "de-indent": ["de-indent@1.0.2", "", {}, "sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg=="], + + "entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="], + + "esbuild": ["esbuild@0.21.5", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.21.5", "@esbuild/android-arm": "0.21.5", "@esbuild/android-arm64": "0.21.5", "@esbuild/android-x64": "0.21.5", "@esbuild/darwin-arm64": "0.21.5", "@esbuild/darwin-x64": "0.21.5", "@esbuild/freebsd-arm64": "0.21.5", "@esbuild/freebsd-x64": "0.21.5", "@esbuild/linux-arm": "0.21.5", "@esbuild/linux-arm64": "0.21.5", "@esbuild/linux-ia32": "0.21.5", "@esbuild/linux-loong64": "0.21.5", "@esbuild/linux-mips64el": "0.21.5", "@esbuild/linux-ppc64": "0.21.5", "@esbuild/linux-riscv64": "0.21.5", "@esbuild/linux-s390x": "0.21.5", "@esbuild/linux-x64": "0.21.5", "@esbuild/netbsd-x64": "0.21.5", "@esbuild/openbsd-x64": "0.21.5", "@esbuild/sunos-x64": "0.21.5", "@esbuild/win32-arm64": "0.21.5", "@esbuild/win32-ia32": "0.21.5", "@esbuild/win32-x64": "0.21.5" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw=="], + + "estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "he": ["he@1.2.0", "", { "bin": { "he": "bin/he" } }, "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw=="], + + "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + + "minimatch": ["minimatch@9.0.9", "", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="], + + "muggle-string": ["muggle-string@0.4.1", "", {}, "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ=="], + + "nanoid": ["nanoid@3.3.12", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ=="], + + "path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "pinia": ["pinia@2.3.1", "", { "dependencies": { "@vue/devtools-api": "^6.6.3", "vue-demi": "^0.14.10" }, "peerDependencies": { "typescript": ">=4.4.4", "vue": "^2.7.0 || ^3.5.11" }, "optionalPeers": ["typescript"] }, "sha512-khUlZSwt9xXCaTbbxFYBKDc/bWAGWJjOgvxETwkTN7KRm66EeT1ZdZj6i2ceh9sP2Pzqsbc704r2yngBrxBVug=="], + + "postcss": ["postcss@8.5.15", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A=="], + + "primevue": ["primevue@4.5.5", "", { "dependencies": { "@primeuix/styled": "^0.7.4", "@primeuix/styles": "^2.0.3", "@primeuix/utils": "^0.6.2", "@primevue/core": "4.5.5", "@primevue/icons": "4.5.5" } }, "sha512-Kv5REIewCdP806QaoU+4nBXfmpzOGFKkZ9qH4KsL6MjiAQVc4PUzypt8erl4r3Vzh3nr3aWZIxkxYRRsLGiX2A=="], + + "rollup": ["rollup@4.62.0", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.62.0", "@rollup/rollup-android-arm64": "4.62.0", "@rollup/rollup-darwin-arm64": "4.62.0", "@rollup/rollup-darwin-x64": "4.62.0", "@rollup/rollup-freebsd-arm64": "4.62.0", "@rollup/rollup-freebsd-x64": "4.62.0", "@rollup/rollup-linux-arm-gnueabihf": "4.62.0", "@rollup/rollup-linux-arm-musleabihf": "4.62.0", "@rollup/rollup-linux-arm64-gnu": "4.62.0", "@rollup/rollup-linux-arm64-musl": "4.62.0", "@rollup/rollup-linux-loong64-gnu": "4.62.0", "@rollup/rollup-linux-loong64-musl": "4.62.0", "@rollup/rollup-linux-ppc64-gnu": "4.62.0", "@rollup/rollup-linux-ppc64-musl": "4.62.0", "@rollup/rollup-linux-riscv64-gnu": "4.62.0", "@rollup/rollup-linux-riscv64-musl": "4.62.0", "@rollup/rollup-linux-s390x-gnu": "4.62.0", "@rollup/rollup-linux-x64-gnu": "4.62.0", "@rollup/rollup-linux-x64-musl": "4.62.0", "@rollup/rollup-openbsd-x64": "4.62.0", "@rollup/rollup-openharmony-arm64": "4.62.0", "@rollup/rollup-win32-arm64-msvc": "4.62.0", "@rollup/rollup-win32-ia32-msvc": "4.62.0", "@rollup/rollup-win32-x64-gnu": "4.62.0", "@rollup/rollup-win32-x64-msvc": "4.62.0", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-nc72Wgq62I7rtDV4izT5/aaS0zxy3kttkinf9586ApknY3jZO9NYsmtc24fUckA0X7Q2v+ML4a15pdUlV5V/jA=="], + + "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "vite": ["vite@5.4.21", "", { "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", "rollup": "^4.20.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || >=20.0.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.4.0" }, "optionalPeers": ["@types/node", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser"], "bin": { "vite": "bin/vite.js" } }, "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw=="], + + "vscode-uri": ["vscode-uri@3.1.0", "", {}, "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ=="], + + "vue": ["vue@3.5.38", "", { "dependencies": { "@vue/compiler-dom": "3.5.38", "@vue/compiler-sfc": "3.5.38", "@vue/runtime-dom": "3.5.38", "@vue/server-renderer": "3.5.38", "@vue/shared": "3.5.38" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-vAMKHfImQlYSy0C+PBue4s3ERZ2xGKfgZg5GXAsLInq1dyh2H78ILVP5sK0KPFPVW4kv+OGCIvBEondcjpZp7A=="], + + "vue-demi": ["vue-demi@0.14.10", "", { "peerDependencies": { "@vue/composition-api": "^1.0.0-rc.1", "vue": "^3.0.0-0 || ^2.6.0" }, "optionalPeers": ["@vue/composition-api"], "bin": { "vue-demi-fix": "bin/vue-demi-fix.js", "vue-demi-switch": "bin/vue-demi-switch.js" } }, "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg=="], + + "vue-router": ["vue-router@4.6.4", "", { "dependencies": { "@vue/devtools-api": "^6.6.4" }, "peerDependencies": { "vue": "^3.5.0" } }, "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg=="], + + "vue-tsc": ["vue-tsc@2.2.12", "", { "dependencies": { "@volar/typescript": "2.4.15", "@vue/language-core": "2.2.12" }, "peerDependencies": { "typescript": ">=5.0.0" }, "bin": { "vue-tsc": "./bin/vue-tsc.js" } }, "sha512-P7OP77b2h/Pmk+lZdJ0YWs+5tJ6J2+uOQPo7tlBnY44QqQSPYvS0qVT4wqDJgwrZaLe47etJLLQRFia71GYITw=="], + } +} diff --git a/ui/index.html b/ui/index.html new file mode 100644 index 0000000..e66c144 --- /dev/null +++ b/ui/index.html @@ -0,0 +1,13 @@ + + + + + + Mercury + + + +
+ + + diff --git a/ui/package.json b/ui/package.json new file mode 100644 index 0000000..4e2e8ae --- /dev/null +++ b/ui/package.json @@ -0,0 +1,23 @@ +{ + "name": "mercury-ui", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc --noEmit && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@nychthemeron/library": "latest", + "pinia": "^2.1.0", + "vue": "^3.4.0", + "vue-router": "^4.3.0" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^5.0.0", + "typescript": "^5.3.0", + "vite": "^5.0.0", + "vue-tsc": "^2.0.0" + } +} diff --git a/ui/public/favicon.svg b/ui/public/favicon.svg new file mode 100644 index 0000000..12fae39 --- /dev/null +++ b/ui/public/favicon.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/ui/src/App.vue b/ui/src/App.vue new file mode 100644 index 0000000..7c2aa3f --- /dev/null +++ b/ui/src/App.vue @@ -0,0 +1,3 @@ + diff --git a/ui/src/assets/main.css b/ui/src/assets/main.css new file mode 100644 index 0000000..840efe7 --- /dev/null +++ b/ui/src/assets/main.css @@ -0,0 +1,246 @@ +*, +*::before, +*::after { + box-sizing: border-box; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + text-rendering: optimizeLegibility; +} + +body { + margin: 0; + font-family: var(--font-serif); + background-color: var(--surface-0); + color: var(--text-body); + min-height: 100vh; +} + +h1, +h2, +h3 { + font-family: var(--font-serif); + font-weight: 600; /* Cinzel's actual heaviest weight — avoids synthetic bold */ + font-optical-sizing: auto; + color: var(--text-high); + margin: 0; + letter-spacing: 0.06em; +} + +a { + color: var(--primary); + text-decoration: none; +} +a:hover { + text-decoration: underline; +} + +code { + font-family: var(--font-mono); + font-size: 0.85em; + color: var(--text-label); + background: var(--surface-2); + padding: 0.1em 0.4em; + border-radius: 3px; + border: 1px solid var(--border-lo); +} + +/* ── Page header ────────────────────────────────────────── */ +.page-header { + display: flex; + justify-content: space-between; + align-items: flex-end; + margin-bottom: 1.75rem; +} + +.page-title { + display: flex; + flex-direction: column; + gap: 0.25rem; +} + +.page-title h2 { + font-size: 1.6rem; + line-height: 1; +} + +.page-title .subtitle { + font-family: var(--font-sans); + font-size: 0.8rem; + color: var(--text-muted); + letter-spacing: 0.02em; +} + +/* ── Table card ─────────────────────────────────────────── */ +.table-card { + background-color: var(--surface-1); + border: 1px solid var(--border); + border-radius: 12px; + box-shadow: + 0 4px 24px rgba(0, 0, 0, 0.07), + 0 1px 4px rgba(0, 0, 0, 0.05); + overflow: hidden; +} + +/* Scroll wrapper sits inside the card so the header stays pinned */ +.table-scroll { + overflow-x: auto; +} + +.table-card-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.875rem 1.25rem; + border-bottom: 1px solid var(--border); + background: var(--surface-2); +} + +.table-card-header .count { + font-size: 0.78rem; + color: var(--text-muted); + font-family: var(--font-mono); +} + +.data-table { + width: 100%; + min-width: max-content; + border-collapse: collapse; + font-family: var(--font-serif); + font-size: 0.875rem; +} + +.data-table th { + padding: 0.65rem 1.25rem; + text-align: left; + background-color: var(--surface-2); + border-bottom: 1px solid var(--border); + font-weight: 700; + font-size: 0.7rem; + color: var(--text-muted); + letter-spacing: 0.1em; + text-transform: uppercase; +} + +.data-table td { + padding: 0.8rem 1.25rem; + text-align: left; + border-bottom: 1px solid var(--border-lo); + color: var(--text-body); + vertical-align: middle; +} + +.data-table tbody tr:last-child td { + border-bottom: none; +} + +.data-table tbody tr { + transition: background-color 0.12s ease; +} + +.data-table tbody tr:hover td { + background: color-mix(in srgb, var(--primary) 4%, var(--surface-1)); +} + +.actions-cell { + display: flex; + gap: 0.4rem; +} + +/* ── Empty state ────────────────────────────────────────── */ +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.5rem; + padding: 4rem 2rem; + color: var(--text-dim); +} + +.empty-state .empty-icon { + font-size: 2.5rem; + opacity: 0.35; + line-height: 1; +} + +.empty-state .empty-label { + font-family: var(--font-serif); + font-size: 1rem; + letter-spacing: 0.04em; + color: var(--text-muted); +} + +.empty-state .empty-hint { + font-size: 0.8rem; + color: var(--text-dim); +} + +/* ── Dialog form ────────────────────────────────────────── */ +.dialog-form { + display: flex; + flex-direction: column; + gap: 1.1rem; + padding-top: 0.25rem; +} + +.field { + display: flex; + flex-direction: column; + gap: 0.4rem; +} + +.field label { + font-size: 0.72rem; + font-weight: 700; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--text-muted); +} + +.field .hint { + margin: 0; + font-size: 0.78rem; + color: var(--text-dim); +} + +.optional { + font-weight: 400; + font-size: 0.72rem; + color: var(--text-dim); + letter-spacing: 0; + text-transform: none; +} + +/* ── Gold divider ───────────────────────────────────────── */ +.gold-rule { + display: flex; + align-items: center; + gap: 0.6rem; + color: var(--primary); + font-size: 0.6rem; + letter-spacing: 0.2em; + opacity: 0.6; +} +.gold-rule::before, +.gold-rule::after { + content: ""; + flex: 1; + height: 1px; + background: linear-gradient( + 90deg, + transparent, + var(--primary), + transparent + ); +} +.nych-dialog { + min-width: 500px; +} + +[class^="nych-button"] { + box-shadow: unset !important; +} + +[class^="nych-button"]:hover { + box-shadow: 0 0 5px var(--text-high); +} diff --git a/ui/src/env.d.ts b/ui/src/env.d.ts new file mode 100644 index 0000000..6ac34fb --- /dev/null +++ b/ui/src/env.d.ts @@ -0,0 +1,7 @@ +/// + +declare module '*.vue' { + import type { DefineComponent } from 'vue' + const component: DefineComponent + export default component +} diff --git a/ui/src/main.ts b/ui/src/main.ts new file mode 100644 index 0000000..92a3949 --- /dev/null +++ b/ui/src/main.ts @@ -0,0 +1,16 @@ +import { createApp } from "vue"; +import '@nychthemeron/library/theme' +import './assets/main.css' +import './stores/theme' +import { createPinia } from "pinia"; +import PrimeVue from "@primevue/core/config"; +import { createNychthemeron } from "@nychthemeron/library"; +import App from "./App.vue"; +import router from "./router"; + +const app = createApp(App); +app.use(createPinia()); +app.use(router); +app.use(PrimeVue, { unstyled: true }); +app.use(createNychthemeron()); +app.mount("#app"); diff --git a/ui/src/router/index.ts b/ui/src/router/index.ts new file mode 100644 index 0000000..fa876b5 --- /dev/null +++ b/ui/src/router/index.ts @@ -0,0 +1,36 @@ +import { createRouter, createWebHistory } from 'vue-router' +import { useAuthStore } from '../stores/auth' + +const router = createRouter({ + history: createWebHistory(), + routes: [ + { path: '/login', component: () => import('../views/Login.vue') }, + { + path: '/admin', + component: () => import('../views/admin/Layout.vue'), + children: [ + { path: 'queries', component: () => import('../views/admin/Queries.vue') }, + { path: 'tables', component: () => import('../views/admin/Tables.vue') }, + { path: 'users', component: () => import('../views/admin/Users.vue') }, + { path: 'permissions', component: () => import('../views/admin/Permissions.vue') }, + { path: 'blacklist', component: () => import('../views/admin/Blacklist.vue') }, + { path: 'api-keys', component: () => import('../views/admin/ApiKeys.vue') }, + { path: 'cache', component: () => import('../views/admin/Cache.vue') }, + ], + meta: { requiresAuth: true }, + }, + { path: '/', redirect: '/admin/queries' }, + ], +}) + +router.beforeEach((to) => { + const auth = useAuthStore() + if (to.meta.requiresAuth && !auth.isAuthenticated) { + return '/login' + } + if (to.path === '/login' && auth.isAuthenticated) { + return '/admin/queries' + } +}) + +export default router diff --git a/ui/src/stores/auth.ts b/ui/src/stores/auth.ts new file mode 100644 index 0000000..4fe8b5f --- /dev/null +++ b/ui/src/stores/auth.ts @@ -0,0 +1,70 @@ +import { defineStore } from "pinia"; +import { ref, computed } from "vue"; + +interface Claims { + sub: string; + permissions: string; + exp: number; +} + +function parseJwt(token: string): Claims | null { + try { + const payload = token.split(".")[1]; + return payload ? (JSON.parse(atob(payload)) as Claims) : null; + } catch { + return null; + } +} + +export const useAuthStore = defineStore("auth", () => { + const token = ref(localStorage.getItem("mercury_token")); + const claims = computed(() => + token.value ? parseJwt(token.value) : null, + ); + const isAuthenticated = computed(() => { + if (!claims.value) return false; + return claims.value.exp * 1000 > Date.now(); + }); + const username = computed(() => claims.value?.sub ?? ""); + + function hasPermission(bit: bigint): boolean { + if (!claims.value) return false; + const mask = BigInt(claims.value.permissions); + return (mask & bit) !== 0n; + } + + const isSuperAdmin = computed(() => hasPermission(32n)); + + async function login(username: string, password: string): Promise { + const res = await fetch("/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username, password }), + }); + if (!res.ok) throw new Error("Invalid credentials"); + const data = await res.json(); + token.value = data.token; + localStorage.setItem("mercury_token", data.token); + } + + function logout() { + token.value = null; + localStorage.removeItem("mercury_token"); + } + + function authHeaders(): Record { + return token.value ? { Authorization: `Bearer ${token.value}` } : {}; + } + + return { + token, + claims, + isAuthenticated, + username, + isSuperAdmin, + hasPermission, + login, + logout, + authHeaders, + }; +}); diff --git a/ui/src/stores/theme.ts b/ui/src/stores/theme.ts new file mode 100644 index 0000000..9cebd64 --- /dev/null +++ b/ui/src/stores/theme.ts @@ -0,0 +1,24 @@ +import { ref } from 'vue' + +export type Theme = 'apollo' | 'hades' + +const stored = localStorage.getItem('mercury-theme') as Theme | null +const theme = ref(stored ?? 'apollo') + +function applyTheme(t: Theme) { + theme.value = t + document.documentElement.setAttribute('data-theme', t) + localStorage.setItem('mercury-theme', t) +} + +applyTheme(theme.value) + +export function useTheme() { + return { + theme, + isDark: () => theme.value === 'hades', + toggle() { + applyTheme(theme.value === 'apollo' ? 'hades' : 'apollo') + }, + } +} diff --git a/ui/src/views/Login.vue b/ui/src/views/Login.vue new file mode 100644 index 0000000..c19ff7a --- /dev/null +++ b/ui/src/views/Login.vue @@ -0,0 +1,174 @@ + + + + + diff --git a/ui/src/views/admin/ApiKeys.vue b/ui/src/views/admin/ApiKeys.vue new file mode 100644 index 0000000..d79cf8a --- /dev/null +++ b/ui/src/views/admin/ApiKeys.vue @@ -0,0 +1,245 @@ + + + + + diff --git a/ui/src/views/admin/Blacklist.vue b/ui/src/views/admin/Blacklist.vue new file mode 100644 index 0000000..1ef743d --- /dev/null +++ b/ui/src/views/admin/Blacklist.vue @@ -0,0 +1,232 @@ + + + + + diff --git a/ui/src/views/admin/Cache.vue b/ui/src/views/admin/Cache.vue new file mode 100644 index 0000000..92ed187 --- /dev/null +++ b/ui/src/views/admin/Cache.vue @@ -0,0 +1,154 @@ + + + + + diff --git a/ui/src/views/admin/Layout.vue b/ui/src/views/admin/Layout.vue new file mode 100644 index 0000000..1e2f38b --- /dev/null +++ b/ui/src/views/admin/Layout.vue @@ -0,0 +1,265 @@ + + + + + diff --git a/ui/src/views/admin/MethodSelect.vue b/ui/src/views/admin/MethodSelect.vue new file mode 100644 index 0000000..128dab8 --- /dev/null +++ b/ui/src/views/admin/MethodSelect.vue @@ -0,0 +1,122 @@ + + + + + diff --git a/ui/src/views/admin/Permissions.vue b/ui/src/views/admin/Permissions.vue new file mode 100644 index 0000000..c1e6ec1 --- /dev/null +++ b/ui/src/views/admin/Permissions.vue @@ -0,0 +1,147 @@ + + + + + diff --git a/ui/src/views/admin/Queries.vue b/ui/src/views/admin/Queries.vue new file mode 100644 index 0000000..c2aa6e5 --- /dev/null +++ b/ui/src/views/admin/Queries.vue @@ -0,0 +1,137 @@ + + + + + diff --git a/ui/src/views/admin/Tables.vue b/ui/src/views/admin/Tables.vue new file mode 100644 index 0000000..af6c418 --- /dev/null +++ b/ui/src/views/admin/Tables.vue @@ -0,0 +1,571 @@ + + + + + diff --git a/ui/src/views/admin/Users.vue b/ui/src/views/admin/Users.vue new file mode 100644 index 0000000..95d22ff --- /dev/null +++ b/ui/src/views/admin/Users.vue @@ -0,0 +1,198 @@ + + + + + diff --git a/ui/tsconfig.json b/ui/tsconfig.json new file mode 100644 index 0000000..d5763ca --- /dev/null +++ b/ui/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "jsx": "preserve", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "isolatedModules": true, + "useDefineForClassFields": true + }, + "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], + "exclude": ["node_modules", "dist"] +} diff --git a/ui/vite.config.d.ts b/ui/vite.config.d.ts new file mode 100644 index 0000000..fd582a2 --- /dev/null +++ b/ui/vite.config.d.ts @@ -0,0 +1,3 @@ +declare const _default: any; +export default _default; +//# sourceMappingURL=vite.config.d.ts.map \ No newline at end of file diff --git a/ui/vite.config.d.ts.map b/ui/vite.config.d.ts.map new file mode 100644 index 0000000..0aae1e2 --- /dev/null +++ b/ui/vite.config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"vite.config.d.ts","sourceRoot":"","sources":["vite.config.ts"],"names":[],"mappings":";AAGA,wBAYE"} \ No newline at end of file diff --git a/ui/vite.config.js b/ui/vite.config.js new file mode 100644 index 0000000..5127513 --- /dev/null +++ b/ui/vite.config.js @@ -0,0 +1,16 @@ +import { defineConfig } from 'vite'; +import vue from '@vitejs/plugin-vue'; +export default defineConfig({ + plugins: [vue()], + server: { + proxy: { + '/api': 'http://localhost:3000', + '/auth': 'http://localhost:3000', + '/admin': 'http://localhost:3000', + }, + }, + build: { + outDir: 'dist', + }, +}); +//# sourceMappingURL=vite.config.js.map \ No newline at end of file diff --git a/ui/vite.config.js.map b/ui/vite.config.js.map new file mode 100644 index 0000000..4cb056d --- /dev/null +++ b/ui/vite.config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"vite.config.js","sourceRoot":"","sources":["vite.config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,MAAM,CAAA;AACnC,OAAO,GAAG,MAAM,oBAAoB,CAAA;AAEpC,eAAe,YAAY,CAAC;IAC1B,OAAO,EAAE,CAAC,GAAG,EAAE,CAAC;IAChB,MAAM,EAAE;QACN,KAAK,EAAE;YACL,MAAM,EAAE,uBAAuB;YAC/B,OAAO,EAAE,uBAAuB;YAChC,QAAQ,EAAE,uBAAuB;SAClC;KACF;IACD,KAAK,EAAE;QACL,MAAM,EAAE,MAAM;KACf;CACF,CAAC,CAAA"} \ No newline at end of file diff --git a/ui/vite.config.ts b/ui/vite.config.ts new file mode 100644 index 0000000..e4ef3c2 --- /dev/null +++ b/ui/vite.config.ts @@ -0,0 +1,29 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' + +export default defineConfig({ + plugins: [vue()], + server: { + proxy: { + '/api': 'http://localhost:3000', + '/auth': 'http://localhost:3000', + '/admin': 'http://localhost:3000', + }, + }, + build: { + outDir: 'dist', + cleanOutDir: true, + rollupOptions: { + output: { + manualChunks: { + vue: ['vue', 'vue-router', 'pinia'], + primevue: ['@primevue/core'], + nychthemeron: ['@nychthemeron/library'], + }, + entryFileNames: 'js/[name]-[hash].js', + chunkFileNames: 'js/[name]-[hash].js', + assetFileNames: 'assets/[name]-[hash][extname]', + }, + }, + }, +})