diff --git a/.firebaserc b/.firebaserc new file mode 100644 index 0000000..b55f805 --- /dev/null +++ b/.firebaserc @@ -0,0 +1,6 @@ +{ + "projects": { + "default": "devs-dev-2027", + "dev": "devs-dev-2027" + } +} diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..56dd9c1 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# Formatting-only commits, skipped by `git blame` on GitHub. +# Locally: git config blame.ignoreRevsFile .git-blame-ignore-revs + +# chore: reformat repo with prettier +feb6a181acb4f6f70adb3e13327fb88974419795 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..ba8ada6 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Regenerated by the pre-commit hook. On a merge conflict, run `pnpm graph` and stage the result. +kb/assets/dependency-graph.svg -diff linguist-generated=true diff --git a/.github/workflows/api.yml b/.github/workflows/api.yml new file mode 100644 index 0000000..709b432 --- /dev/null +++ b/.github/workflows/api.yml @@ -0,0 +1,36 @@ +# Builds and tests the Java API (apps/api). The tests start a Supabase Postgres with +# Testcontainers, apply db/migrations, and check every endpoint's access rules. + +name: API + +on: + pull_request: + paths: ["apps/api/**", "db/**", ".github/workflows/api.yml"] + push: + branches: [main] + paths: ["apps/api/**", "db/**", ".github/workflows/api.yml"] + +permissions: + contents: read + +jobs: + test: + name: Build and test + runs-on: ubuntu-latest + defaults: + run: + working-directory: apps/api + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "25" + cache: maven + + - name: Test + run: ./mvnw -B verify + + - name: Build the Docker image + run: docker build -t devs-api . diff --git a/.gitignore b/.gitignore index 0c3cfe4..152eea4 100644 --- a/.gitignore +++ b/.gitignore @@ -29,4 +29,17 @@ yarn.lock .env #Template for landing page slideshow -public/home/slideshow/template.psd \ No newline at end of file +public/home/slideshow/template.psd +# Firebase CLI cache +.firebase/ + +# Local DB dump / anonymised seed (contains prod schema incl. secrets) +dump/ +supabase/seed.sql + +# Supabase CLI local state +supabase/.branches +supabase/.temp + +# Personal Claude Code settings +.claude/ diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100644 index 0000000..b670edb --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1,7 @@ +# Commits are authored by people: reject AI co-author trailers (Claude, ChatGPT, Codex). +if grep -v '^#' "$1" | grep -Eiq '^co-authored-by:.*(claude|anthropic|chatgpt|codex|openai)'; then + echo "Remove the AI Co-Authored-By line from the commit message." >&2 + exit 1 +fi + +pnpm exec commitlint --edit "$1" diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 0000000..f9c5b54 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,3 @@ +pnpm exec lint-staged +pnpm graph +git add kb/assets/dependency-graph.svg diff --git a/README.md b/README.md index de34cda..202e1d4 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,13 @@ This repository contains the source code for the **DEVS (Developers Society) website**, built with **React, TypeScript, Tailwind CSS, and Vite**. The project follows a component-first approach with shared design and development guidelines to ensure consistency across the site. - + ## Documentation + Find all documentation, including a setup guide in the [Knowledge Base](kb/home.md). + +## Dependency Graph + +Every module in the website (`apps/web/src`) and what it imports. The pre-commit hook regenerates this on each commit, so it stays up to date as the code changes. Run `pnpm graph` to regenerate it manually. + +[![Dependency graph of apps/web/src](kb/assets/dependency-graph.svg)](kb/assets/dependency-graph.svg) diff --git a/apps/api/.dockerignore b/apps/api/.dockerignore new file mode 100644 index 0000000..dbb0988 --- /dev/null +++ b/apps/api/.dockerignore @@ -0,0 +1,4 @@ +target +*.iml +.idea +.vscode diff --git a/apps/api/.gitignore b/apps/api/.gitignore new file mode 100644 index 0000000..1ebf457 --- /dev/null +++ b/apps/api/.gitignore @@ -0,0 +1,3 @@ +target/ +*.iml +.idea/ diff --git a/apps/api/.mvn/wrapper/maven-wrapper.properties b/apps/api/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..216df05 --- /dev/null +++ b/apps/api/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile new file mode 100644 index 0000000..887557c --- /dev/null +++ b/apps/api/Dockerfile @@ -0,0 +1,17 @@ +# Build: compile and package the API. Tests run in CI, where Docker-in-Docker is available. +FROM maven:3.9-eclipse-temurin-25 AS build +WORKDIR /src +COPY pom.xml . +RUN mvn -B -q dependency:go-offline +COPY src src +RUN mvn -B -q -DskipTests package && cp target/devs-api-*.jar /api.jar + +# Run: JRE only, as an unprivileged user with nothing writable except the local storage folder. +FROM eclipse-temurin:25-jre-noble +RUN useradd --system --uid 10001 --no-create-home api \ + && mkdir -p /app /data/storage \ + && chown api /data/storage +COPY --from=build /api.jar /app/api.jar +USER 10001 +EXPOSE 8080 +ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/api.jar"] diff --git a/apps/api/README.md b/apps/api/README.md new file mode 100644 index 0000000..39997a8 --- /dev/null +++ b/apps/api/README.md @@ -0,0 +1,97 @@ +# DEVS API + +The only service that reads and writes the DEVS database and file storage. The website calls +this API; it no longer talks to Supabase tables, storage or edge functions directly. Supabase +is still used for logging in (Auth), Postgres and Storage. + +Java 25, Spring Boot 4, plain SQL through `JdbcClient`. Database changes live in +[`db/migrations`](../../db/migrations) and are applied by Flyway in CI, never by the API. + +## Run it locally + +With Docker: + +```sh +docker compose up --build # from the repo root +``` + +This starts a Supabase Postgres on `localhost:54330`, applies every migration, loads fake data +from [`db/seed/dev_seed.sql`](../../db/seed/dev_seed.sql), and runs the API on +`http://localhost:8080`. `docker compose down -v` wipes it. + +There's no Supabase Auth in the local stack, so mint a token for one of the seeded users: + +```sh +curl localhost:8080/api/events +curl -H "Authorization: Bearer $(apps/api/scripts/dev-token.sh admin)" localhost:8080/api/admin/members +``` + +`pnpm dev` proxies `/api` to `localhost:8080`, so the website's public pages work against the +local API. Admin pages need a real login: point the API at the shared dev Supabase project +instead (set `SUPABASE_URL` and `SUPABASE_JWT_SECRET` to the dev project's values). + +Without Docker, use the Maven wrapper with Java 25 installed: `./mvnw spring-boot:run`, with the +environment variables below pointing at the dev database. + +## Tests + +```sh +./mvnw verify +``` + +The integration tests start a Supabase Postgres with Testcontainers, so they need Docker; without +it they're skipped. CI always runs them. `SecurityMatrixTest` walks every endpoint and checks that +anonymous callers get 401 and non-admins get 403, so a new endpoint is covered automatically. + +## Configuration + +| Variable | What it is | +| -------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `DB_URL`, `DB_USER`, `DB_PASSWORD` | Postgres connection. Connect as `api_app` (see below), never `postgres`. | +| `SUPABASE_URL` | The project's URL, e.g. `https://.supabase.co`. Tokens must be issued by `/auth/v1`. | +| `SUPABASE_JWT_SECRET` | Legacy HS256 JWT secret. Leave empty if the project uses signing keys (JWKS). | +| `SUPABASE_SERVICE_ROLE_KEY` | Server-only key for Storage and inviting execs. Never put it in the website's env. | +| `SITE_URL` | The website's address, used for Stripe and invite redirects. | +| `CORS_ALLOWED_ORIGINS` | Comma-separated origins allowed to call the API. | +| `STORAGE_MODE` | `supabase` (default) or `local` (Docker dev). | +| `EMAIL_MODE`, `RESEND_API_KEY`, `CONTACT_EMAIL_TO` | `resend` sends mail; `log` only logs it. | +| `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` | Card payments. The webhook endpoint is `/api/webhooks/stripe`. | +| `MARKETING_APPS_SCRIPT_URL` | The Google Apps Script that writes marketing requests to the sheet. | +| `FORWARD_HEADERS_STRATEGY` | `native` behind a proxy that sets `X-Forwarded-For`, so rate limits see real IPs. | + +### The `api_app` database role + +Migration `V20261026_0310__api_role.sql` creates `api_app` with grants on exactly the tables the +API uses. It has no password until you set one, once per project, in the SQL editor: + +```sql +alter role api_app with password ''; +``` + +Then connect through the session pooler as `api_app.`. + +## How a request is handled + +1. CORS, security headers, and a per-IP rate limit on public writes (sign up, RSVP, contact). +2. A bearer token, if sent, must be a Supabase user access token for this project: valid + signature, issuer, audience `authenticated`, role `authenticated`, not expired. +3. The caller's role is read from `public.profiles` on every request. Nothing in the token or + request body can make someone an admin. +4. `SecurityConfig` decides who may call each path. Anything not listed is denied. +5. Request bodies are validated (types, sizes, formats) before any code runs. +6. Writes run in a transaction that first tells Postgres who the caller is (`ActorContext`), so the + existing audit triggers keep recording the real person. +7. Errors come back as `{ status, code, detail }`. No stack traces, SQL or internal names. + +## Endpoints + +Public: `GET /api/events`, `GET /api/links`, `GET /api/degrees`, `GET /api/degrees/{id}/majors`, +`POST /api/members`, `POST /api/events/{id}/rsvps`, `POST /api/events/{id}/rsvps/bank-transfer`, +`POST /api/events/{id}/rsvps/checkout`, `POST /api/contact`, `POST /api/webhooks/stripe` (Stripe-signed). + +Logged in: `GET /api/me`. + +Execs (`/api/admin/**`): events, uploads, attendees and payment proofs, members, links, event +to-dos/notes/doc links, tasks and comments, marketing requests. + +Superusers: `/api/admin/audit-log/**` (view and restore) and `/api/admin/users/invite`. diff --git a/apps/api/mvnw b/apps/api/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/apps/api/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/apps/api/mvnw.cmd b/apps/api/mvnw.cmd new file mode 100644 index 0000000..5761d94 --- /dev/null +++ b/apps/api/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/apps/api/pom.xml b/apps/api/pom.xml new file mode 100644 index 0000000..b9d215c --- /dev/null +++ b/apps/api/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.2 + + + + com.devsuoa + devs-api + 0.1.0 + DEVS API + The only service that talks to the DEVS database and storage. + + + 25 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-security-oauth2-resource-server + + + org.springframework.boot + spring-boot-starter-jdbc + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-restclient + + + org.springframework.boot + spring-boot-starter-actuator + + + org.postgresql + postgresql + runtime + + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + org.springframework.boot + spring-boot-starter-security-test + test + + + org.springframework.boot + spring-boot-testcontainers + test + + + org.testcontainers + testcontainers-junit-jupiter + test + + + + org.flywaydb + flyway-database-postgresql + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/apps/api/scripts/dev-token.sh b/apps/api/scripts/dev-token.sh new file mode 100755 index 0000000..dfea79b --- /dev/null +++ b/apps/api/scripts/dev-token.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Prints a JWT for one of the seeded local users, signed with the local compose secret. +# Only works against the local stack (docker compose), never a real Supabase project. +# +# apps/api/scripts/dev-token.sh admin # Ada Admin, tech team +# apps/api/scripts/dev-token.sh super # Sam Super, president, superuser +# apps/api/scripts/dev-token.sh user # Una User, not an exec +# +# curl -H "Authorization: Bearer $(apps/api/scripts/dev-token.sh admin)" localhost:8080/api/me +set -euo pipefail + +case "${1:-admin}" in + admin) sub=00000000-0000-4000-8000-000000000001 ;; + super) sub=00000000-0000-4000-8000-000000000002 ;; + user) sub=00000000-0000-4000-8000-000000000003 ;; + *) echo "usage: $0 admin|super|user" >&2; exit 1 ;; +esac + +secret="local-dev-jwt-secret-not-for-production-0123456789" +issuer="http://localhost:54321/auth/v1" +now=$(date +%s) + +b64url() { openssl base64 -A | tr '+/' '-_' | tr -d '='; } + +header=$(printf '{"alg":"HS256","typ":"JWT"}' | b64url) +payload=$(printf '{"sub":"%s","iss":"%s","aud":"authenticated","role":"authenticated","email":"%s@example.test","iat":%d,"exp":%d}' \ + "$sub" "$issuer" "$1" "$now" "$((now + 3600))" | b64url) +signature=$(printf '%s.%s' "$header" "$payload" | openssl dgst -sha256 -hmac "$secret" -binary | b64url) + +printf '%s.%s.%s\n' "$header" "$payload" "$signature" diff --git a/apps/api/src/main/java/com/devsuoa/api/ApiApplication.java b/apps/api/src/main/java/com/devsuoa/api/ApiApplication.java new file mode 100644 index 0000000..7efbc10 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/ApiApplication.java @@ -0,0 +1,16 @@ +package com.devsuoa.api; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@ConfigurationPropertiesScan +@EnableScheduling +public class ApiApplication { + + public static void main(String[] args) { + SpringApplication.run(ApiApplication.class, args); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/audit/AuditController.java b/apps/api/src/main/java/com/devsuoa/api/audit/AuditController.java new file mode 100644 index 0000000..7cb0f1f --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/audit/AuditController.java @@ -0,0 +1,190 @@ +package com.devsuoa.api.audit; + +import com.devsuoa.api.auth.ActorContext; +import com.devsuoa.api.common.ApiException; +import com.devsuoa.api.common.Json; +import java.time.OffsetDateTime; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.node.ObjectNode; + +/** + * The CMS audit log, for superusers only. Restoring an entry replaces the old browser code + * that sent raw DELETE/POST/PATCH requests for any table name it was given. + */ +@RestController +public class AuditController { + + public record Entry(UUID id, OffsetDateTime createdAt, String adminName, String adminTeam, UUID authId, String action, + String targetTable, String targetId, JsonNode targetOld, JsonNode targetNew, String userAgent, String ipAddress, + String undoOf) {} + + /** + * Tables whose changes can be reverted, and the column the audit trigger uses as target_id. + * {@code profiles} is left out on purpose: restoring a profile could hand out admin rights. + */ + static final Map RESTORABLE = Map.of( + "events", "id", + "links", "id", + "tasks", "id", + "task_comments", "id", + "events_rsvp", "id", + "marketing_requests", "id", + "members", "student_id"); + + private static final int MAX_PAGE_SIZE = 5000; + + private final JdbcClient jdbc; + private final Json json; + private final ActorContext actor; + + public AuditController(JdbcClient jdbc, Json json, ActorContext actor) { + this.jdbc = jdbc; + this.json = json; + this.actor = actor; + } + + @GetMapping("/api/admin/audit-log") + List list(@RequestParam(defaultValue = "0") int page, @RequestParam(name = "page_size", defaultValue = "500") int pageSize) { + int size = Math.clamp(pageSize, 1, MAX_PAGE_SIZE); + int offset = Math.max(page, 0) * size; + return jdbc.sql(""" + select id, created_at, admin_name, admin_team, auth_id, action, target_table, target_id, + target_old::text as target_old, target_new::text as target_new, user_agent, ip_address, undo_of + from public.admin_audit_log order by created_at desc limit :size offset :offset + """) + .param("size", size).param("offset", offset) + .query((rs, n) -> new Entry( + rs.getObject("id", UUID.class), + rs.getObject("created_at", OffsetDateTime.class), + rs.getString("admin_name"), + rs.getString("admin_team"), + rs.getObject("auth_id", UUID.class), + rs.getString("action"), + rs.getString("target_table"), + rs.getString("target_id"), + json.parse(rs.getString("target_old")), + json.parse(rs.getString("target_new")), + rs.getString("user_agent"), + rs.getString("ip_address"), + rs.getString("undo_of"))) + .list(); + } + + /** + * Undoes one logged change. Refuses if the row has changed since, so a restore can't + * silently overwrite later work. + */ + @PostMapping("/api/admin/audit-log/{id}/restore") + @ResponseStatus(HttpStatus.NO_CONTENT) + @Transactional + void restore(@PathVariable UUID id) { + actor.bind(id.toString()); + Entry e = find(id).orElseThrow(() -> ApiException.notFound("Audit entry")); + String pk = RESTORABLE.get(e.targetTable()); + if (pk == null) throw ApiException.badRequest("not_restorable", "Changes to this table can't be restored here."); + String table = "public." + quote(e.targetTable()); + Set columns = columns(e.targetTable()); + + Optional current = jdbc.sql("select to_jsonb(t)::text from " + table + " t where " + quote(pk) + "::text = :pk") + .param("pk", e.targetId()) + .query(String.class) + .optional() + .map(json::parse); + + switch (e.action().toUpperCase()) { + case "INSERT", "CREATE" -> { + requireUnchanged(current, e.targetNew()); + jdbc.sql("delete from " + table + " where " + quote(pk) + "::text = :pk").param("pk", e.targetId()).update(); + } + case "DELETE" -> { + if (current.isPresent()) throw ApiException.conflict("row_exists", "That row exists again, so there's nothing to restore."); + ObjectNode snapshot = only(e.targetOld(), columns); + String cols = snapshot.propertyNames().stream().map(AuditController::quote).collect(Collectors.joining(", ")); + jdbc.sql("insert into " + table + " (" + cols + ") select " + cols + + " from jsonb_populate_record(null::" + table + ", cast(:snap as jsonb))") + .param("snap", snapshot.toString()) + .update(); + } + case "UPDATE" -> { + requireUnchanged(current, e.targetNew()); + ObjectNode snapshot = only(e.targetOld(), columns); + snapshot.remove(pk); + if (snapshot.isEmpty()) return; + String cols = snapshot.propertyNames().stream().map(AuditController::quote).collect(Collectors.joining(", ")); + jdbc.sql("update " + table + " set (" + cols + ") = (select " + cols + + " from jsonb_populate_record(null::" + table + ", cast(:snap as jsonb))) where " + + quote(pk) + "::text = :pk") + .param("snap", snapshot.toString()) + .param("pk", e.targetId()) + .update(); + } + default -> throw ApiException.badRequest("not_restorable", "This entry can't be restored."); + } + } + + private Optional find(UUID id) { + return jdbc.sql(""" + select id, created_at, admin_name, admin_team, auth_id, action, target_table, target_id, + target_old::text as target_old, target_new::text as target_new, user_agent, ip_address, undo_of + from public.admin_audit_log where id = :id + """) + .param("id", id) + .query((rs, n) -> new Entry(rs.getObject("id", UUID.class), rs.getObject("created_at", OffsetDateTime.class), + rs.getString("admin_name"), rs.getString("admin_team"), rs.getObject("auth_id", UUID.class), + rs.getString("action"), rs.getString("target_table"), rs.getString("target_id"), + json.parse(rs.getString("target_old")), json.parse(rs.getString("target_new")), + rs.getString("user_agent"), rs.getString("ip_address"), rs.getString("undo_of"))) + .optional(); + } + + /** The row must still look exactly like it did right after the logged change. */ + private static void requireUnchanged(Optional current, JsonNode expected) { + if (current.isEmpty()) throw ApiException.conflict("row_missing", "That row no longer exists."); + if (expected == null || !expected.isObject()) throw ApiException.badRequest("not_restorable", "This entry can't be restored."); + for (String key : expected.propertyNames()) { + if (!expected.get(key).equals(current.get().get(key))) { + throw ApiException.conflict("changed_since", "That row has changed since this entry. Restore the later entries first."); + } + } + } + + /** Keeps only real columns of the table, so a snapshot can't name anything else. */ + private ObjectNode only(JsonNode snapshot, Set columns) { + if (snapshot == null || !snapshot.isObject()) throw ApiException.badRequest("not_restorable", "This entry can't be restored."); + ObjectNode out = json.mapper().createObjectNode(); + for (String key : snapshot.propertyNames()) { + if (columns.contains(key)) out.set(key, snapshot.get(key)); + } + return out; + } + + private Set columns(String table) { + return new HashSet<>(jdbc.sql(""" + select column_name from information_schema.columns + where table_schema = 'public' and table_name = :t and is_generated = 'NEVER' and identity_generation is null + """) + .param("t", table) + .query(String.class) + .list()); + } + + private static String quote(String identifier) { + return "\"" + identifier.replace("\"", "\"\"") + "\""; + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/auth/ActorContext.java b/apps/api/src/main/java/com/devsuoa/api/auth/ActorContext.java new file mode 100644 index 0000000..315e9cd --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/auth/ActorContext.java @@ -0,0 +1,83 @@ +package com.devsuoa.api.auth; + +import jakarta.servlet.http.HttpServletRequest; +import java.util.LinkedHashMap; +import java.util.Map; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import tools.jackson.databind.json.JsonMapper; + +/** + * Tells the database who is making a change, so the existing audit triggers + * ({@code public.log_admin_action}) keep recording the real person. + * + *

Supabase's {@code auth.uid()} reads {@code request.jwt.claims}, and the trigger reads + * {@code request.headers}. PostgREST used to set both; the API now sets them with + * {@code set_config(..., true)}, which only lasts until the end of the current transaction. + * Call {@link #bind()} first thing in every {@code @Transactional} method that writes. + */ +@Component +public class ActorContext { + + private final JdbcClient jdbc; + private final JsonMapper json; + + public ActorContext(JdbcClient jdbc, JsonMapper json) { + this.jdbc = jdbc; + this.json = json; + } + + public void bind() { + bind(null); + } + + /** @param undoOf audit log id this change reverts, recorded in {@code admin_audit_log.undo_of} */ + public void bind(String undoOf) { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + // Outside a transaction set_config would leak onto a pooled connection. + throw new IllegalStateException("ActorContext.bind() must run inside a transaction"); + } + + Map claims = new LinkedHashMap<>(); + Auth.current().ifPresentOrElse( + u -> { + claims.put("sub", u.id().toString()); + claims.put("role", "authenticated"); + }, + () -> claims.put("role", "anon")); + + Map headers = new LinkedHashMap<>(); + HttpServletRequest request = currentRequest(); + if (request != null) { + String userAgent = request.getHeader("User-Agent"); + headers.put("user-agent", userAgent == null ? "unknown" : truncate(userAgent, 300)); + headers.put("x-forwarded-for", request.getRemoteAddr()); + } + headers.put("x-devs-api", "true"); + if (undoOf != null) headers.put("x-audit-undo", undoOf); + + // Older auth.uid() definitions read request.jwt.claim.sub, newer ones request.jwt.claims: set both. + jdbc.sql(""" + select set_config('request.jwt.claims', :claims, true), + set_config('request.jwt.claim.sub', :sub, true), + set_config('request.headers', :headers, true) + """) + .param("claims", json.writeValueAsString(claims)) + .param("sub", (String) claims.getOrDefault("sub", "")) + .param("headers", json.writeValueAsString(headers)) + .query() + .listOfRows(); + } + + private static HttpServletRequest currentRequest() { + if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes a) return a.getRequest(); + return null; + } + + private static String truncate(String s, int max) { + return s.length() <= max ? s : s.substring(0, max); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/auth/Auth.java b/apps/api/src/main/java/com/devsuoa/api/auth/Auth.java new file mode 100644 index 0000000..483a4c1 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/auth/Auth.java @@ -0,0 +1,23 @@ +package com.devsuoa.api.auth; + +import com.devsuoa.api.common.ApiException; +import java.util.Optional; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +/** Static access to the caller, for services that are not handed it by a controller. */ +public final class Auth { + + private Auth() {} + + public static Optional current() { + Authentication a = SecurityContextHolder.getContext().getAuthentication(); + if (a instanceof DevsAuthentication d) return Optional.of(d.getPrincipal()); + return Optional.empty(); + } + + public static CurrentUser require() { + return current().orElseThrow(() -> new ApiException(HttpStatus.UNAUTHORIZED, "unauthenticated", "Please log in.")); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/auth/CurrentUser.java b/apps/api/src/main/java/com/devsuoa/api/auth/CurrentUser.java new file mode 100644 index 0000000..b426ad5 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/auth/CurrentUser.java @@ -0,0 +1,34 @@ +package com.devsuoa.api.auth; + +import java.util.UUID; + +/** + * The logged-in person, as the database sees them. Roles come from {@code public.profiles}, + * which clients can no longer write to, never from claims inside the JWT. + */ +public record CurrentUser(UUID id, String email, String username, String role, String team, boolean superuser) { + + public static final String ROLE_ADMIN = "ROLE_ADMIN"; + public static final String ROLE_SUPERUSER = "ROLE_SUPERUSER"; + + /** Teams whose members see every team's tasks. Mirrors the old RLS policy. */ + public static final java.util.Set GLOBAL_TEAMS = java.util.Set.of("president", "senior_advisor"); + + public boolean isAdmin() { + return "admin".equals(role); + } + + public boolean isSuperuserAdmin() { + return isAdmin() && superuser; + } + + public boolean seesAllTeams() { + return team != null && GLOBAL_TEAMS.contains(team); + } + + public String displayName() { + if (username != null && !username.isBlank()) return username; + if (email != null && !email.isBlank()) return email; + return "Unknown"; + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/auth/DevsAuthentication.java b/apps/api/src/main/java/com/devsuoa/api/auth/DevsAuthentication.java new file mode 100644 index 0000000..b8e22cf --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/auth/DevsAuthentication.java @@ -0,0 +1,35 @@ +package com.devsuoa.api.auth; + +import java.util.Collection; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; + +/** A verified Supabase JWT plus the profile it belongs to. */ +public class DevsAuthentication extends AbstractAuthenticationToken { + + private final Jwt jwt; + private final CurrentUser user; + + public DevsAuthentication(Jwt jwt, CurrentUser user, Collection authorities) { + super(authorities); + this.jwt = jwt; + this.user = user; + setAuthenticated(true); + } + + @Override + public Object getCredentials() { + return jwt; + } + + @Override + public CurrentUser getPrincipal() { + return user; + } + + @Override + public String getName() { + return user.id().toString(); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/auth/MeController.java b/apps/api/src/main/java/com/devsuoa/api/auth/MeController.java new file mode 100644 index 0000000..20429aa --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/auth/MeController.java @@ -0,0 +1,23 @@ +package com.devsuoa.api.auth; + +import java.util.Map; +import java.util.UUID; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class MeController { + + public record Me(UUID id, String email, String username, String role, String team, boolean isSuperuser) {} + + @GetMapping("/api/health") + Map health() { + return Map.of("status", "ok"); + } + + @GetMapping("/api/me") + Me me() { + CurrentUser u = Auth.require(); + return new Me(u.id(), u.email(), u.username(), u.role(), u.team(), u.superuser()); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/auth/ProfileAuthenticationConverter.java b/apps/api/src/main/java/com/devsuoa/api/auth/ProfileAuthenticationConverter.java new file mode 100644 index 0000000..9c3630e --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/auth/ProfileAuthenticationConverter.java @@ -0,0 +1,39 @@ +package com.devsuoa.api.auth; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.springframework.core.convert.converter.Converter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.stereotype.Component; + +/** + * Turns a verified JWT into a {@link DevsAuthentication}. The JWT only proves who the + * caller is. What they may do is looked up in the database on every request, so removing + * someone's admin role takes effect immediately rather than when their token expires. + */ +@Component +public class ProfileAuthenticationConverter implements Converter { + + private final ProfileRepository profiles; + + public ProfileAuthenticationConverter(ProfileRepository profiles) { + this.profiles = profiles; + } + + @Override + public DevsAuthentication convert(Jwt jwt) { + UUID id = UUID.fromString(jwt.getSubject()); + String email = jwt.getClaimAsString("email"); + CurrentUser user = profiles.find(id) + .map(p -> new CurrentUser(id, email, p.username(), p.role(), p.team(), p.superuser())) + .orElseGet(() -> new CurrentUser(id, email, null, "user", null, false)); + + List authorities = new ArrayList<>(); + if (user.isAdmin()) authorities.add(new SimpleGrantedAuthority(CurrentUser.ROLE_ADMIN)); + if (user.isSuperuserAdmin()) authorities.add(new SimpleGrantedAuthority(CurrentUser.ROLE_SUPERUSER)); + return new DevsAuthentication(jwt, user, authorities); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/auth/ProfileRepository.java b/apps/api/src/main/java/com/devsuoa/api/auth/ProfileRepository.java new file mode 100644 index 0000000..75628dc --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/auth/ProfileRepository.java @@ -0,0 +1,55 @@ +package com.devsuoa.api.auth; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Repository; + +@Repository +public class ProfileRepository { + + public record Profile(UUID id, String username, String role, String team, boolean superuser) {} + + public record AdminSummary(UUID id, String username) {} + + private final JdbcClient jdbc; + + public ProfileRepository(JdbcClient jdbc) { + this.jdbc = jdbc; + } + + public Optional find(UUID id) { + return jdbc.sql(""" + select id, username, role, team::text as team, is_superuser + from public.profiles where id = :id + """) + .param("id", id) + .query((rs, n) -> new Profile( + rs.getObject("id", UUID.class), + rs.getString("username"), + rs.getString("role"), + rs.getString("team"), + rs.getBoolean("is_superuser"))) + .optional(); + } + + public List admins() { + return jdbc.sql("select id, username from public.profiles where role = 'admin' order by username") + .query((rs, n) -> new AdminSummary(rs.getObject("id", UUID.class), rs.getString("username"))) + .list(); + } + + /** Makes an invited account an exec. Upserts in case the handle_new_user trigger hasn't run. */ + public void promote(UUID id, String username, String team) { + jdbc.sql(""" + insert into public.profiles (id, role, username, team) + values (:id, 'admin', :username, cast(:team as public.team_enum)) + on conflict (id) do update set role = 'admin', username = excluded.username, team = excluded.team + """) + .param("id", id) + .param("username", username) + .param("team", team) + .update(); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/common/ApiException.java b/apps/api/src/main/java/com/devsuoa/api/common/ApiException.java new file mode 100644 index 0000000..ddb7d49 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/common/ApiException.java @@ -0,0 +1,43 @@ +package com.devsuoa.api.common; + +import org.springframework.http.HttpStatus; + +/** + * An error the client is allowed to see. {@code code} is a stable machine-readable + * string the frontend switches on; {@code message} is safe to show to a person. + */ +public class ApiException extends RuntimeException { + + private final HttpStatus status; + private final String code; + + public ApiException(HttpStatus status, String code, String message) { + super(message); + this.status = status; + this.code = code; + } + + public HttpStatus status() { + return status; + } + + public String code() { + return code; + } + + public static ApiException notFound(String what) { + return new ApiException(HttpStatus.NOT_FOUND, "not_found", what + " not found."); + } + + public static ApiException badRequest(String code, String message) { + return new ApiException(HttpStatus.BAD_REQUEST, code, message); + } + + public static ApiException conflict(String code, String message) { + return new ApiException(HttpStatus.CONFLICT, code, message); + } + + public static ApiException forbidden(String message) { + return new ApiException(HttpStatus.FORBIDDEN, "forbidden", message); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/common/GlobalExceptionHandler.java b/apps/api/src/main/java/com/devsuoa/api/common/GlobalExceptionHandler.java new file mode 100644 index 0000000..b8cfb9c --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/common/GlobalExceptionHandler.java @@ -0,0 +1,118 @@ +package com.devsuoa.api.common; + +import jakarta.validation.ConstraintViolationException; +import java.util.LinkedHashMap; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ProblemDetail; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import org.springframework.web.multipart.MaxUploadSizeExceededException; +import org.springframework.web.multipart.support.MissingServletRequestPartException; +import org.springframework.web.servlet.resource.NoResourceFoundException; + +/** + * Turns every exception into a small JSON problem: {@code {status, code, detail}}. + * Stack traces, SQL and constraint names never reach the client; they go to the log. + */ +@RestControllerAdvice +public class GlobalExceptionHandler { + + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + public static ProblemDetail problem(HttpStatus status, String code, String detail) { + ProblemDetail p = ProblemDetail.forStatusAndDetail(status, detail); + p.setProperty("code", code); + return p; + } + + @ExceptionHandler(ApiException.class) + ResponseEntity api(ApiException e) { + return ResponseEntity.status(e.status()).body(problem(e.status(), e.code(), e.getMessage())); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + ResponseEntity invalidBody(MethodArgumentNotValidException e) { + Map fields = new LinkedHashMap<>(); + e.getBindingResult().getFieldErrors().forEach(f -> fields.putIfAbsent(f.getField(), f.getDefaultMessage())); + ProblemDetail p = problem(HttpStatus.BAD_REQUEST, "invalid_input", "Some fields are invalid."); + p.setProperty("fields", fields); + return ResponseEntity.badRequest().body(p); + } + + @ExceptionHandler(ConstraintViolationException.class) + ResponseEntity invalidParam(ConstraintViolationException e) { + return ResponseEntity.badRequest().body(problem(HttpStatus.BAD_REQUEST, "invalid_input", "Some parameters are invalid.")); + } + + @ExceptionHandler({ + HttpMessageNotReadableException.class, + MethodArgumentTypeMismatchException.class, + MissingServletRequestParameterException.class, + MissingServletRequestPartException.class + }) + ResponseEntity unreadable(Exception e) { + return ResponseEntity.badRequest().body(problem(HttpStatus.BAD_REQUEST, "invalid_input", "The request could not be read.")); + } + + @ExceptionHandler(MaxUploadSizeExceededException.class) + ResponseEntity tooLarge(MaxUploadSizeExceededException e) { + return ResponseEntity.status(HttpStatus.CONTENT_TOO_LARGE) + .body(problem(HttpStatus.CONTENT_TOO_LARGE, "file_too_large", "The file is too large.")); + } + + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + ResponseEntity mediaType(HttpMediaTypeNotSupportedException e) { + return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE) + .body(problem(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "unsupported_media_type", "Unsupported content type.")); + } + + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + ResponseEntity method(HttpRequestMethodNotSupportedException e) { + return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) + .body(problem(HttpStatus.METHOD_NOT_ALLOWED, "method_not_allowed", "Method not allowed.")); + } + + @ExceptionHandler(NoResourceFoundException.class) + ResponseEntity noRoute(NoResourceFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(problem(HttpStatus.NOT_FOUND, "not_found", "Not found.")); + } + + @ExceptionHandler(DataIntegrityViolationException.class) + ResponseEntity integrity(DataIntegrityViolationException e) { + log.info("Data integrity violation: {}", e.getMostSpecificCause().getMessage()); + return ResponseEntity.status(HttpStatus.CONFLICT) + .body(problem(HttpStatus.CONFLICT, "conflict", "That change conflicts with existing data.")); + } + + // Method security (@PreAuthorize) throws these inside the MVC layer. + @ExceptionHandler(AccessDeniedException.class) + ResponseEntity denied(AccessDeniedException e) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(problem(HttpStatus.FORBIDDEN, "forbidden", "You don't have access to this.")); + } + + @ExceptionHandler(AuthenticationException.class) + ResponseEntity unauthenticated(AuthenticationException e) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body(problem(HttpStatus.UNAUTHORIZED, "unauthenticated", "Please log in.")); + } + + @ExceptionHandler(Exception.class) + ResponseEntity unexpected(Exception e) { + log.error("Unhandled error", e); + return ResponseEntity.internalServerError() + .body(problem(HttpStatus.INTERNAL_SERVER_ERROR, "internal_error", "Something went wrong.")); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/common/Json.java b/apps/api/src/main/java/com/devsuoa/api/common/Json.java new file mode 100644 index 0000000..4282269 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/common/Json.java @@ -0,0 +1,30 @@ +package com.devsuoa.api.common; + +import org.springframework.stereotype.Component; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.JsonNodeFactory; + +/** Reads and writes the jsonb columns (RSVP questions and answers, group emails, audit snapshots). */ +@Component +public class Json { + + private final JsonMapper mapper; + + public Json(JsonMapper mapper) { + this.mapper = mapper; + } + + public JsonNode parse(String text) { + if (text == null) return JsonNodeFactory.instance.nullNode(); + return mapper.readTree(text); + } + + public String write(Object value) { + return mapper.writeValueAsString(value); + } + + public JsonMapper mapper() { + return mapper; + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/common/Urls.java b/apps/api/src/main/java/com/devsuoa/api/common/Urls.java new file mode 100644 index 0000000..7c03d19 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/common/Urls.java @@ -0,0 +1,36 @@ +package com.devsuoa.api.common; + +import java.net.URI; +import java.util.Locale; +import java.util.Set; + +/** URL checks for anything an admin can type that later ends up in an href or img src. */ +public final class Urls { + + private Urls() {} + + /** Throws unless {@code value} is null/blank or an absolute URL with one of {@code schemes}. */ + public static String requireScheme(String value, String field, Set schemes) { + if (value == null || value.isBlank()) return null; + String trimmed = value.trim(); + try { + URI uri = new URI(trimmed); + String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT); + if (!schemes.contains(scheme)) throw invalid(field); + if ((scheme.equals("http") || scheme.equals("https")) && (uri.getHost() == null || uri.getHost().isBlank())) { + throw invalid(field); + } + return trimmed; + } catch (java.net.URISyntaxException e) { + throw invalid(field); + } + } + + public static String requireWeb(String value, String field) { + return requireScheme(value, field, Set.of("http", "https")); + } + + private static ApiException invalid(String field) { + return ApiException.badRequest("invalid_url", "The " + field + " must be a full web address."); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/config/DevsProperties.java b/apps/api/src/main/java/com/devsuoa/api/config/DevsProperties.java new file mode 100644 index 0000000..6749bf7 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/config/DevsProperties.java @@ -0,0 +1,33 @@ +package com.devsuoa.api.config; + +import java.math.BigDecimal; +import java.util.List; +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** Settings under {@code devs.*} in application.yml. */ +@ConfigurationProperties("devs") +public record DevsProperties( + String siteUrl, + List corsAllowedOrigins, + Schema schema, + Supabase supabase, + Storage storage, + Email email, + Stripe stripe, + Marketing marketing, + RateLimit rateLimit) { + + public record Schema(String requiredVersion, boolean checkOnStartup) {} + + public record Supabase(String url, String jwtSecret, String serviceRoleKey) {} + + public record Storage(String mode, String localDir, String publicBaseUrl) {} + + public record Email(String mode, String resendApiKey, String from, String contactTo) {} + + public record Stripe(String secretKey, String webhookSecret, BigDecimal cardFeePercent, BigDecimal cardFeeFixed) {} + + public record Marketing(String appsScriptUrl) {} + + public record RateLimit(int publicWritesPerMinute) {} +} diff --git a/apps/api/src/main/java/com/devsuoa/api/config/RateLimitFilter.java b/apps/api/src/main/java/com/devsuoa/api/config/RateLimitFilter.java new file mode 100644 index 0000000..6f3ecc4 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/config/RateLimitFilter.java @@ -0,0 +1,67 @@ +package com.devsuoa.api.config; + +import com.devsuoa.api.common.GlobalExceptionHandler; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import tools.jackson.databind.json.JsonMapper; + +/** + * Caps how often one IP can call the public write endpoints (sign up, RSVP, contact form), + * which is what bots and enumeration scripts hammer. Counts reset every minute. + * + *

This is per instance and in memory. That is enough for one API instance; run it behind + * the edge's rate limiting as well once there is more than one. + */ +@Component +public class RateLimitFilter extends OncePerRequestFilter { + + private final ConcurrentHashMap counts = new ConcurrentHashMap<>(); + private final int perMinute; + private final JsonMapper json; + + public RateLimitFilter(DevsProperties props, JsonMapper json) { + this.perMinute = props.rateLimit().publicWritesPerMinute(); + this.json = json; + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + if (!"POST".equals(request.getMethod())) return true; + String path = request.getRequestURI(); + boolean publicWrite = path.equals("/api/members") + || path.equals("/api/contact") + || (path.startsWith("/api/events/") && path.contains("/rsvps")); + return !publicWrite; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + String key = request.getRemoteAddr(); + int n = counts.computeIfAbsent(key, k -> new AtomicInteger()).incrementAndGet(); + if (n > perMinute) { + response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); + response.setHeader("Retry-After", "60"); + response.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE); + response.getWriter().write(json.writeValueAsString(GlobalExceptionHandler.problem( + HttpStatus.TOO_MANY_REQUESTS, "rate_limited", "Too many requests. Please wait a minute and try again."))); + return; + } + chain.doFilter(request, response); + } + + @Scheduled(fixedRate = 60_000) + void reset() { + counts.clear(); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/config/SchemaVersionCheck.java b/apps/api/src/main/java/com/devsuoa/api/config/SchemaVersionCheck.java new file mode 100644 index 0000000..03c3554 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/config/SchemaVersionCheck.java @@ -0,0 +1,53 @@ +package com.devsuoa.api.config; + +import java.math.BigDecimal; +import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Component; + +/** + * Refuses to start against a database that is missing migrations this code depends on. + * The API never runs migrations itself: CI applies them (see kb/database_migrations.md). + */ +@Component +public class SchemaVersionCheck implements ApplicationRunner { + + private static final Logger log = LoggerFactory.getLogger(SchemaVersionCheck.class); + + private final JdbcClient jdbc; + private final DevsProperties props; + + public SchemaVersionCheck(JdbcClient jdbc, DevsProperties props) { + this.jdbc = jdbc; + this.props = props; + } + + @Override + public void run(ApplicationArguments args) { + if (!props.schema().checkOnStartup()) return; + BigDecimal required = new BigDecimal(props.schema().requiredVersion()); + + Optional current; + try { + current = jdbc.sql(""" + select max(cast(version as numeric)) from flyway.flyway_schema_history + where success and version is not null + """) + .query(BigDecimal.class) + .optional(); + } catch (RuntimeException e) { + throw new IllegalStateException("Cannot read flyway.flyway_schema_history. Has the database been migrated?", e); + } + + BigDecimal version = current.orElse(BigDecimal.ZERO); + if (version.compareTo(required) < 0) { + throw new IllegalStateException("Database is at migration " + version + " but this API needs " + required + + ". Apply the missing migrations in db/migrations first."); + } + log.info("Database schema at {} (needs {})", version, required); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/config/SecurityConfig.java b/apps/api/src/main/java/com/devsuoa/api/config/SecurityConfig.java new file mode 100644 index 0000000..5aa9458 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/config/SecurityConfig.java @@ -0,0 +1,158 @@ +package com.devsuoa.api.config; + +import com.devsuoa.api.auth.ProfileAuthenticationConverter; +import com.devsuoa.api.common.GlobalExceptionHandler; +import java.nio.charset.StandardCharsets; +import java.util.List; +import javax.crypto.spec.SecretKeySpec; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; +import org.springframework.security.oauth2.core.OAuth2Error; +import org.springframework.security.oauth2.core.OAuth2TokenValidator; +import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; +import org.springframework.security.oauth2.jose.jws.MacAlgorithm; +import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtValidators; +import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import tools.jackson.databind.json.JsonMapper; + +/** + * Who may call what. Everything not listed as public needs a valid Supabase JWT, and + * anything not matched at all is denied, so a new endpoint is closed until someone opens it. + */ +@Configuration +@EnableMethodSecurity +public class SecurityConfig { + + /** Endpoints anyone may call without logging in. Kept in one place so the tests can check it. */ + public static final List PUBLIC_ENDPOINTS = List.of( + new String[] {"GET", "/api/health"}, + new String[] {"GET", "/api/events"}, + new String[] {"GET", "/api/links"}, + new String[] {"GET", "/api/degrees"}, + new String[] {"GET", "/api/degrees/{degreeId}/majors"}, + new String[] {"POST", "/api/members"}, + new String[] {"POST", "/api/events/{eventId}/rsvps"}, + new String[] {"POST", "/api/events/{eventId}/rsvps/bank-transfer"}, + new String[] {"POST", "/api/events/{eventId}/rsvps/checkout"}, + new String[] {"POST", "/api/contact"}, + new String[] {"POST", "/api/webhooks/stripe"}, + new String[] {"GET", "/api/files/public/{bucket}/**"}); + + @Bean + SecurityFilterChain api( + HttpSecurity http, + ProfileAuthenticationConverter converter, + RateLimitFilter rateLimit, + JsonMapper json) throws Exception { + http.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + // Bearer tokens in a header, no cookies: CSRF does not apply. + .csrf(c -> c.disable()) + .cors(c -> {}) + .httpBasic(b -> b.disable()) + .formLogin(f -> f.disable()) + .logout(l -> l.disable()) + .headers(h -> h + .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'none'; frame-ancestors 'none'")) + .referrerPolicy(r -> r.policy( + org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER))) + .authorizeHttpRequests(a -> { + for (String[] e : PUBLIC_ENDPOINTS) a.requestMatchers(HttpMethod.valueOf(e[0]), e[1]).permitAll(); + a.requestMatchers(HttpMethod.GET, "/internal/health").permitAll() + .requestMatchers(HttpMethod.GET, "/api/me").authenticated() + .requestMatchers("/api/admin/audit-log/**", "/api/admin/users/**").hasRole("SUPERUSER") + .requestMatchers("/api/admin/**").hasRole("ADMIN") + .anyRequest().denyAll(); + }) + .oauth2ResourceServer(o -> o + .jwt(j -> j.jwtAuthenticationConverter(converter)) + .authenticationEntryPoint((req, res, ex) -> writeProblem(res, json, HttpStatus.UNAUTHORIZED, "unauthenticated", "Please log in.")) + .accessDeniedHandler((req, res, ex) -> writeProblem(res, json, HttpStatus.FORBIDDEN, "forbidden", "You don't have access to this."))) + .exceptionHandling(e -> e + .authenticationEntryPoint((req, res, ex) -> writeProblem(res, json, HttpStatus.UNAUTHORIZED, "unauthenticated", "Please log in.")) + .accessDeniedHandler((req, res, ex) -> writeProblem(res, json, HttpStatus.FORBIDDEN, "forbidden", "You don't have access to this."))) + .addFilterBefore(rateLimit, AnonymousAuthenticationFilter.class); + return http.build(); + } + + private static void writeProblem(jakarta.servlet.http.HttpServletResponse res, JsonMapper json, HttpStatus status, String code, String detail) + throws java.io.IOException { + res.setStatus(status.value()); + res.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE); + res.getWriter().write(json.writeValueAsString(GlobalExceptionHandler.problem(status, code, detail))); + } + + /** + * Verifies Supabase access tokens. Projects on the legacy JWT secret sign with HS256; + * projects on the newer signing keys publish a JWKS. Either way the token must be issued + * by this project's Auth server, for the {@code authenticated} audience and role, which + * rules out the public anon key (also a JWT, but with role {@code anon}). + */ + @Bean + JwtDecoder jwtDecoder(DevsProperties props) { + String base = props.supabase().url().replaceAll("/+$", ""); + if (base.isBlank()) throw new IllegalStateException("SUPABASE_URL is not set"); + String issuer = base + "/auth/v1"; + + NimbusJwtDecoder decoder; + String secret = props.supabase().jwtSecret(); + if (secret != null && !secret.isBlank()) { + if (secret.length() < 32) throw new IllegalStateException("SUPABASE_JWT_SECRET is too short"); + decoder = NimbusJwtDecoder.withSecretKey(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")) + .macAlgorithm(MacAlgorithm.HS256) + .build(); + } else { + decoder = NimbusJwtDecoder.withJwkSetUri(issuer + "/.well-known/jwks.json") + .jwsAlgorithms(algs -> { + algs.add(SignatureAlgorithm.ES256); + algs.add(SignatureAlgorithm.RS256); + }) + .build(); + } + + OAuth2TokenValidator audienceAndRole = jwt -> { + boolean audienceOk = jwt.getAudience() != null && jwt.getAudience().contains("authenticated"); + boolean roleOk = "authenticated".equals(jwt.getClaimAsString("role")); + boolean subjectOk = jwt.getSubject() != null && jwt.getSubject().matches("[0-9a-fA-F-]{36}"); + if (audienceOk && roleOk && subjectOk) return OAuth2TokenValidatorResult.success(); + return OAuth2TokenValidatorResult.failure(new OAuth2Error("invalid_token", "Not a user access token", null)); + }; + decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefaultWithIssuer(issuer), audienceAndRole)); + return decoder; + } + + /** The rate limiter runs inside the security chain only, not a second time as a plain servlet filter. */ + @Bean + org.springframework.boot.web.servlet.FilterRegistrationBean rateLimitRegistration(RateLimitFilter f) { + var registration = new org.springframework.boot.web.servlet.FilterRegistrationBean<>(f); + registration.setEnabled(false); + return registration; + } + + @Bean + CorsConfigurationSource corsConfigurationSource(DevsProperties props) { + CorsConfiguration cors = new CorsConfiguration(); + cors.setAllowedOrigins(props.corsAllowedOrigins()); + cors.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE")); + cors.setAllowedHeaders(List.of("Authorization", "Content-Type")); + cors.setAllowCredentials(false); + cors.setMaxAge(600L); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/api/**", cors); + return source; + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/contact/ContactController.java b/apps/api/src/main/java/com/devsuoa/api/contact/ContactController.java new file mode 100644 index 0000000..1006424 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/contact/ContactController.java @@ -0,0 +1,61 @@ +package com.devsuoa.api.contact; + +import com.devsuoa.api.config.DevsProperties; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.util.HtmlUtils; + +/** + * The contact and sponsorship forms. The recipient, subject and layout are fixed here; the + * visitor only supplies their name, email and message, and all three are HTML-escaped. + */ +@RestController +public class ContactController { + + public record Message( + @NotNull @Pattern(regexp = "contact|sponsor") String kind, + @NotBlank @Size(max = 200) String name, + @NotBlank @Email @Size(max = 254) String email, + @NotBlank @Size(max = 5000) String message) {} + + private final EmailSender email; + private final String recipient; + + public ContactController(EmailSender email, DevsProperties props) { + this.email = email; + this.recipient = props.email().contactTo(); + } + + @PostMapping("/api/contact") + @ResponseStatus(HttpStatus.ACCEPTED) + void send(@Valid @RequestBody Message m) { + boolean sponsor = m.kind().equals("sponsor"); + String name = HtmlUtils.htmlEscape(m.name().trim()); + String from = HtmlUtils.htmlEscape(m.email().trim()); + String body = HtmlUtils.htmlEscape(m.message().trim()).replace("\n", "
"); + String subject = (sponsor ? "Sponsorship Inquiry from " : "Contact Form Submission from ") + oneLine(m.name()); + String html = """ +

%s

+

%s: %s

+

Email: %s

+

Message:

+

%s

+ """.formatted(sponsor ? "New Sponsorship Inquiry" : "New Contact Form Submission", + sponsor ? "Company" : "Name", name, from, body); + email.send(recipient, m.email().trim(), subject, html); + } + + /** Subjects are headers: no line breaks, so nothing can be smuggled into the mail headers. */ + private static String oneLine(String s) { + return s.replaceAll("[\\r\\n\\t]+", " ").trim(); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/contact/EmailSender.java b/apps/api/src/main/java/com/devsuoa/api/contact/EmailSender.java new file mode 100644 index 0000000..96e5c2b --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/contact/EmailSender.java @@ -0,0 +1,46 @@ +package com.devsuoa.api.contact; + +import com.devsuoa.api.config.DevsProperties; +import java.util.List; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClient; + +/** Sends mail through Resend, or only logs it when {@code devs.email.mode=log} (Docker dev, tests). */ +@Component +public class EmailSender { + + private static final Logger log = LoggerFactory.getLogger(EmailSender.class); + + private final DevsProperties.Email config; + private final RestClient http; + + public EmailSender(DevsProperties props, RestClient.Builder builder) { + this.config = props.email(); + this.http = builder.clone() + .baseUrl("https://api.resend.com") + .defaultHeader("Authorization", "Bearer " + (config.resendApiKey() == null ? "" : config.resendApiKey())) + .build(); + } + + public void send(String to, String replyTo, String subject, String html) { + if (!"resend".equals(config.mode())) { + log.info("Email (not sent, mode={}): to={} subject={}", config.mode(), to, subject); + return; + } + http.post() + .uri("/emails") + .contentType(MediaType.APPLICATION_JSON) + .body(Map.of( + "from", config.from(), + "to", List.of(to), + "reply_to", replyTo, + "subject", subject, + "html", html)) + .retrieve() + .toBodilessEntity(); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/events/EventForm.java b/apps/api/src/main/java/com/devsuoa/api/events/EventForm.java new file mode 100644 index 0000000..f6376d5 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/events/EventForm.java @@ -0,0 +1,45 @@ +package com.devsuoa.api.events; + +import jakarta.validation.constraints.DecimalMax; +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.Digits; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.Size; +import java.math.BigDecimal; +import java.time.LocalDate; +import tools.jackson.databind.JsonNode; + +/** An event as an admin creates or edits it. */ +public record EventForm( + @NotBlank @Size(max = 200) String title, + @Size(max = 10_000) String description, + @Size(max = 2000) String imageUrl, + @Size(max = 100) String tag, + @NotNull LocalDate eventDate, + @Size(max = 100) String eventTime, + @Size(max = 300) String location, + @Size(max = 2000) String registerUrl, + @NotNull Boolean isActive, + @Positive @Max(100_000) Integer maxAttendees, + @NotNull Boolean groupRsvpEnabled, + @Positive @Max(100) Integer groupRsvpMaxEmails, + @NotNull Boolean paymentEnabled, + @DecimalMin("0.00") @DecimalMax("100000.00") @Digits(integer = 6, fraction = 2) BigDecimal chargeAmount, + @NotNull Boolean bankTransferEnabled, + JsonNode rsvpQuestions) { + + /** Fills the gaps the old form left to database constraints, with readable errors instead. */ + EventForm normalised(String imageUrl, String registerUrl) { + return new EventForm(title.trim(), blankToNull(description), imageUrl, blankToNull(tag), eventDate, + blankToNull(eventTime), blankToNull(location), registerUrl, isActive, maxAttendees, groupRsvpEnabled, + groupRsvpEnabled ? groupRsvpMaxEmails : null, paymentEnabled, paymentEnabled ? chargeAmount : null, + paymentEnabled && bankTransferEnabled, rsvpQuestions); + } + + private static String blankToNull(String s) { + return s == null || s.isBlank() ? null : s.trim(); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/events/EventRepository.java b/apps/api/src/main/java/com/devsuoa/api/events/EventRepository.java new file mode 100644 index 0000000..d13f0d8 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/events/EventRepository.java @@ -0,0 +1,185 @@ +package com.devsuoa.api.events; + +import com.devsuoa.api.common.Json; +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Repository; +import tools.jackson.databind.JsonNode; + +@Repository +public class EventRepository { + + /** Every column. Only admin endpoints return this. */ + public record Event( + UUID id, + String title, + String description, + String imageUrl, + String tag, + LocalDate eventDate, + String eventTime, + String location, + String registerUrl, + boolean isActive, + OffsetDateTime createdAt, + Integer maxAttendees, + boolean groupRsvpEnabled, + Integer groupRsvpMaxEmails, + JsonNode rsvpQuestions, + boolean paymentEnabled, + BigDecimal chargeAmount, + boolean bankTransferEnabled, + String bankAccountName, + String bankAccountNumber) {} + + /** What visitors see. Leaves out internal fields such as the linked Google Sheet. */ + public record PublicEvent( + UUID id, + String title, + String description, + String imageUrl, + String tag, + LocalDate eventDate, + String eventTime, + String location, + String registerUrl, + Integer maxAttendees, + boolean groupRsvpEnabled, + Integer groupRsvpMaxEmails, + boolean paymentEnabled, + BigDecimal chargeAmount, + boolean bankTransferEnabled, + JsonNode rsvpQuestions, + boolean isActive) { + + static PublicEvent of(Event e) { + return new PublicEvent(e.id(), e.title(), e.description(), e.imageUrl(), e.tag(), e.eventDate(), e.eventTime(), + e.location(), e.registerUrl(), e.maxAttendees(), e.groupRsvpEnabled(), e.groupRsvpMaxEmails(), + e.paymentEnabled(), e.chargeAmount(), e.bankTransferEnabled(), e.rsvpQuestions(), e.isActive()); + } + } + + private static final String COLUMNS = """ + id, title, description, image_url, tag, event_date, event_time, location, register_url, + coalesce(is_active, false) as is_active, created_at, max_attendees, group_rsvp_enabled, + group_rsvp_max_emails, rsvp_questions::text as rsvp_questions, payment_enabled, charge_amount, + bank_transfer_enabled, bank_account_name, bank_account_number + """; + + private final JdbcClient jdbc; + private final Json json; + + public EventRepository(JdbcClient jdbc, Json json) { + this.jdbc = jdbc; + this.json = json; + } + + public List active() { + return jdbc.sql("select " + COLUMNS + " from public.events where is_active order by event_date asc") + .query(this::map) + .list(); + } + + public List all() { + return jdbc.sql("select " + COLUMNS + " from public.events order by event_date desc").query(this::map).list(); + } + + public Optional find(UUID id) { + return jdbc.sql("select " + COLUMNS + " from public.events where id = :id").param("id", id).query(this::map).optional(); + } + + /** Locks the event row for the rest of the transaction, so capacity checks can't race. */ + public Optional findForUpdate(UUID id) { + return jdbc.sql("select " + COLUMNS + " from public.events where id = :id for update") + .param("id", id) + .query(this::map) + .optional(); + } + + public Event insert(EventForm f, String questionsJson) { + return jdbc.sql(""" + insert into public.events (title, description, image_url, tag, event_date, event_time, location, + register_url, is_active, max_attendees, group_rsvp_enabled, group_rsvp_max_emails, rsvp_questions, + payment_enabled, charge_amount, bank_transfer_enabled, bank_account_name, bank_account_number) + values (:title, :description, :imageUrl, :tag, :eventDate, :eventTime, :location, + :registerUrl, :isActive, :maxAttendees, :groupRsvpEnabled, :groupRsvpMaxEmails, cast(:questions as jsonb), + :paymentEnabled, :chargeAmount, :bankTransferEnabled, null, null) + returning + """ + COLUMNS) + .params(params(f, questionsJson)) + .query(this::map) + .single(); + } + + public boolean update(UUID id, EventForm f, String questionsJson) { + return jdbc.sql(""" + update public.events set + title = :title, description = :description, image_url = :imageUrl, tag = :tag, + event_date = :eventDate, event_time = :eventTime, location = :location, register_url = :registerUrl, + is_active = :isActive, max_attendees = :maxAttendees, group_rsvp_enabled = :groupRsvpEnabled, + group_rsvp_max_emails = :groupRsvpMaxEmails, rsvp_questions = cast(:questions as jsonb), + payment_enabled = :paymentEnabled, charge_amount = :chargeAmount, + bank_transfer_enabled = :bankTransferEnabled, bank_account_name = null, bank_account_number = null + where id = :id + """) + .params(params(f, questionsJson)) + .param("id", id) + .update() == 1; + } + + private static java.util.Map params(EventForm f, String questionsJson) { + java.util.Map p = new java.util.HashMap<>(); + p.put("title", f.title()); + p.put("description", f.description()); + p.put("imageUrl", f.imageUrl()); + p.put("tag", f.tag()); + p.put("eventDate", f.eventDate()); + p.put("eventTime", f.eventTime()); + p.put("location", f.location()); + p.put("registerUrl", f.registerUrl()); + p.put("isActive", f.isActive()); + p.put("maxAttendees", f.maxAttendees()); + p.put("groupRsvpEnabled", f.groupRsvpEnabled()); + p.put("groupRsvpMaxEmails", f.groupRsvpMaxEmails()); + p.put("paymentEnabled", f.paymentEnabled()); + p.put("chargeAmount", f.chargeAmount()); + p.put("bankTransferEnabled", f.bankTransferEnabled()); + p.put("questions", questionsJson); + return p; + } + + public boolean delete(UUID id) { + return jdbc.sql("delete from public.events where id = :id").param("id", id).update() == 1; + } + + private Event map(ResultSet rs, int row) throws SQLException { + return new Event( + rs.getObject("id", UUID.class), + rs.getString("title"), + rs.getString("description"), + rs.getString("image_url"), + rs.getString("tag"), + rs.getObject("event_date", LocalDate.class), + rs.getString("event_time"), + rs.getString("location"), + rs.getString("register_url"), + rs.getBoolean("is_active"), + rs.getObject("created_at", OffsetDateTime.class), + (Integer) rs.getObject("max_attendees"), + rs.getBoolean("group_rsvp_enabled"), + (Integer) rs.getObject("group_rsvp_max_emails"), + json.parse(rs.getString("rsvp_questions")), + rs.getBoolean("payment_enabled"), + rs.getBigDecimal("charge_amount"), + rs.getBoolean("bank_transfer_enabled"), + rs.getString("bank_account_name"), + rs.getString("bank_account_number")); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/events/EventsController.java b/apps/api/src/main/java/com/devsuoa/api/events/EventsController.java new file mode 100644 index 0000000..f4f5545 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/events/EventsController.java @@ -0,0 +1,110 @@ +package com.devsuoa.api.events; + +import com.devsuoa.api.auth.ActorContext; +import com.devsuoa.api.common.ApiException; +import com.devsuoa.api.common.Json; +import com.devsuoa.api.common.Urls; +import com.devsuoa.api.events.EventRepository.Event; +import com.devsuoa.api.events.EventRepository.PublicEvent; +import com.devsuoa.api.rsvp.RsvpQuestions; +import com.devsuoa.api.storage.BlobStore; +import jakarta.validation.Valid; +import java.util.List; +import java.util.UUID; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class EventsController { + + private static final Logger log = LoggerFactory.getLogger(EventsController.class); + + private final EventRepository events; + private final ActorContext actor; + private final BlobStore store; + private final Json json; + private final TransactionTemplate tx; + + public EventsController(EventRepository events, ActorContext actor, BlobStore store, Json json, TransactionTemplate tx) { + this.events = events; + this.actor = actor; + this.store = store; + this.json = json; + this.tx = tx; + } + + /** Active events, oldest first. The site splits them into upcoming and past. */ + @GetMapping("/api/events") + List publicEvents() { + return events.active().stream().map(PublicEvent::of).toList(); + } + + @GetMapping("/api/admin/events") + List all() { + return events.all(); + } + + @PostMapping("/api/admin/events") + @ResponseStatus(HttpStatus.CREATED) + @Transactional + Event create(@Valid @RequestBody EventForm form) { + actor.bind(); + EventForm f = check(form); + return events.insert(f, questionsJson(f)); + } + + @PutMapping("/api/admin/events/{id}") + @Transactional + Event update(@PathVariable UUID id, @Valid @RequestBody EventForm form) { + actor.bind(); + EventForm f = check(form); + if (!events.update(id, f, questionsJson(f))) throw ApiException.notFound("Event"); + return events.find(id).orElseThrow(); + } + + @DeleteMapping("/api/admin/events/{id}") + @ResponseStatus(HttpStatus.NO_CONTENT) + void delete(@PathVariable UUID id) { + Event event = events.find(id).orElseThrow(() -> ApiException.notFound("Event")); + tx.executeWithoutResult(s -> { + actor.bind(); + if (!events.delete(id)) throw ApiException.notFound("Event"); + }); + // The row is gone; failing to tidy up the image shouldn't fail the request. + store.pathFromPublicUrl(BlobStore.EVENT_IMAGES, event.imageUrl()).ifPresent(path -> { + try { + store.delete(BlobStore.EVENT_IMAGES, path); + } catch (RuntimeException e) { + log.warn("Could not delete image {} for event {}", path, id, e); + } + }); + } + + private EventForm check(EventForm form) { + String image = Urls.requireWeb(form.imageUrl(), "image URL"); + String register = Urls.requireWeb(form.registerUrl(), "registration link"); + EventForm f = form.normalised(image, register); + if (f.groupRsvpEnabled() && f.groupRsvpMaxEmails() == null) { + throw ApiException.badRequest("group_size_required", "Set the largest group size allowed."); + } + if (f.paymentEnabled() && (f.chargeAmount() == null || f.chargeAmount().signum() <= 0)) { + throw ApiException.badRequest("charge_required", "Set the price for a paid event."); + } + return f; + } + + private String questionsJson(EventForm f) { + return json.write(RsvpQuestions.toJson(RsvpQuestions.parse(f.rsvpQuestions()))); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/links/LinksController.java b/apps/api/src/main/java/com/devsuoa/api/links/LinksController.java new file mode 100644 index 0000000..b4ff9a5 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/links/LinksController.java @@ -0,0 +1,198 @@ +package com.devsuoa.api.links; + +import com.devsuoa.api.auth.ActorContext; +import com.devsuoa.api.common.ApiException; +import com.devsuoa.api.common.Urls; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.format.DateTimeParseException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +/** The links page (link-in-bio style list) and its admin editor. */ +@RestController +public class LinksController { + + public record Link( + UUID id, + String title, + String url, + boolean isActive, + OffsetDateTime activeFrom, + OffsetDateTime activeTo, + int displayOrder, + boolean isSpacer, + String customIcon, + OffsetDateTime createdAt, + OffsetDateTime updatedAt) { + + /** Same rule the site used client-side: spacers follow is_active; links also need to be inside their date window. */ + boolean visibleAt(OffsetDateTime now) { + if (!isActive) return false; + if (isSpacer) return true; + if (activeFrom != null && now.isBefore(activeFrom)) return false; + return activeTo == null || !now.isAfter(activeTo); + } + } + + public record LinkForm( + @NotNull @Size(max = 200) String title, + @Size(max = 2000) String url, + @NotNull Boolean isActive, + @Size(max = 40) String activeFrom, + @Size(max = 40) String activeTo, + @Min(0) @Max(100_000) Integer displayOrder, + Boolean isSpacer, + @Size(max = 2000) String customIcon) {} + + public record Order(@NotNull @Size(max = 500) List ids) {} + + private static final Set LINK_SCHEMES = Set.of("http", "https", "mailto"); + private static final String COLUMNS = + "id, title, url, coalesce(is_active, false) as is_active, active_from, active_to, display_order, is_spacer, custom_icon, created_at, updated_at"; + + private final JdbcClient jdbc; + private final ActorContext actor; + + public LinksController(JdbcClient jdbc, ActorContext actor) { + this.jdbc = jdbc; + this.actor = actor; + } + + @GetMapping("/api/links") + List visible() { + OffsetDateTime now = OffsetDateTime.now(); + return all().stream().filter(l -> l.visibleAt(now)).toList(); + } + + @GetMapping("/api/admin/links") + List all() { + return jdbc.sql("select " + COLUMNS + " from public.links order by display_order asc, created_at desc") + .query(LinksController::map) + .list(); + } + + @PostMapping("/api/admin/links") + @ResponseStatus(HttpStatus.CREATED) + @Transactional + Link create(@Valid @RequestBody LinkForm form) { + actor.bind(); + Checked c = check(form); + Integer order = form.displayOrder() != null ? form.displayOrder() + : jdbc.sql("select coalesce(max(display_order) + 1, 0) from public.links").query(Integer.class).single(); + return jdbc.sql(""" + insert into public.links (title, url, is_active, active_from, active_to, display_order, is_spacer, custom_icon) + values (:title, :url, :active, cast(:from as timestamptz), cast(:to as timestamptz), :order, :spacer, :icon) + returning + """ + COLUMNS) + .param("title", c.title).param("url", c.url).param("active", form.isActive()) + .param("from", c.from).param("to", c.to).param("order", order) + .param("spacer", c.spacer).param("icon", c.icon) + .query(LinksController::map) + .single(); + } + + @PutMapping("/api/admin/links/{id}") + @Transactional + Link update(@PathVariable UUID id, @Valid @RequestBody LinkForm form) { + actor.bind(); + Checked c = check(form); + return jdbc.sql(""" + update public.links set title = :title, url = :url, is_active = :active, + active_from = cast(:from as timestamptz), active_to = cast(:to as timestamptz), + display_order = coalesce(:order, display_order), is_spacer = :spacer, custom_icon = :icon + where id = :id + returning + """ + COLUMNS) + .param("title", c.title).param("url", c.url).param("active", form.isActive()) + .param("from", c.from).param("to", c.to).param("order", form.displayOrder()) + .param("spacer", c.spacer).param("icon", c.icon).param("id", id) + .query(LinksController::map) + .optional() + .orElseThrow(() -> ApiException.notFound("Link")); + } + + @DeleteMapping("/api/admin/links/{id}") + @ResponseStatus(HttpStatus.NO_CONTENT) + @Transactional + void delete(@PathVariable UUID id) { + actor.bind(); + if (jdbc.sql("delete from public.links where id = :id").param("id", id).update() == 0) throw ApiException.notFound("Link"); + } + + /** Saves a new order in one transaction: display_order becomes each link's position in {@code ids}. */ + @PutMapping("/api/admin/links/order") + @ResponseStatus(HttpStatus.NO_CONTENT) + @Transactional + void reorder(@Valid @RequestBody Order order) { + actor.bind(); + if (new HashSet<>(order.ids()).size() != order.ids().size()) throw ApiException.badRequest("duplicate_ids", "Each link can appear once."); + for (int i = 0; i < order.ids().size(); i++) { + jdbc.sql("update public.links set display_order = :i where id = :id and display_order is distinct from :i") + .param("i", i).param("id", order.ids().get(i)) + .update(); + } + } + + private record Checked(String title, String url, String from, String to, boolean spacer, String icon) {} + + private static Checked check(LinkForm f) { + boolean spacer = Boolean.TRUE.equals(f.isSpacer()); + String url = spacer && (f.url() == null || f.url().isBlank()) ? "" : Urls.requireScheme(f.url(), "link", LINK_SCHEMES); + if (url == null) throw ApiException.badRequest("url_required", "Enter the link's address."); + if (!spacer && f.title().isBlank()) throw ApiException.badRequest("title_required", "Give the link a title."); + return new Checked(f.title().trim(), url, timestamp(f.activeFrom()), timestamp(f.activeTo()), spacer, + Urls.requireWeb(f.customIcon(), "icon URL")); + } + + /** Accepts what the admin form sends: an ISO timestamp, with or without a zone. */ + private static String timestamp(String s) { + if (s == null || s.isBlank()) return null; + try { + OffsetDateTime.parse(s); + return s; + } catch (DateTimeParseException e) { + try { + LocalDateTime.parse(s); + return s; + } catch (DateTimeParseException e2) { + throw ApiException.badRequest("invalid_date", "Dates must look like 2026-10-26T09:00."); + } + } + } + + private static Link map(ResultSet rs, int row) throws SQLException { + return new Link( + rs.getObject("id", UUID.class), + rs.getString("title"), + rs.getString("url"), + rs.getBoolean("is_active"), + rs.getObject("active_from", OffsetDateTime.class), + rs.getObject("active_to", OffsetDateTime.class), + rs.getInt("display_order"), + rs.getBoolean("is_spacer"), + rs.getString("custom_icon"), + rs.getObject("created_at", OffsetDateTime.class), + rs.getObject("updated_at", OffsetDateTime.class)); + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/marketing/MarketingController.java b/apps/api/src/main/java/com/devsuoa/api/marketing/MarketingController.java new file mode 100644 index 0000000..f270657 --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/marketing/MarketingController.java @@ -0,0 +1,185 @@ +package com.devsuoa.api.marketing; + +import com.devsuoa.api.auth.ActorContext; +import com.devsuoa.api.auth.Auth; +import com.devsuoa.api.auth.CurrentUser; +import com.devsuoa.api.common.ApiException; +import com.devsuoa.api.config.DevsProperties; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import java.security.SecureRandom; +import java.time.LocalDate; +import java.time.format.DateTimeParseException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestClient; + +/** + * Marketing requests from execs. One call saves the request, adds a task to the marketing + * team's board, and forwards it to the Google Sheet (whose Apps Script sends the emails). + * Replaces the browser-side insert, the create-marketing-task edge function and the + * browser's direct Apps Script call (whose URL was public in the JS bundle). + */ +@RestController +public class MarketingController { + + private static final Logger log = LoggerFactory.getLogger(MarketingController.class); + private static final SecureRandom RANDOM = new SecureRandom(); + + public record Request( + @NotNull @Pattern(regexp = "event|sponsorship") String postType, + @Size(max = 200) String eventName, + @Size(max = 20) String eventDate, + @Size(max = 100) String eventTime, + @Size(max = 300) String eventLocation, + @Size(max = 10_000) String eventDescription, + @Size(max = 10_000) String eventSuggestions, + @Size(max = 200) String sponsorName, + @Size(max = 20) String sponsorshipEmailDate, + @Size(max = 20) String sponsorshipPostDate, + @Size(max = 200) String sponsorshipEventName, + @Size(max = 5_000) String sponsorshipLinks, + @Size(max = 10_000) String sponsorshipDescription, + @Size(max = 10_000) String marketingDescription, + @Size(max = 10_000) String preWrittenCaptions) {} + + public record Result(UUID id, String taskId, boolean sheetUpdated) {} + + private final JdbcClient jdbc; + private final ActorContext actor; + private final TransactionTemplate tx; + private final RestClient http; + private final String appsScriptUrl; + + public MarketingController(JdbcClient jdbc, ActorContext actor, TransactionTemplate tx, DevsProperties props, + RestClient.Builder builder) { + this.jdbc = jdbc; + this.actor = actor; + this.tx = tx; + this.http = builder.clone().build(); + this.appsScriptUrl = props.marketing().appsScriptUrl(); + } + + @PostMapping("/api/admin/marketing-requests") + @ResponseStatus(HttpStatus.CREATED) + Result submit(@Valid @RequestBody Request r) { + CurrentUser me = Auth.require(); + boolean event = r.postType().equals("event"); + LocalDate eventDate = date(r.eventDate()); + LocalDate emailDate = date(r.sponsorshipEmailDate()); + LocalDate postDate = date(r.sponsorshipPostDate()); + + String title = event ? nonBlank(r.eventName(), "Event") : nonBlank(r.sponsorName(), "Sponsor"); + String taskId = "mkt-" + HexFormat.of().formatHex(randomBytes(6)); + + UUID id = tx.execute(s -> { + actor.bind(); + UUID requestId = jdbc.sql(""" + insert into public.marketing_requests (post_type, event_name, event_date, event_time, event_location, + event_description, event_suggestions, sponsor_name, sponsorship_email_date, sponsorship_post_date, + sponsorship_event_name, sponsorship_links, sponsorship_description, marketing_description, + pre_written_captions, created_by) + values (:postType, :eventName, :eventDate, :eventTime, :eventLocation, :eventDescription, :eventSuggestions, + :sponsorName, :emailDate, :postDate, :sponsorshipEventName, :sponsorshipLinks, :sponsorshipDescription, + :marketingDescription, :captions, :createdBy) + returning id + """) + .param("postType", r.postType()) + .param("eventName", event ? r.eventName() : null) + .param("eventDate", event ? eventDate : null) + .param("eventTime", event ? r.eventTime() : null) + .param("eventLocation", event ? r.eventLocation() : null) + .param("eventDescription", event ? r.eventDescription() : null) + .param("eventSuggestions", event ? r.eventSuggestions() : null) + .param("sponsorName", event ? null : r.sponsorName()) + .param("emailDate", event ? null : emailDate) + .param("postDate", event ? null : postDate) + .param("sponsorshipEventName", event ? null : r.sponsorshipEventName()) + .param("sponsorshipLinks", event ? null : r.sponsorshipLinks()) + .param("sponsorshipDescription", event ? null : r.sponsorshipDescription()) + .param("marketingDescription", r.marketingDescription()) + .param("captions", r.preWrittenCaptions()) + .param("createdBy", me.id()) + .query(UUID.class) + .single(); + + jdbc.sql(""" + insert into public.tasks (id, name, label, assignee, status, description, team, "order", archived, due_date) + values (:id, :name, :label, null, 'todo', :description, 'marketing', + (select coalesce(max("order") + 1, 0) from public.tasks where team = 'marketing' and status = 'todo'), + false, :due) + """) + .param("id", taskId) + .param("name", (event ? "Marketing: " : "Sponsor post: ") + title) + .param("label", event ? "event" : "sponsorship") + .param("description", "Requested by " + me.displayName() + ".\n\n" + nonBlank(r.marketingDescription(), "")) + .param("due", event ? eventDate : postDate) + .update(); + return requestId; + }); + + return new Result(id, taskId, forwardToSheet(r)); + } + + /** Best effort: the request is saved either way, and the response says whether the sheet got it. */ + private boolean forwardToSheet(Request r) { + if (appsScriptUrl == null || appsScriptUrl.isBlank()) return false; + // The Apps Script expects the same camelCase fields the browser used to send. + Map body = new LinkedHashMap<>(); + body.put("postType", r.postType()); + body.put("eventName", r.eventName()); + body.put("eventDate", r.eventDate()); + body.put("eventTime", r.eventTime()); + body.put("eventLocation", r.eventLocation()); + body.put("eventDescription", r.eventDescription()); + body.put("eventSuggestions", r.eventSuggestions()); + body.put("sponsorName", r.sponsorName()); + body.put("sponsorshipEmailDate", r.sponsorshipEmailDate()); + body.put("sponsorshipPostDate", r.sponsorshipPostDate()); + body.put("sponsorshipEventName", r.sponsorshipEventName()); + body.put("sponsorshipLinks", r.sponsorshipLinks()); + body.put("sponsorshipDescription", r.sponsorshipDescription()); + body.put("marketingDescription", r.marketingDescription()); + body.put("preWrittenCaptions", r.preWrittenCaptions()); + try { + http.post().uri(appsScriptUrl).contentType(MediaType.APPLICATION_JSON).body(body).retrieve().toBodilessEntity(); + return true; + } catch (RuntimeException e) { + log.warn("Could not forward marketing request to the Google Sheet", e); + return false; + } + } + + private static LocalDate date(String s) { + if (s == null || s.isBlank()) return null; + try { + return LocalDate.parse(s); + } catch (DateTimeParseException e) { + throw ApiException.badRequest("invalid_date", "Dates must look like 2026-10-26."); + } + } + + private static String nonBlank(String s, String fallback) { + return s == null || s.isBlank() ? fallback : s.trim(); + } + + private static byte[] randomBytes(int n) { + byte[] b = new byte[n]; + RANDOM.nextBytes(b); + return b; + } +} diff --git a/apps/api/src/main/java/com/devsuoa/api/members/DegreesController.java b/apps/api/src/main/java/com/devsuoa/api/members/DegreesController.java new file mode 100644 index 0000000..8fa4bab --- /dev/null +++ b/apps/api/src/main/java/com/devsuoa/api/members/DegreesController.java @@ -0,0 +1,41 @@ +package com.devsuoa.api.members; + +import java.util.List; +import java.util.UUID; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +/** Reference data for the join form: degrees and the majors each offers. */ +@RestController +public class DegreesController { + + public record Option(UUID id, String name) {} + + private final JdbcClient jdbc; + + public DegreesController(JdbcClient jdbc) { + this.jdbc = jdbc; + } + + @GetMapping("/api/degrees") + List