From 4d6d742991afecebb07d223a40bb97cd02028dc1 Mon Sep 17 00:00:00 2001 From: alxtr Date: Sun, 30 Aug 2026 17:52:19 +0000 Subject: [PATCH 01/14] first api draft --- .dockerignore | 6 +- .env.example | 22 +- .github/workflows/ci.yml | 18 +- .gitignore | 2 - Makefile | 5 +- README.md | 31 +- cmd/stickd/main.go | 11 +- cmd/stickd/main_test.go | 14 +- compose.idp.yaml | 19 - example.config.yaml | 21 +- go.mod | 4 +- go.sum | 4 +- internal/adapters/notification/smtp/smtp.go | 2 +- internal/adapters/notification/teams/teams.go | 2 +- .../adapters/notification/teams/teams_test.go | 2 +- internal/api/handler.go | 621 +++++++ internal/api/handler_test.go | 152 ++ internal/api/headers.go | 11 + internal/auth/jwt.go | 189 +++ internal/auth/jwt_test.go | 105 ++ internal/auth/oidc.go | 9 - internal/auth/session.go | 73 - internal/auth/session_test.go | 170 -- .../azure_app_configuration_provider_test.go | 16 +- internal/config/config.go | 8 +- internal/config/config_test.go | 194 +-- internal/config/environment_provider.go | 15 +- internal/config/normalize.go | 45 +- internal/config/yaml_provider.go | 28 +- internal/web/auth/handler.go | 315 ---- internal/web/auth/oidc_test.go | 710 -------- internal/web/auth/routes.go | 14 - internal/web/content/assets/styles.css | 466 ------ internal/web/content/content.go | 61 - internal/web/content/content_test.go | 28 - internal/web/content/routes.go | 19 - internal/web/content/templates/base.html | 16 - .../content/templates/components/alert.html | 2 - .../templates/components/field-error.html | 2 - .../templates/components/pagination.html | 11 - .../components/stick-action-form.html | 9 - .../content/templates/components/topbar.html | 13 - internal/web/content/templates/dashboard.html | 17 - internal/web/content/templates/detail.html | 16 - internal/web/content/templates/error.html | 16 - internal/web/content/templates/new-stick.html | 16 - .../partials/dashboard/archived-sticks.html | 16 - .../partials/dashboard/stick-cards.html | 70 - .../partials/detail/admin-controls.html | 19 - .../templates/partials/detail/history.html | 19 - .../partials/detail/stick-header.html | 13 - .../partials/detail/stick-state.html | 38 - .../partials/new-stick/create-form.html | 16 - internal/web/dashboard/handler.go | 82 - internal/web/dashboard/routes.go | 12 - internal/web/health/handler.go | 4 +- internal/web/httpx/middleware.go | 4 +- internal/web/httpx/middleware_test.go | 23 +- internal/web/httpx/router.go | 6 - internal/web/httpx/url.go | 37 - internal/web/httpx/url_test.go | 57 +- internal/web/render/render.go | 103 -- internal/web/render/render_test.go | 162 -- internal/web/security/auth.go | 35 - internal/web/security/auth_test.go | 173 -- internal/web/security/csrf.go | 111 -- internal/web/security/csrf_test.go | 85 - internal/web/security/headers.go | 16 - internal/web/security/headers_test.go | 36 - internal/web/security/session.go | 8 - internal/web/server.go | 75 +- internal/web/server_test.go | 1490 ----------------- internal/web/sticks/form.go | 16 - internal/web/sticks/form_test.go | 26 - internal/web/sticks/handler.go | 201 --- internal/web/sticks/mutations.go | 253 --- internal/web/sticks/pagination.go | 59 - internal/web/sticks/pagination_test.go | 35 - internal/web/sticks/path.go | 28 - internal/web/sticks/path_test.go | 42 - internal/web/sticks/routes.go | 23 - internal/web/views/views.go | 564 ------- internal/web/views/views_test.go | 183 -- package-lock.json | 76 - package.json | 10 - playwright.config.js | 18 - test/browser/smoke.spec.js | 561 ------- test/e2e/stickd_test.go | 496 ------ test/integration/webui_csrf_test.go | 76 - test/integration/webui_form_test.go | 105 -- test/integration/webui_mutations_test.go | 468 ------ test/integration/webui_test_helpers_test.go | 116 -- 92 files changed, 1285 insertions(+), 8311 deletions(-) delete mode 100644 compose.idp.yaml create mode 100644 internal/api/handler.go create mode 100644 internal/api/handler_test.go create mode 100644 internal/api/headers.go create mode 100644 internal/auth/jwt.go create mode 100644 internal/auth/jwt_test.go delete mode 100644 internal/auth/oidc.go delete mode 100644 internal/auth/session.go delete mode 100644 internal/auth/session_test.go delete mode 100644 internal/web/auth/handler.go delete mode 100644 internal/web/auth/oidc_test.go delete mode 100644 internal/web/auth/routes.go delete mode 100644 internal/web/content/assets/styles.css delete mode 100644 internal/web/content/content.go delete mode 100644 internal/web/content/content_test.go delete mode 100644 internal/web/content/routes.go delete mode 100644 internal/web/content/templates/base.html delete mode 100644 internal/web/content/templates/components/alert.html delete mode 100644 internal/web/content/templates/components/field-error.html delete mode 100644 internal/web/content/templates/components/pagination.html delete mode 100644 internal/web/content/templates/components/stick-action-form.html delete mode 100644 internal/web/content/templates/components/topbar.html delete mode 100644 internal/web/content/templates/dashboard.html delete mode 100644 internal/web/content/templates/detail.html delete mode 100644 internal/web/content/templates/error.html delete mode 100644 internal/web/content/templates/new-stick.html delete mode 100644 internal/web/content/templates/partials/dashboard/archived-sticks.html delete mode 100644 internal/web/content/templates/partials/dashboard/stick-cards.html delete mode 100644 internal/web/content/templates/partials/detail/admin-controls.html delete mode 100644 internal/web/content/templates/partials/detail/history.html delete mode 100644 internal/web/content/templates/partials/detail/stick-header.html delete mode 100644 internal/web/content/templates/partials/detail/stick-state.html delete mode 100644 internal/web/content/templates/partials/new-stick/create-form.html delete mode 100644 internal/web/dashboard/handler.go delete mode 100644 internal/web/dashboard/routes.go delete mode 100644 internal/web/render/render.go delete mode 100644 internal/web/render/render_test.go delete mode 100644 internal/web/security/auth.go delete mode 100644 internal/web/security/auth_test.go delete mode 100644 internal/web/security/csrf.go delete mode 100644 internal/web/security/csrf_test.go delete mode 100644 internal/web/security/headers.go delete mode 100644 internal/web/security/headers_test.go delete mode 100644 internal/web/security/session.go delete mode 100644 internal/web/server_test.go delete mode 100644 internal/web/sticks/form.go delete mode 100644 internal/web/sticks/form_test.go delete mode 100644 internal/web/sticks/handler.go delete mode 100644 internal/web/sticks/mutations.go delete mode 100644 internal/web/sticks/pagination.go delete mode 100644 internal/web/sticks/pagination_test.go delete mode 100644 internal/web/sticks/path.go delete mode 100644 internal/web/sticks/path_test.go delete mode 100644 internal/web/sticks/routes.go delete mode 100644 internal/web/views/views.go delete mode 100644 internal/web/views/views_test.go delete mode 100644 package-lock.json delete mode 100644 package.json delete mode 100644 playwright.config.js delete mode 100644 test/browser/smoke.spec.js delete mode 100644 test/e2e/stickd_test.go delete mode 100644 test/integration/webui_csrf_test.go delete mode 100644 test/integration/webui_form_test.go delete mode 100644 test/integration/webui_mutations_test.go delete mode 100644 test/integration/webui_test_helpers_test.go diff --git a/.dockerignore b/.dockerignore index 2c72b14..2d31cb0 100644 --- a/.dockerignore +++ b/.dockerignore @@ -17,10 +17,9 @@ config.* *secret* *token* -# Compose and local IDP configuration +# Compose and local configuration docker-compose*.yaml docker-compose*.yml -local-idp.* # Runtime databases and application data data/ @@ -36,9 +35,6 @@ bin/ build/ dist/ coverage/ -node_modules/ -test-results/ -playwright-report/ *.exe *.dll *.so diff --git a/.env.example b/.env.example index 54d00a3..53236c9 100644 --- a/.env.example +++ b/.env.example @@ -1,29 +1,21 @@ # Copy this file to .env and replace the required values. # Non-empty STICK_* values override values from earlier configuration providers. -# The callback URL for the OIDC client is /auth/callback. +# The API is available below /api/v1. # Required application settings. A filesystem path selects SQLite; # postgres://, postgresql://, mongodb://, or mongodb+srv:// selects the # corresponding database backend. MongoDB must use a replica set or mongos. STICK_DATABASE=/data/stick.db -# Public URL used for links and OIDC redirects. HTTPS is required except for -# loopback addresses used during local development. Include the mount path, if any. +# Optional public URL used for notification links and the application mount path. +# Defaults to http://localhost. HTTPS is required for non-local URLs. STICK_SERVER_PUBLIC_URL=http://localhost:8080 # Address to bind (default: :8080). STICK_SERVER_LISTEN_ADDR=:8080 -# OIDC provider settings. Any compliant provider can be used. -STICK_AUTH_OIDC_ISSUER=https://accounts.google.com -STICK_AUTH_OIDC_CLIENT_ID=your-client-id -STICK_AUTH_OIDC_CLIENT_SECRET=your-client-secret -# Use at least 32 random bytes; generate one with: openssl rand -hex 32 -STICK_AUTH_SESSION_SECRET=replace-with-at-least-32-random-bytes - -# Optional settings for the local Keycloak instance in compose.idp.yaml. -# Set IDP_ADMIN_PASSWORD before starting that Compose override. -# STICK_IDP_PUBLIC_URL=http://localhost:8081/idp -# IDP_ADMIN_USERNAME=admin -# IDP_ADMIN_PASSWORD=replace-with-a-random-password +# External JWT validation settings. +STICK_AUTH_IDP_ENDPOINT=https://accounts.google.com +STICK_AUTH_AUDIENCE=your-api-audience +STICK_AUTH_SCOPE=your-required-scope # Optional comma-separated administrator list. # STICK_AUTH_ADMIN_EMAILS=alice@example.com,bob@example.com diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 44b2569..14943b4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,25 +70,9 @@ jobs: vuln-type: os,library severity: CRITICAL,HIGH - browser: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v5 - - uses: actions/setup-go@v6 - with: - go-version-file: go.mod - cache: true - - uses: actions/setup-node@v5 - with: - node-version: 24 - cache: npm - - run: npm ci - - run: npx playwright install --with-deps --only-shell chromium - - run: npm run test:browser - publish-image: if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/')) - needs: [test, race, lint, analysis, image, browser] + needs: [test, race, lint, analysis, image] runs-on: ubuntu-latest permissions: contents: read diff --git a/.gitignore b/.gitignore index 9d75bba..a798571 100644 --- a/.gitignore +++ b/.gitignore @@ -35,5 +35,3 @@ data/ config.yaml .env /stickd -node_modules/ -test-results/ \ No newline at end of file diff --git a/Makefile b/Makefile index 9156d08..f97c323 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ BUILD_DATE ?= unknown LDFLAGS := -s -w -X main.commit=$(COMMIT) -X main.buildDate=$(BUILD_DATE) GO_FILES := $(shell find . -type d \( -name .git -o -name data -o -name node_modules -o -name vendor \) -prune -o -type f -name '*.go' -print) -.PHONY: build fmt verify-format test test-integration test-e2e test-race vet lint govulncheck image check run clean +.PHONY: build fmt verify-format test test-integration test-race vet lint govulncheck image check run clean build: $(GOENV) CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o $(BINARY) ./cmd/stickd @@ -29,9 +29,6 @@ test: test-integration: $(GOENV) CGO_ENABLED=0 go test -count=1 ./test/integration -test-e2e: - $(GOENV) CGO_ENABLED=0 go test -count=1 ./test/e2e - test-race: $(GOENV) go test -race $(TEST_FLAGS) ./... diff --git a/README.md b/README.md index c161240..7ba89e4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,8 @@ Stick is a small, self-hosted coordination service for shared operational resources. Users claim a stick with a reason, release it when finished, and can subscribe to release notifications. -- Uses OIDC for login. +- Provides a JSON REST API with bearer-token authentication and optimistic + concurrency using ETags. - Supports different storage backends: - SQLite (default) - PostgreSQL @@ -29,16 +30,15 @@ Copy the example environment file: cp .env.example .env ``` -Edit `.env` and set the OIDC values, a random session secret, and the public URL. HTTPS is required for non-local deployments. - -Register `/auth/callback` as the OIDC client's redirect URI. +Edit `.env` and set the identity-provider endpoint and expected audience and +scope. The public URL is optional; HTTPS is required for non-local URLs. ```sh -openssl rand -hex 32 # use the result for STICK_AUTH_SESSION_SECRET docker compose up -d --build ``` -Stick is available at `STICK_SERVER_PUBLIC_URL`. The Compose file binds it to loopback, so put it behind a TLS reverse proxy for remote access. +The API is available at `STICK_SERVER_PUBLIC_URL/api/v1`. The Compose file +binds it to loopback, so put it behind a TLS reverse proxy for remote access. ### Kubernetes @@ -46,7 +46,7 @@ Create and edit the application configuration. Keep this file private because it ```sh cp example.config.yaml config.yaml -# edit config.yaml and set a random session_secret +# edit config.yaml and set the API authentication values kubectl create namespace stick kubectl -n stick create secret generic stick-config --from-file=config.yaml=./config.yaml ``` @@ -59,7 +59,8 @@ kubectl apply -f example.kubernetes.yaml This creates a single-replica Deployment, Service, and persistent volume claim. -Expose the Service through an Ingress or Gateway, use its HTTPS URL as `STICK_SERVER_PUBLIC_URL`, and register `/auth/callback` with the OIDC provider. +Expose the Service through an Ingress or Gateway, and use its HTTPS URL as +`STICK_SERVER_PUBLIC_URL`. If the application is mounted under a path, include that path in the probe URLs as well. @@ -104,7 +105,7 @@ When Azure is the only structured source, omit `-config`; when combining it with a file, use `STICK_CONFIG_PROVIDERS=yaml,azure-app-config,environment`. Use slash-separated keys such as `stick/database`, -`stick/server/public_url`, and `stick/auth/oidc/issuer`. Notification lists +`stick/server/public_url`, and `stick/auth/idp_endpoint`. Notification lists should be stored as JSON values with the `application/json` content type. The hierarchy separator is configurable (supported values include `/`, `.`, `:` and `__`) and defaults to `/`. @@ -130,10 +131,10 @@ make check make image ``` -The `compose.idp.yaml` override also starts Keycloak for local OIDC development. - -Set `IDP_ADMIN_PASSWORD` in `.env`, configure Keycloak as your OIDC provider, and run it with: +Send an external JWT in the `Authorization: Bearer ` header. Resource +updates require the current `If-Match` ETag; reads return an ETag and support +`If-None-Match`. -```sh -docker compose -f compose.yaml -f compose.idp.yaml up -d --build -``` +The API provides stick listing, creation, rename, archive/unarchive, claim, +release, history, and notification subscription endpoints below +`/api/v1`. diff --git a/cmd/stickd/main.go b/cmd/stickd/main.go index f0101b3..8b4b0f1 100644 --- a/cmd/stickd/main.go +++ b/cmd/stickd/main.go @@ -21,6 +21,7 @@ import ( "stick/internal/adapters/persistence/postgres" "stick/internal/adapters/persistence/sqlite" "stick/internal/application" + "stick/internal/auth" "stick/internal/config" "stick/internal/outbox" "stick/internal/web" @@ -87,20 +88,18 @@ func mainContext(parent context.Context, args []string) (err error) { }() service := application.NewService(store) - webRunner, err := web.NewRunner(service, store, web.Options{ + serverRunner, err := web.NewRunner(service, store, web.Options{ PublicURL: cfg.Server.PublicURL, ListenAddr: cfg.Server.ListenAddr, - OIDC: cfg.Auth.OIDC, - SessionSecret: cfg.Auth.SessionSecret, + JWT: auth.JWTConfig{Endpoint: cfg.Auth.IDPEndpoint, Audience: cfg.Auth.Audience, Scope: cfg.Auth.Scope}, AdminEmails: cfg.Auth.AdminEmails, - Timezone: cfg.Timezone, NotificationsEnabled: notifier != nil, }) if err != nil { - return fmt.Errorf("web: %w", err) + return fmt.Errorf("HTTP server: %w", err) } - components := []application.Component{webRunner} + components := []application.Component{serverRunner} if notifier != nil { components = append(components, outbox.NewWorker(store, notifier, outbox.WorkerOptions{ BaseURL: cfg.Server.PublicURL.String(), diff --git a/cmd/stickd/main_test.go b/cmd/stickd/main_test.go index edfc615..7bd6e6d 100644 --- a/cmd/stickd/main_test.go +++ b/cmd/stickd/main_test.go @@ -18,12 +18,11 @@ import ( func TestMainContextStopsOnCanceledParent(t *testing.T) { t.Setenv("STICK_DATABASE", filepath.Join(t.TempDir(), "stick.db")) - t.Setenv("STICK_AUTH_OIDC_ISSUER", "https://accounts.google.com") - t.Setenv("STICK_AUTH_OIDC_CLIENT_ID", "client-id") - t.Setenv("STICK_AUTH_OIDC_CLIENT_SECRET", "client-secret") + t.Setenv("STICK_AUTH_IDP_ENDPOINT", "https://accounts.google.com") + t.Setenv("STICK_AUTH_AUDIENCE", "stick-api") + t.Setenv("STICK_AUTH_SCOPE", "stick:use") t.Setenv("STICK_SERVER_PUBLIC_URL", "http://localhost:8080") t.Setenv("STICK_SERVER_LISTEN_ADDR", "127.0.0.1:0") - t.Setenv("STICK_AUTH_SESSION_SECRET", "0123456789abcdef0123456789abcdef") ctx, cancel := context.WithCancel(context.Background()) cancel() @@ -133,12 +132,11 @@ func TestBuildConfigProvidersRejectsUnknownProvider(t *testing.T) { func setMinimalRuntimeEnv(t *testing.T, databasePath string) { t.Helper() t.Setenv("STICK_DATABASE", databasePath) - t.Setenv("STICK_AUTH_OIDC_ISSUER", "https://accounts.google.com") - t.Setenv("STICK_AUTH_OIDC_CLIENT_ID", "client-id") - t.Setenv("STICK_AUTH_OIDC_CLIENT_SECRET", "client-secret") + t.Setenv("STICK_AUTH_IDP_ENDPOINT", "https://accounts.google.com") + t.Setenv("STICK_AUTH_AUDIENCE", "stick-api") + t.Setenv("STICK_AUTH_SCOPE", "stick:use") t.Setenv("STICK_SERVER_PUBLIC_URL", "http://localhost:8080") t.Setenv("STICK_SERVER_LISTEN_ADDR", "127.0.0.1:0") - t.Setenv("STICK_AUTH_SESSION_SECRET", "0123456789abcdef0123456789abcdef") } func TestBuildNotifierWithNoBackendsSucceeds(t *testing.T) { diff --git a/compose.idp.yaml b/compose.idp.yaml deleted file mode 100644 index 1529997..0000000 --- a/compose.idp.yaml +++ /dev/null @@ -1,19 +0,0 @@ -services: - keycloak: - image: quay.io/keycloak/keycloak:26.7.2 - command: - - start-dev - ports: - - "127.0.0.1:8081:8080" - environment: - KC_HTTP_ENABLED: "true" - KC_HTTP_RELATIVE_PATH: /idp - KC_HOSTNAME: ${STICK_IDP_PUBLIC_URL:-http://localhost:8081/idp} - KC_PROXY_HEADERS: xforwarded - KC_BOOTSTRAP_ADMIN_USERNAME: ${IDP_ADMIN_USERNAME:-admin} - KC_BOOTSTRAP_ADMIN_PASSWORD: ${IDP_ADMIN_PASSWORD:?Set IDP_ADMIN_PASSWORD in .env} - volumes: - - keycloak-data:/opt/keycloak/data - -volumes: - keycloak-data: diff --git a/example.config.yaml b/example.config.yaml index 83937b6..9e631be 100644 --- a/example.config.yaml +++ b/example.config.yaml @@ -2,7 +2,7 @@ # Copy this file to config.yaml and replace the required values. # Non-empty STICK_* environment variables override values from earlier # providers. The provider chain itself is selected with STICK_CONFIG_PROVIDERS. -# The OIDC callback URL is /auth/callback. +# The API is available below /api/v1. # Required: a filesystem path selects SQLite; a postgres://, postgresql://, # mongodb://, or mongodb+srv:// URL selects the backend automatically. @@ -12,22 +12,17 @@ database: /data/stick.db # database: mongodb://stick:password@mongo.example.com:27017/stick?replicaSet=rs0 server: - # Public URL used for links, cookies, redirects, and health probes. HTTPS is - # required except for loopback addresses used during local development. - # Include the optional application mount path, if one is used. + # Optional public URL used for notification links and the application mount + # path. Defaults to http://localhost. HTTPS is required for non-local URLs. public_url: http://localhost:8080 # Address to bind (default: :8080). # listen_addr: :8080 auth: - oidc: - # Any compliant provider works (for example, Google, Keycloak, or Authentik). - issuer: https://accounts.google.com - client_id: your-client-id - client_secret: your-client-secret - # Signs browser session cookies. Use at least 32 random bytes. Generate one - # with: openssl rand -hex 32 - session_secret: replace-with-at-least-32-random-bytes + # Identity-provider issuer used to discover signing keys for external bearer JWTs. + idp_endpoint: https://accounts.google.com + audience: your-api-audience + scope: your-required-scope # Admin email addresses are compared case-insensitively. # admin_emails: # - alice@example.com @@ -59,7 +54,7 @@ auth: # {{.StickName}} was held by {{.HolderEmail}} for {{.Duration}}. # Released at {{.ReleasedAt}} # -# → Claim it now: {{.BaseURL}}/sticks/{{.StickID}} +# → Claim it now: {{.BaseURL}}/api/v1/sticks/{{.StickID}} # You can also configure a webhook alongside SMTP: # notifications: diff --git a/go.mod b/go.mod index 79f497e..8fca41f 100644 --- a/go.mod +++ b/go.mod @@ -8,12 +8,10 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 github.com/Azure/azure-sdk-for-go/sdk/data/azappconfig/v2 v2.1.0 github.com/coreos/go-oidc/v3 v3.17.0 - github.com/golang-jwt/jwt/v5 v5.3.1 github.com/jackc/pgx/v5 v5.10.0 github.com/testcontainers/testcontainers-go/modules/mongodb v0.44.0 github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 go.mongodb.org/mongo-driver v1.17.9 - golang.org/x/oauth2 v0.36.0 gopkg.in/yaml.v3 v3.0.1 modernc.org/sqlite v1.48.0 ) @@ -45,6 +43,7 @@ require ( github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.3.0 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect + github.com/golang-jwt/jwt/v5 v5.3.0 // indirect github.com/golang/snappy v1.0.0 // indirect github.com/google/uuid v1.6.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect @@ -91,6 +90,7 @@ require ( go.opentelemetry.io/otel/trace v1.44.0 // indirect golang.org/x/crypto v0.56.0 // indirect golang.org/x/net v0.57.0 // indirect + golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sync v0.22.0 // indirect golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.41.0 // indirect diff --git a/go.sum b/go.sum index 6e54fa8..d7002be 100644 --- a/go.sum +++ b/go.sum @@ -71,8 +71,8 @@ github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= -github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= -github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= +github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs= github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= diff --git a/internal/adapters/notification/smtp/smtp.go b/internal/adapters/notification/smtp/smtp.go index ed8bf7e..9ce3852 100644 --- a/internal/adapters/notification/smtp/smtp.go +++ b/internal/adapters/notification/smtp/smtp.go @@ -27,7 +27,7 @@ The stick you were waiting for just dropped. {{.StickName}} was held by {{.HolderEmail}} for {{.Duration}}. Released at {{.ReleasedAt}} -→ Claim it now: {{.BaseURL}}/sticks/{{.StickID}}` +→ Claim it now: {{.BaseURL}}/api/v1/sticks/{{.StickID}}` const ( // TLSModeStartTLS upgrades a plaintext SMTP connection before sending diff --git a/internal/adapters/notification/teams/teams.go b/internal/adapters/notification/teams/teams.go index ce19b82..d1b0594 100644 --- a/internal/adapters/notification/teams/teams.go +++ b/internal/adapters/notification/teams/teams.go @@ -107,7 +107,7 @@ func (n *Notifier) Notify(ctx context.Context, notification application.Notifica Name: "Claim it now", Targets: []Target{{ OS: "default", - URI: strings.TrimRight(notification.BaseURL, "/") + "/sticks/" + url.PathEscape(notification.StickID), + URI: strings.TrimRight(notification.BaseURL, "/") + "/api/v1/sticks/" + url.PathEscape(notification.StickID), }}, }} } diff --git a/internal/adapters/notification/teams/teams_test.go b/internal/adapters/notification/teams/teams_test.go index f7e5152..e0448c8 100644 --- a/internal/adapters/notification/teams/teams_test.go +++ b/internal/adapters/notification/teams/teams_test.go @@ -68,7 +68,7 @@ func TestTeamsNotifierPostsMessageCard(t *testing.T) { } actions := received["potentialAction"].([]any) target := actions[0].(map[string]any)["targets"].([]any)[0].(map[string]any) - if target["uri"] != "https://stick.example.com/stick/sticks/prod%2Fdeploy" { + if target["uri"] != "https://stick.example.com/stick/api/v1/sticks/prod%2Fdeploy" { t.Errorf("claim URI = %v", target["uri"]) } } diff --git a/internal/api/handler.go b/internal/api/handler.go new file mode 100644 index 0000000..585da5c --- /dev/null +++ b/internal/api/handler.go @@ -0,0 +1,621 @@ +// Package api provides the JSON REST API for Stick. +package api + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net/http" + "strconv" + "strings" + "time" + + "stick/internal/application" + "stick/internal/auth" + domain "stick/internal/core" + "stick/internal/publicurl" + "stick/internal/web/httpx" +) + +const ( + apiPrefix = "/api/v1" + maxJSONBodyBytes = 1 << 20 + defaultHistoryLimit = 20 + maxHistoryLimit = 100 + maxHistoryOffset = 100_000 +) + +// Handler serves the Stick REST API. +type Handler struct { + service *application.Service + validator TokenValidator + admins map[string]struct{} + publicURL publicurl.URL + notificationsEnabled bool +} + +// TokenValidator authenticates one external bearer token. +type TokenValidator interface { + Validate(context.Context, string) (domain.Identity, error) +} + +// New returns an API handler. +func New( + service *application.Service, + validator TokenValidator, + adminEmails []string, + publicURL publicurl.URL, + notificationsEnabled bool, +) *Handler { + return &Handler{ + service: service, + validator: validator, + admins: auth.AdminSet(adminEmails), + publicURL: publicURL, + notificationsEnabled: notificationsEnabled, + } +} + +// Register adds all API routes to router. Authentication is applied to the +// complete API route family; health probes remain unauthenticated. +func Register(router *httpx.Router, handler *Handler) { + protected := router.With(handler.authenticate) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks", handler.listSticks) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks", handler.createStick) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/archived", handler.listArchivedSticks) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}", handler.getStick) + protected.HandleFunc(http.MethodPatch, apiPrefix+"/sticks/{id}", handler.renameStick) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}/history", handler.history) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/claim", handler.claimStick) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/release", handler.releaseStick) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/archive", handler.archiveStick) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/unarchive", handler.unarchiveStick) + if handler.notificationsEnabled { + protected.HandleFunc(http.MethodPut, apiPrefix+"/sticks/{id}/subscription", handler.subscribe) + protected.HandleFunc(http.MethodDelete, apiPrefix+"/sticks/{id}/subscription", handler.unsubscribe) + protected.HandleFunc(http.MethodGet, apiPrefix+"/subscriptions", handler.subscriptions) + } +} + +// NotFound writes the JSON response used for unknown API routes. +func NotFound(w http.ResponseWriter, _ *http.Request) { + writeError(w, http.StatusNotFound, "not found") +} + +func (h *Handler) authenticate(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + parts := strings.Fields(r.Header.Get("Authorization")) + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { + unauthorized(w) + return + } + if h.validator == nil { + writeError(w, http.StatusInternalServerError, "internal server error") + return + } + identity, err := h.validator.Validate(r.Context(), parts[1]) + if err != nil { + unauthorized(w) + return + } + identity = auth.WithAdminStatus(identity, h.admins) + next.ServeHTTP(w, r.WithContext(auth.WithIdentity(r.Context(), identity))) + }) +} + +func (h *Handler) listSticks(w http.ResponseWriter, r *http.Request) { + sticks, err := h.service.ListSticks(r.Context()) + if err != nil { + internalError(w, r, "list sticks", err) + return + } + writeCollection(w, r, sticksToJSON(sticks)) +} + +func (h *Handler) listArchivedSticks(w http.ResponseWriter, r *http.Request) { + identity := auth.IdentityFromContext(r.Context()) + if !identity.IsAdmin { + writeError(w, http.StatusForbidden, "forbidden") + return + } + sticks, err := h.service.ListArchivedSticks(r.Context(), identity) + if err != nil { + handleError(w, r, "list archived sticks", err) + return + } + writeCollection(w, r, sticksToJSON(sticks)) +} + +func (h *Handler) getStick(w http.ResponseWriter, r *http.Request) { + stick, err := h.service.GetStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id")) + if err != nil { + handleError(w, r, "get stick", err) + return + } + setETag(w, stick.Version) + if ifNoneMatch(headerValue(r, "If-None-Match"), etag(stick.Version)) { + notModified(w) + return + } + writeJSON(w, http.StatusOK, stickToJSON(stick)) +} + +func (h *Handler) createStick(w http.ResponseWriter, r *http.Request) { + if !auth.IdentityFromContext(r.Context()).IsAdmin { + writeError(w, http.StatusForbidden, "forbidden") + return + } + var request struct { + Name string `json:"name"` + } + if !decodeJSON(w, r, &request) { + return + } + stick, err := h.service.CreateStick(r.Context(), auth.IdentityFromContext(r.Context()), request.Name) + if err != nil { + handleError(w, r, "create stick", err) + return + } + setETag(w, stick.Version) + w.Header().Set("Location", httpx.Absolute(h.publicURL, apiPrefix+"/sticks/"+stick.ID)) + writeJSON(w, http.StatusCreated, stickToJSON(stick)) +} + +func (h *Handler) renameStick(w http.ResponseWriter, r *http.Request) { + if !auth.IdentityFromContext(r.Context()).IsAdmin { + writeError(w, http.StatusForbidden, "forbidden") + return + } + var request struct { + Name string `json:"name"` + } + if !decodeJSON(w, r, &request) { + return + } + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + stick, err := h.service.RenameStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), request.Name, version) + if err != nil { + handleError(w, r, "rename stick", err) + return + } + writeStick(w, stick) +} + +func (h *Handler) archiveStick(w http.ResponseWriter, r *http.Request) { + if !auth.IdentityFromContext(r.Context()).IsAdmin { + writeError(w, http.StatusForbidden, "forbidden") + return + } + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + stick, err := h.service.ArchiveStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version) + if err != nil { + handleError(w, r, "archive stick", err) + return + } + writeStick(w, stick) +} + +func (h *Handler) unarchiveStick(w http.ResponseWriter, r *http.Request) { + if !auth.IdentityFromContext(r.Context()).IsAdmin { + writeError(w, http.StatusForbidden, "forbidden") + return + } + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + stick, err := h.service.UnarchiveStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version) + if err != nil { + handleError(w, r, "unarchive stick", err) + return + } + writeStick(w, stick) +} + +func (h *Handler) claimStick(w http.ResponseWriter, r *http.Request) { + var request struct { + Reason string `json:"reason"` + } + if !decodeJSON(w, r, &request) { + return + } + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + stick, err := h.service.ClaimStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), request.Reason, version) + if err != nil { + handleError(w, r, "claim stick", err) + return + } + writeStick(w, stick) +} + +func (h *Handler) releaseStick(w http.ResponseWriter, r *http.Request) { + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + stick, err := h.service.ReleaseStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version) + if err != nil { + handleError(w, r, "release stick", err) + return + } + writeStick(w, stick) +} + +func (h *Handler) history(w http.ResponseWriter, r *http.Request) { + identity := auth.IdentityFromContext(r.Context()) + id := r.PathValue("id") + stick, err := h.service.GetStick(r.Context(), identity, id) + if err != nil { + handleError(w, r, "get stick history", err) + return + } + setETag(w, stick.Version) + limit, offset, ok := historyPagination(w, r) + if !ok { + return + } + sessions, total, err := h.service.GetHistory(r.Context(), identity, id, limit, offset) + if err != nil { + handleError(w, r, "get stick history", err) + return + } + response := struct { + Sessions []sessionJSON `json:"sessions"` + Total int `json:"total"` + Limit int `json:"limit"` + Offset int `json:"offset"` + }{ + Sessions: sessionsToJSON(sessions), + Total: total, + Limit: limit, + Offset: offset, + } + writeConditionalJSON(w, r, response) +} + +func (h *Handler) subscribe(w http.ResponseWriter, r *http.Request) { + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + if err := h.service.Subscribe(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version); err != nil { + handleError(w, r, "subscribe to stick", err) + return + } + setETag(w, version) + w.WriteHeader(http.StatusNoContent) +} + +func (h *Handler) unsubscribe(w http.ResponseWriter, r *http.Request) { + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + if err := h.service.Unsubscribe(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version); err != nil { + handleError(w, r, "unsubscribe from stick", err) + return + } + setETag(w, version) + w.WriteHeader(http.StatusNoContent) +} + +func (h *Handler) subscriptions(w http.ResponseWriter, r *http.Request) { + ids, err := h.service.SubscribedStickIDs(r.Context(), auth.IdentityFromContext(r.Context())) + if err != nil { + internalError(w, r, "list subscriptions", err) + return + } + if ids == nil { + ids = []string{} + } + writeCollection(w, r, ids) +} + +func (h *Handler) expectedVersion(w http.ResponseWriter, r *http.Request, id string) (int64, bool) { + header := headerValue(r, "If-Match") + if strings.TrimSpace(header) == "" { + writeError(w, http.StatusPreconditionRequired, "If-Match header is required") + return 0, false + } + tags, wildcard, err := parseIfMatch(header) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid If-Match header") + return 0, false + } + if len(tags) == 1 && !wildcard { + return tags[0], true + } + + // A wildcard or a list of tags must be compared to the current + // representation before choosing the version passed to the service. + stick, err := h.service.GetStick(r.Context(), auth.IdentityFromContext(r.Context()), id) + if err != nil { + handleError(w, r, "get stick", err) + return 0, false + } + if !wildcard { + matched := false + for _, tag := range tags { + if tag == stick.Version { + matched = true + break + } + } + if !matched { + writeError(w, http.StatusPreconditionFailed, "precondition failed") + return 0, false + } + } + return stick.Version, true +} + +func historyPagination(w http.ResponseWriter, r *http.Request) (int, int, bool) { + query := r.URL.Query() + limit := defaultHistoryLimit + offset := 0 + var err error + if raw := query.Get("limit"); raw != "" { + limit, err = strconv.Atoi(raw) + if err != nil || limit < 1 || limit > maxHistoryLimit { + writeError(w, http.StatusBadRequest, "invalid history limit") + return 0, 0, false + } + } + if raw := query.Get("offset"); raw != "" { + offset, err = strconv.Atoi(raw) + if err != nil || offset < 0 || offset > maxHistoryOffset { + writeError(w, http.StatusBadRequest, "invalid history offset") + return 0, 0, false + } + } + return limit, offset, true +} + +func parseIfMatch(value string) ([]int64, bool, error) { + value = strings.TrimSpace(value) + if value == "" { + return nil, false, errors.New("missing If-Match") + } + if value == "*" { + return nil, true, nil + } + parts := strings.Split(value, ",") + tags := make([]int64, 0, len(parts)) + for _, part := range parts { + part = strings.TrimSpace(part) + if len(part) < 3 || part[0] != '"' || part[len(part)-1] != '"' || strings.HasPrefix(part, "W/") { + return nil, false, errors.New("invalid entity tag") + } + version, err := strconv.ParseInt(part[1:len(part)-1], 10, 64) + if err != nil || version < 1 || etag(version) != part { + return nil, false, errors.New("invalid entity tag") + } + tags = append(tags, version) + } + if len(tags) == 0 { + return nil, false, errors.New("missing entity tag") + } + return tags, false, nil +} + +func ifNoneMatch(header, current string) bool { + for _, part := range strings.Split(header, ",") { + part = strings.TrimSpace(part) + if part == "*" { + return true + } + if strings.HasPrefix(part, "W/") { + part = strings.TrimSpace(strings.TrimPrefix(part, "W/")) + } + if part == current { + return true + } + } + return false +} + +func writeStick(w http.ResponseWriter, stick domain.Stick) { + setETag(w, stick.Version) + writeJSON(w, http.StatusOK, stickToJSON(stick)) +} + +func writeCollection(w http.ResponseWriter, r *http.Request, value any) { + data, err := json.Marshal(value) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal server error") + return + } + sum := sha256.Sum256(data) + collectionETag := `"` + hex.EncodeToString(sum[:]) + `"` + w.Header().Set("ETag", collectionETag) + if ifNoneMatch(headerValue(r, "If-None-Match"), collectionETag) { + notModified(w) + return + } + writeData(w, http.StatusOK, data) +} + +func writeConditionalJSON(w http.ResponseWriter, r *http.Request, value any) { + data, err := json.Marshal(value) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal server error") + return + } + sum := sha256.Sum256(data) + representationETag := `"` + hex.EncodeToString(sum[:]) + `"` + w.Header().Set("ETag", representationETag) + if ifNoneMatch(headerValue(r, "If-None-Match"), representationETag) { + notModified(w) + return + } + writeData(w, http.StatusOK, data) +} + +func headerValue(r *http.Request, name string) string { + return strings.Join(r.Header.Values(name), ",") +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + data, err := json.Marshal(value) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal server error") + return + } + writeData(w, status, data) +} + +func writeData(w http.ResponseWriter, status int, data []byte) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(status) + _, _ = w.Write(data) +} + +func notModified(w http.ResponseWriter) { + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusNotModified) +} + +func writeError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, struct { + Error string `json:"error"` + }{Error: message}) +} + +func setETag(w http.ResponseWriter, version int64) { w.Header().Set("ETag", etag(version)) } + +func etag(version int64) string { return `"` + strconv.FormatInt(version, 10) + `"` } + +func decodeJSON(w http.ResponseWriter, r *http.Request, destination any) bool { + r.Body = http.MaxBytesReader(w, r.Body, maxJSONBodyBytes) + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(destination); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return false + } + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return false + } + return true +} + +func unauthorized(w http.ResponseWriter) { + w.Header().Set("WWW-Authenticate", `Bearer`) + writeError(w, http.StatusUnauthorized, "unauthorized") +} + +func internalError(w http.ResponseWriter, r *http.Request, operation string, err error) { + httpx.LogError(r.Context(), "request failed", operation, err) + writeError(w, http.StatusInternalServerError, "internal server error") +} + +func handleError(w http.ResponseWriter, r *http.Request, operation string, err error) { + switch { + case errors.Is(err, application.ErrNotFound): + writeError(w, http.StatusNotFound, "not found") + case errors.Is(err, application.ErrForbidden), errors.Is(err, domain.ErrNotHolder): + writeError(w, http.StatusForbidden, "forbidden") + case errors.Is(err, application.ErrVersionConflict): + writeError(w, http.StatusPreconditionFailed, "precondition failed") + case errors.Is(err, application.ErrAlreadyExists): + writeError(w, http.StatusConflict, "conflict") + case errors.Is(err, domain.ErrInvalidStickName), errors.Is(err, domain.ErrInvalidClaimReason): + writeError(w, http.StatusUnprocessableEntity, "invalid request") + case errors.Is(err, domain.ErrAlreadyHeld), errors.Is(err, domain.ErrAlreadyArchived), + errors.Is(err, domain.ErrNotArchived), errors.Is(err, domain.ErrHeld), + errors.Is(err, domain.ErrVersionExhausted): + writeError(w, http.StatusConflict, "conflict") + default: + internalError(w, r, operation, err) + } +} + +type stickJSON struct { + ID string `json:"id"` + Name string `json:"name"` + Version int64 `json:"version"` + Archived bool `json:"archived"` + Available bool `json:"available"` + ArchivedAt *time.Time `json:"archived_at"` + Holder *holderJSON `json:"holder"` +} + +type holderJSON struct { + Name string `json:"name"` + Email string `json:"email"` + ClaimedAt string `json:"claimed_at"` + Reason string `json:"reason"` +} + +type sessionJSON struct { + ID int64 `json:"id"` + StickID string `json:"stick_id"` + HolderName string `json:"holder_name"` + HolderEmail string `json:"holder_email"` + Reason string `json:"reason"` + ClaimedAt string `json:"claimed_at"` + ReleasedAt *string `json:"released_at"` +} + +func stickToJSON(stick domain.Stick) stickJSON { + response := stickJSON{ + ID: stick.ID, + Name: stick.Name, + Version: stick.Version, + Archived: stick.Archived(), + Available: stick.Available(), + ArchivedAt: stick.ArchivedAt, + } + if stick.Holder != nil { + response.Holder = &holderJSON{ + Name: stick.Holder.Name, + Email: stick.Holder.Email, + ClaimedAt: stick.Holder.ClaimedAt.UTC().Format("2006-01-02T15:04:05.999999999Z07:00"), + Reason: stick.Holder.Reason, + } + } + return response +} + +func sticksToJSON(sticks []domain.Stick) []stickJSON { + result := make([]stickJSON, 0, len(sticks)) + for _, stick := range sticks { + result = append(result, stickToJSON(stick)) + } + return result +} + +func sessionsToJSON(sessions []domain.Session) []sessionJSON { + result := make([]sessionJSON, 0, len(sessions)) + for _, session := range sessions { + item := sessionJSON{ + ID: session.ID, + StickID: session.StickID, + HolderName: session.HolderName, + HolderEmail: session.HolderEmail, + Reason: session.Reason, + ClaimedAt: session.ClaimedAt.UTC().Format("2006-01-02T15:04:05.999999999Z07:00"), + } + if session.ReleasedAt != nil { + releasedAt := session.ReleasedAt.UTC().Format("2006-01-02T15:04:05.999999999Z07:00") + item.ReleasedAt = &releasedAt + } + result = append(result, item) + } + return result +} diff --git a/internal/api/handler_test.go b/internal/api/handler_test.go new file mode 100644 index 0000000..56ca0c3 --- /dev/null +++ b/internal/api/handler_test.go @@ -0,0 +1,152 @@ +package api_test + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "stick/internal/adapters/persistence/sqlite" + "stick/internal/api" + "stick/internal/application" + domain "stick/internal/core" + "stick/internal/publicurl" + "stick/internal/web/httpx" +) + +type tokenValidator map[string]domain.Identity + +func (v tokenValidator) Validate(_ context.Context, token string) (domain.Identity, error) { + identity, ok := v[token] + if !ok { + return domain.Identity{}, errors.New("invalid token") + } + return identity, nil +} + +func newTestHandler(t *testing.T) http.Handler { + t.Helper() + store, err := sqlite.Open(filepath.Join(t.TempDir(), "stick.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = store.Close() }) + publicURL, err := publicurl.Parse("http://localhost:8080") + if err != nil { + t.Fatal(err) + } + admin := domain.Identity{Sub: "admin", Name: "Admin", Email: "admin@example.com", EmailVerified: true} + handler := api.New(application.NewService(store), tokenValidator{ + "admin-token": admin, + "user-token": {Sub: "user", Name: "User", Email: "user@example.com", EmailVerified: true}, + }, []string{"admin@example.com"}, publicURL, true) + router := httpx.NewRouter(publicURL) + api.Register(router, handler) + router.SetNotFound(http.HandlerFunc(api.NotFound)) + return router +} + +func request(handler http.Handler, method, path, token, body string, headers map[string]string) *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + request := httptest.NewRequest(method, path, stringsReader(body)) + if token != "" { + request.Header.Set("Authorization", "Bearer "+token) + } + for key, value := range headers { + request.Header.Set(key, value) + } + handler.ServeHTTP(recorder, request) + return recorder +} + +func stringsReader(value string) *strings.Reader { return strings.NewReader(value) } + +func TestAuthorizationIsBearerOnly(t *testing.T) { + handler := newTestHandler(t) + response := request(handler, http.MethodGet, "/api/v1/sticks", "", "", nil) + if response.Code != http.StatusUnauthorized || response.Header().Get("WWW-Authenticate") != "Bearer" { + t.Fatalf("status=%d authenticate=%q body=%s", response.Code, response.Header().Get("WWW-Authenticate"), response.Body.String()) + } + response = request(handler, http.MethodGet, "/api/v1/sticks", "unknown", "", nil) + if response.Code != http.StatusUnauthorized { + t.Fatalf("invalid token status=%d", response.Code) + } +} + +func TestStickETagAndOptimisticConcurrency(t *testing.T) { + handler := newTestHandler(t) + created := request(handler, http.MethodPost, "/api/v1/sticks", "admin-token", `{"name":"Deploy Key"}`, map[string]string{"Content-Type": "application/json"}) + if created.Code != http.StatusCreated || created.Header().Get("ETag") != `"1"` { + t.Fatalf("create status=%d etag=%q body=%s", created.Code, created.Header().Get("ETag"), created.Body.String()) + } + var stick struct { + ID string `json:"id"` + Version int64 `json:"version"` + } + if err := json.Unmarshal(created.Body.Bytes(), &stick); err != nil { + t.Fatal(err) + } + if stick.ID == "" || stick.Version != 1 { + t.Fatalf("created stick = %+v", stick) + } + + path := "/api/v1/sticks/" + stick.ID + current := request(handler, http.MethodGet, path, "user-token", "", nil) + if current.Code != http.StatusOK || current.Header().Get("ETag") != `"1"` { + t.Fatalf("get status=%d etag=%q", current.Code, current.Header().Get("ETag")) + } + notModified := request(handler, http.MethodGet, path, "user-token", "", map[string]string{"If-None-Match": `"1"`}) + if notModified.Code != http.StatusNotModified || notModified.Body.Len() != 0 { + t.Fatalf("not modified status=%d body=%q", notModified.Code, notModified.Body.String()) + } + + missing := request(handler, http.MethodPatch, path, "admin-token", `{"name":"Renamed"}`, map[string]string{"Content-Type": "application/json"}) + if missing.Code != http.StatusPreconditionRequired { + t.Fatalf("missing If-Match status=%d", missing.Code) + } + stale := request(handler, http.MethodPatch, path, "admin-token", `{"name":"Stale"}`, map[string]string{ + "Content-Type": "application/json", "If-Match": `"9"`, + }) + if stale.Code != http.StatusPreconditionFailed { + t.Fatalf("stale status=%d body=%s", stale.Code, stale.Body.String()) + } + updated := request(handler, http.MethodPatch, path, "admin-token", `{"name":"Renamed"}`, map[string]string{ + "Content-Type": "application/json", "If-Match": `"1"`, + }) + if updated.Code != http.StatusOK || updated.Header().Get("ETag") != `"2"` { + t.Fatalf("update status=%d etag=%q body=%s", updated.Code, updated.Header().Get("ETag"), updated.Body.String()) + } +} + +func TestAPIMapsAuthorizationAndValidationErrors(t *testing.T) { + handler := newTestHandler(t) + for _, test := range []struct { + name string + method string + path string + token string + body string + status int + }{ + {name: "non-admin create", method: http.MethodPost, path: "/api/v1/sticks", token: "user-token", body: `{"name":"x"}`, status: http.StatusForbidden}, + {name: "invalid JSON", method: http.MethodPost, path: "/api/v1/sticks", token: "admin-token", body: `{`, status: http.StatusBadRequest}, + } { + t.Run(test.name, func(t *testing.T) { + response := request(handler, test.method, test.path, test.token, test.body, map[string]string{"Content-Type": "application/json"}) + if response.Code != test.status { + t.Fatalf("status=%d body=%s, want %d", response.Code, response.Body.String(), test.status) + } + }) + } + + unknown := request(handler, http.MethodGet, "/api/v1/missing", "user-token", "", nil) + if unknown.Code != http.StatusNotFound || unknown.Header().Get("Content-Type") != "application/json" { + t.Fatalf("unknown route status=%d content-type=%q", unknown.Code, unknown.Header().Get("Content-Type")) + } +} + +var _ api.TokenValidator = tokenValidator{} diff --git a/internal/api/headers.go b/internal/api/headers.go new file mode 100644 index 0000000..a9300c6 --- /dev/null +++ b/internal/api/headers.go @@ -0,0 +1,11 @@ +package api + +import "net/http" + +// Headers adds response headers useful for a JSON API. +func Headers(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Content-Type-Options", "nosniff") + next.ServeHTTP(w, r) + }) +} diff --git a/internal/auth/jwt.go b/internal/auth/jwt.go new file mode 100644 index 0000000..6152875 --- /dev/null +++ b/internal/auth/jwt.go @@ -0,0 +1,189 @@ +package auth + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "sync" + "time" + + domain "stick/internal/core" + + "github.com/coreos/go-oidc/v3/oidc" +) + +// JWTConfig contains the settings used to validate external bearer tokens. +// Endpoint is an OIDC issuer URL. The provider's discovery document and JWKS +// are used to validate the token signature and registered claims. +type JWTConfig struct { + Endpoint string + Audience string + Scope string +} + +// JWTValidator validates external JWTs issued by the configured identity +// provider. Provider discovery is lazy so an identity-provider outage does +// not prevent the service from starting. +type JWTValidator struct { + config JWTConfig + + mu sync.Mutex + provider *oidc.Provider + discoveryDone chan struct{} + lastDiscoveryErr error + retryDiscoveryAt time.Time + failureBackoff time.Duration +} + +const ( + providerDiscoveryTimeout = 10 * time.Second + initialDiscoveryBackoff = time.Second + maxDiscoveryBackoff = 30 * time.Second +) + +// NewJWTValidator returns a validator for config. +func NewJWTValidator(config JWTConfig) *JWTValidator { + return &JWTValidator{config: config} +} + +// Validate verifies rawToken and returns the identity carried by it. +func (v *JWTValidator) Validate(ctx context.Context, rawToken string) (domain.Identity, error) { + if strings.TrimSpace(rawToken) == "" { + return domain.Identity{}, errors.New("token is empty") + } + provider, err := v.providerFor(ctx) + if err != nil { + return domain.Identity{}, err + } + + verifier := provider.Verifier(&oidc.Config{ClientID: v.config.Audience}) + token, err := verifier.Verify(ctx, rawToken) + if err != nil { + return domain.Identity{}, err + } + + var claims jwtClaims + if err := token.Claims(&claims); err != nil { + return domain.Identity{}, err + } + if strings.TrimSpace(claims.Subject) == "" { + return domain.Identity{}, errors.New("token subject is required") + } + if !scopeContains(claims.Scope, claims.SCP, v.config.Scope) { + return domain.Identity{}, errors.New("token scope is insufficient") + } + + return domain.Identity{ + Sub: claims.Subject, + Name: claims.Name, + Email: claims.Email, + EmailVerified: claims.EmailVerified, + }, nil +} + +type jwtClaims struct { + Subject string `json:"sub"` + Name string `json:"name"` + Email string `json:"email"` + EmailVerified bool `json:"email_verified"` + Scope scopeValues `json:"scope"` + SCP scopeValues `json:"scp"` +} + +type scopeValues []string + +func (s *scopeValues) UnmarshalJSON(data []byte) error { + var values []string + if err := json.Unmarshal(data, &values); err == nil { + *s = values + return nil + } + var value string + if err := json.Unmarshal(data, &value); err != nil { + return err + } + *s = []string{value} + return nil +} + +func scopeContains(scope, scp scopeValues, required string) bool { + provided := make(map[string]struct{}) + for _, value := range scope { + for _, item := range strings.Fields(value) { + provided[item] = struct{}{} + } + } + for _, value := range scp { + for _, item := range strings.Fields(value) { + provided[item] = struct{}{} + } + } + for _, value := range strings.Fields(required) { + if _, ok := provided[value]; !ok { + return false + } + } + return true +} + +func (v *JWTValidator) providerFor(ctx context.Context) (*oidc.Provider, error) { + for { + v.mu.Lock() + if v.provider != nil { + provider := v.provider + v.mu.Unlock() + return provider, nil + } + if v.lastDiscoveryErr != nil && time.Now().Before(v.retryDiscoveryAt) { + err := v.lastDiscoveryErr + v.mu.Unlock() + return nil, err + } + if done := v.discoveryDone; done != nil { + v.mu.Unlock() + select { + case <-done: + continue + case <-ctx.Done(): + return nil, ctx.Err() + } + } + done := make(chan struct{}) + v.discoveryDone = done + v.mu.Unlock() + + discoveryCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), providerDiscoveryTimeout) + provider, err := oidc.NewProvider(oidc.ClientContext(discoveryCtx, &http.Client{Timeout: providerDiscoveryTimeout}), v.config.Endpoint) + cancel() + + v.mu.Lock() + if err == nil { + v.provider = provider + v.lastDiscoveryErr = nil + v.retryDiscoveryAt = time.Time{} + v.failureBackoff = 0 + } else { + err = fmt.Errorf("discover identity provider: %w", err) + v.lastDiscoveryErr = err + v.failureBackoff = nextDiscoveryBackoff(v.failureBackoff) + v.retryDiscoveryAt = time.Now().Add(v.failureBackoff) + } + v.discoveryDone = nil + close(done) + v.mu.Unlock() + return provider, err + } +} + +func nextDiscoveryBackoff(current time.Duration) time.Duration { + if current <= 0 { + return initialDiscoveryBackoff + } + if current >= maxDiscoveryBackoff/2 { + return maxDiscoveryBackoff + } + return current * 2 +} diff --git a/internal/auth/jwt_test.go b/internal/auth/jwt_test.go new file mode 100644 index 0000000..28922e5 --- /dev/null +++ b/internal/auth/jwt_test.go @@ -0,0 +1,105 @@ +package auth_test + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "stick/internal/auth" +) + +func TestJWTValidatorValidatesExternalToken(t *testing.T) { + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + var providerURL string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/.well-known/openid-configuration": + _, _ = fmt.Fprintf(w, `{"issuer":%q,"jwks_uri":%q}`, providerURL, providerURL+"/keys") + case "/keys": + keyData := map[string]any{ + "keys": []map[string]any{{ + "kty": "RSA", "kid": "test-key", "use": "sig", "alg": "RS256", + "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()), "e": "AQAB", + }}, + } + _ = json.NewEncoder(w).Encode(keyData) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + providerURL = server.URL + + validator := auth.NewJWTValidator(auth.JWTConfig{Endpoint: server.URL, Audience: "stick-api", Scope: "stick:use"}) + token := signedJWT(t, key, map[string]any{ + "iss": server.URL, "aud": []string{"stick-api"}, "sub": "user-1", + "name": "Alice", "email": "alice@example.com", "email_verified": true, + "scope": "openid stick:use", "exp": time.Now().Add(time.Hour).Unix(), + }) + identity, err := validator.Validate(t.Context(), token) + if err != nil { + t.Fatalf("Validate: %v", err) + } + if identity.Sub != "user-1" || identity.Name != "Alice" || identity.Email != "alice@example.com" || !identity.EmailVerified { + t.Fatalf("identity = %+v", identity) + } +} + +func TestJWTValidatorRequiresScope(t *testing.T) { + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + var providerURL string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/.well-known/openid-configuration" { + _, _ = fmt.Fprintf(w, `{"issuer":%q,"jwks_uri":%q}`, providerURL, providerURL+"/keys") + return + } + keyData := map[string]any{"keys": []map[string]any{{ + "kty": "RSA", "kid": "test-key", "use": "sig", "alg": "RS256", + "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()), "e": "AQAB", + }}} + _ = json.NewEncoder(w).Encode(keyData) + })) + defer server.Close() + providerURL = server.URL + + validator := auth.NewJWTValidator(auth.JWTConfig{Endpoint: server.URL, Audience: "stick-api", Scope: "stick:write"}) + token := signedJWT(t, key, map[string]any{ + "iss": server.URL, "aud": "stick-api", "sub": "user-1", "scope": "stick:read", + "exp": time.Now().Add(time.Hour).Unix(), + }) + if _, err := validator.Validate(t.Context(), token); err == nil { + t.Fatal("expected token with insufficient scope to be rejected") + } +} + +func signedJWT(t *testing.T, key *rsa.PrivateKey, claims map[string]any) string { + t.Helper() + header := `{"alg":"RS256","kid":"test-key","typ":"JWT"}` + payload, err := json.Marshal(claims) + if err != nil { + t.Fatal(err) + } + encoded := base64.RawURLEncoding.EncodeToString([]byte(header)) + "." + base64.RawURLEncoding.EncodeToString(payload) + digest := sha256.Sum256([]byte(encoded)) + signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:]) + if err != nil { + t.Fatal(err) + } + return encoded + "." + base64.RawURLEncoding.EncodeToString(signature) +} diff --git a/internal/auth/oidc.go b/internal/auth/oidc.go deleted file mode 100644 index b8d9760..0000000 --- a/internal/auth/oidc.go +++ /dev/null @@ -1,9 +0,0 @@ -package auth - -// OIDCConfig contains the provider credentials used by the authentication -// flow. -type OIDCConfig struct { - Issuer string - ClientID string - ClientSecret string -} diff --git a/internal/auth/session.go b/internal/auth/session.go deleted file mode 100644 index d7e4400..0000000 --- a/internal/auth/session.go +++ /dev/null @@ -1,73 +0,0 @@ -package auth - -import ( - "fmt" - "strings" - "time" - - domain "stick/internal/core" - - "github.com/golang-jwt/jwt/v5" -) - -// SessionTTL is the lifetime of a signed session token. -const SessionTTL = 24 * time.Hour - -const sessionIssuer = "stick" -const sessionAudience = "stick-session" - -type sessionClaims struct { - jwt.RegisteredClaims - Name string `json:"name"` - Email string `json:"email"` - EmailVerified bool `json:"email_verified"` -} - -// Issue creates a signed JWT for the given identity. -func Issue(identity domain.Identity, secret []byte) (string, error) { - if strings.TrimSpace(identity.Sub) == "" { - return "", fmt.Errorf("identity subject is required") - } - now := time.Now() - claims := sessionClaims{ - RegisteredClaims: jwt.RegisteredClaims{ - Issuer: sessionIssuer, - Subject: identity.Sub, - Audience: jwt.ClaimStrings{sessionAudience}, - ExpiresAt: jwt.NewNumericDate(now.Add(SessionTTL)), - IssuedAt: jwt.NewNumericDate(now), - }, - Name: identity.Name, - Email: identity.Email, - EmailVerified: identity.EmailVerified, - } - return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret) -} - -// Verify parses and validates a signed JWT, returning the identity it carries. -func Verify(tokenString string, secret []byte) (domain.Identity, error) { - var claims sessionClaims - _, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (any, error) { - if token.Method != jwt.SigningMethodHS256 { - return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) - } - return secret, nil - }, - jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}), - jwt.WithIssuer(sessionIssuer), - jwt.WithAudience(sessionAudience), - jwt.WithExpirationRequired(), - ) - if err != nil { - return domain.Identity{}, err - } - if strings.TrimSpace(claims.Subject) == "" { - return domain.Identity{}, fmt.Errorf("token subject is required") - } - return domain.Identity{ - Sub: claims.Subject, - Name: claims.Name, - Email: claims.Email, - EmailVerified: claims.EmailVerified, - }, nil -} diff --git a/internal/auth/session_test.go b/internal/auth/session_test.go deleted file mode 100644 index bbed3d5..0000000 --- a/internal/auth/session_test.go +++ /dev/null @@ -1,170 +0,0 @@ -package auth_test - -import ( - "testing" - "time" - - "stick/internal/auth" - domain "stick/internal/core" - - "github.com/golang-jwt/jwt/v5" -) - -func TestSessionRoundTrip(t *testing.T) { - secret := []byte("test-secret-key-32-bytes-minimum!") - identity := domain.Identity{Sub: "user123", Name: "Alice", Email: "alice@example.com", EmailVerified: true} - - token, err := auth.Issue(identity, secret) - if err != nil { - t.Fatalf("Issue: %v", err) - } - if token == "" { - t.Fatal("expected non-empty token") - } - - got, err := auth.Verify(token, secret) - if err != nil { - t.Fatalf("Verify: %v", err) - } - if got.Sub != identity.Sub || got.Email != identity.Email || !got.EmailVerified { - t.Errorf("got %+v, want %+v", got, identity) - } -} - -func TestSessionIssuesStableIssuerAudienceAndTTL(t *testing.T) { - secret := []byte("test-secret-key-32-bytes-minimum!") - before := time.Now() - tokenString, err := auth.Issue(domain.Identity{Sub: "user123"}, secret) - if err != nil { - t.Fatal(err) - } - parsed, err := jwt.Parse(tokenString, func(*jwt.Token) (any, error) { return secret, nil }) - if err != nil { - t.Fatal(err) - } - claims, ok := parsed.Claims.(jwt.MapClaims) - if !ok { - t.Fatalf("claims type = %T", parsed.Claims) - } - if claims["iss"] != "stick" { - t.Fatalf("issuer = %v", claims["iss"]) - } - audience, ok := claims["aud"].([]any) - if !ok || len(audience) != 1 || audience[0] != "stick-session" { - t.Fatalf("audience = %#v", claims["aud"]) - } - issuedAt := time.Unix(int64(claims["iat"].(float64)), 0) - expiresAt := time.Unix(int64(claims["exp"].(float64)), 0) - if ttl := expiresAt.Sub(issuedAt); ttl != auth.SessionTTL { - t.Fatalf("session TTL = %v, want %v", ttl, auth.SessionTTL) - } - if issuedAt.Before(before.Add(-time.Second)) || issuedAt.After(time.Now().Add(time.Second)) { - t.Fatalf("issued-at time = %v", issuedAt) - } -} - -func TestSessionRejectsMissingOrIncorrectIssuerAndAudience(t *testing.T) { - secret := []byte("test-secret-key-32-bytes-minimum!") - tests := []struct { - name string - issuer any - audience any - }{ - {name: "missing issuer", audience: []string{"stick-session"}}, - {name: "wrong issuer", issuer: "other", audience: []string{"stick-session"}}, - {name: "missing audience", issuer: "stick"}, - {name: "wrong audience", issuer: "stick", audience: []string{"other"}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - claims := jwt.MapClaims{ - "sub": "user123", "exp": time.Now().Add(time.Hour).Unix(), - } - if tt.issuer != nil { - claims["iss"] = tt.issuer - } - if tt.audience != nil { - claims["aud"] = tt.audience - } - tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret) - if err != nil { - t.Fatal(err) - } - if _, err := auth.Verify(tokenString, secret); err == nil { - t.Fatal("expected token to be rejected") - } - }) - } -} - -func TestSessionRejectsMissingExpiration(t *testing.T) { - secret := []byte("test-secret-key-32-bytes-minimum!") - tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ - "iss": "stick", "aud": []string{"stick-session"}, "sub": "user123", - }).SignedString(secret) - if err != nil { - t.Fatal(err) - } - if _, err := auth.Verify(tokenString, secret); err == nil { - t.Fatal("expected token without expiration to be rejected") - } -} - -func TestSessionRejectsEmptySubject(t *testing.T) { - secret := []byte("test-secret-key-32-bytes-minimum!") - token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ - "iss": "stick", - "aud": []string{"stick-session"}, - "sub": "", - "exp": time.Now().Add(time.Hour).Unix(), - }) - tokenString, err := token.SignedString(secret) - if err != nil { - t.Fatalf("SignedString: %v", err) - } - - if _, err := auth.Verify(tokenString, secret); err == nil { - t.Fatal("expected empty subject to be rejected") - } -} - -func TestSessionIssueRejectsEmptySubject(t *testing.T) { - _, err := auth.Issue(domain.Identity{Email: "alice@example.com"}, []byte("test-secret-key-32-bytes-minimum!")) - if err == nil { - t.Fatal("expected empty subject to be rejected") - } -} - -func TestSessionRejectsInvalidSecret(t *testing.T) { - secret := []byte("correct-secret-key-32-bytes-min!!") - identity := domain.Identity{Sub: "u1", Name: "Alice", Email: "a@example.com"} - - token, _ := auth.Issue(identity, secret) - _, err := auth.Verify(token, []byte("wrong-secret-key-32-bytes-minimun")) - if err == nil { - t.Error("expected error for wrong secret") - } -} - -func TestSessionRejectsOtherHMACAlgorithms(t *testing.T) { - secret := []byte("test-secret-key-32-bytes-minimum!") - for _, method := range []jwt.SigningMethod{ - jwt.SigningMethodHS384, - jwt.SigningMethodHS512, - } { - t.Run(method.Alg(), func(t *testing.T) { - token := jwt.NewWithClaims(method, jwt.MapClaims{ - "sub": "user123", - "exp": time.Now().Add(time.Hour).Unix(), - }) - tokenString, err := token.SignedString(secret) - if err != nil { - t.Fatalf("SignedString: %v", err) - } - - if _, err := auth.Verify(tokenString, secret); err == nil { - t.Fatalf("expected %s token to be rejected", method.Alg()) - } - }) - } -} diff --git a/internal/config/azure_app_configuration_provider_test.go b/internal/config/azure_app_configuration_provider_test.go index 9248d16..ce43e2b 100644 --- a/internal/config/azure_app_configuration_provider_test.go +++ b/internal/config/azure_app_configuration_provider_test.go @@ -15,8 +15,6 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/data/azappconfig/v2" ) -const azureTestSecret = "0123456789abcdef0123456789abcdef" - type testAzureCredential struct{} func (testAzureCredential) GetToken(context.Context, policy.TokenRequestOptions) (azcore.AccessToken, error) { @@ -51,10 +49,9 @@ func TestAzureAppConfigurationProviderLoadsSettings(t *testing.T) { settings := []map[string]any{ {"key": "stick/database", "value": "/tmp/azure.db", "label": "production"}, {"key": "stick/server/public_url", "value": "http://localhost:8080", "label": "production"}, - {"key": "stick/auth/oidc/issuer", "value": "https://issuer.example.com", "label": "production"}, - {"key": "stick/auth/oidc/client_id", "value": "client-id", "label": "production"}, - {"key": "stick/auth/oidc/client_secret", "value": "client-secret", "label": "production"}, - {"key": "stick/auth/session_secret", "value": azureTestSecret, "label": "production"}, + {"key": "stick/auth/idp_endpoint", "value": "https://issuer.example.com", "label": "production"}, + {"key": "stick/auth/audience", "value": "stick-api", "label": "production"}, + {"key": "stick/auth/scope", "value": "stick:use", "label": "production"}, {"key": "stick/auth/admin_emails", "value": `["Alice@example.com","bob@example.com"]`, "label": "production", "content_type": "application/json"}, {"key": "stick/timezone", "value": "America/New_York", "label": "production"}, {"key": "stick/notifications/webhook", "value": `[{"url":"https://hooks.example.com/stick"}]`, "label": "production", "content_type": "application/json"}, @@ -141,10 +138,9 @@ func TestAzureAppConfigurationProviderSupportsCustomSeparator(t *testing.T) { settings := []map[string]string{ {"key": "stick.database", "value": "/tmp/azure-dot.db"}, {"key": "stick.server.public_url", "value": "http://localhost:8080"}, - {"key": "stick.auth.oidc.issuer", "value": "https://issuer.example.com"}, - {"key": "stick.auth.oidc.client_id", "value": "client-id"}, - {"key": "stick.auth.oidc.client_secret", "value": "client-secret"}, - {"key": "stick.auth.session_secret", "value": azureTestSecret}, + {"key": "stick.auth.idp_endpoint", "value": "https://issuer.example.com"}, + {"key": "stick.auth.audience", "value": "stick-api"}, + {"key": "stick.auth.scope", "value": "stick:use"}, } server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if got := r.URL.Query().Get("key"); got != "stick.*" { diff --git a/internal/config/config.go b/internal/config/config.go index 2f92aaf..944b22b 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,7 +4,6 @@ package config import ( "time" - "stick/internal/auth" "stick/internal/publicurl" ) @@ -30,9 +29,10 @@ type DatabaseConfig struct { // AuthConfig contains authentication and authorization settings. type AuthConfig struct { - OIDC auth.OIDCConfig - SessionSecret []byte - AdminEmails []string + IDPEndpoint string + Audience string + Scope string + AdminEmails []string } // SMTPConfig holds SMTP connection settings and optional email templates. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 629efd0..4c4d903 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -11,27 +11,12 @@ import ( "stick/internal/config" ) -const testSecret = "0123456789abcdef0123456789abcdef" - var configEnvKeys = []string{ - "STICK_DATABASE", - "STICK_SERVER_PUBLIC_URL", - "STICK_SERVER_LISTEN_ADDR", - "STICK_TIMEZONE", - "STICK_AUTH_OIDC_ISSUER", - "STICK_AUTH_OIDC_CLIENT_ID", - "STICK_AUTH_OIDC_CLIENT_SECRET", - "STICK_AUTH_SESSION_SECRET", - "STICK_AUTH_ADMIN_EMAILS", - "STICK_NOTIFICATIONS_SMTP_HOST", - "STICK_NOTIFICATIONS_SMTP_PORT", - "STICK_NOTIFICATIONS_SMTP_TLS_MODE", - "STICK_NOTIFICATIONS_SMTP_USERNAME", - "STICK_NOTIFICATIONS_SMTP_PASSWORD", - "STICK_NOTIFICATIONS_SMTP_FROM", - "STICK_NOTIFICATIONS_SMTP_SUBJECT", - "STICK_NOTIFICATIONS_SMTP_BODY", - "STICK_NOTIFICATIONS_WEBHOOK_URL", + "STICK_DATABASE", "STICK_SERVER_PUBLIC_URL", "STICK_SERVER_LISTEN_ADDR", "STICK_TIMEZONE", + "STICK_AUTH_IDP_ENDPOINT", "STICK_AUTH_AUDIENCE", "STICK_AUTH_SCOPE", "STICK_AUTH_ADMIN_EMAILS", + "STICK_NOTIFICATIONS_SMTP_HOST", "STICK_NOTIFICATIONS_SMTP_PORT", "STICK_NOTIFICATIONS_SMTP_TLS_MODE", + "STICK_NOTIFICATIONS_SMTP_USERNAME", "STICK_NOTIFICATIONS_SMTP_PASSWORD", "STICK_NOTIFICATIONS_SMTP_FROM", + "STICK_NOTIFICATIONS_SMTP_SUBJECT", "STICK_NOTIFICATIONS_SMTP_BODY", "STICK_NOTIFICATIONS_WEBHOOK_URL", "STICK_NOTIFICATIONS_TEAMS_URL", } @@ -40,10 +25,9 @@ func setRequiredEnv(t *testing.T) { clearConfigEnv(t) t.Setenv("STICK_DATABASE", "/tmp/test.db") t.Setenv("STICK_SERVER_PUBLIC_URL", "http://localhost:8080") - t.Setenv("STICK_AUTH_OIDC_ISSUER", "https://accounts.google.com") - t.Setenv("STICK_AUTH_OIDC_CLIENT_ID", "client-id") - t.Setenv("STICK_AUTH_OIDC_CLIENT_SECRET", "client-secret") - t.Setenv("STICK_AUTH_SESSION_SECRET", testSecret) + t.Setenv("STICK_AUTH_IDP_ENDPOINT", "https://accounts.google.com") + t.Setenv("STICK_AUTH_AUDIENCE", "stick-api") + t.Setenv("STICK_AUTH_SCOPE", "stick:use") } func clearConfigEnv(t *testing.T) { @@ -80,84 +64,58 @@ func writeConfig(t *testing.T, content string) string { return path } -func TestLoad_FromEnvironment(t *testing.T) { +func TestLoadFromEnvironment(t *testing.T) { setRequiredEnv(t) cfg := loadFromEnv(t) - if cfg.Database.Driver != config.DatabaseDriverSQLite || cfg.Database.DSN != "/tmp/test.db" { t.Fatalf("database = %+v", cfg.Database) } - if cfg.Server.ListenAddr != ":8080" { - t.Errorf("ListenAddr = %q, want :8080", cfg.Server.ListenAddr) - } - if cfg.Server.PublicURL.String() != "http://localhost:8080" { - t.Errorf("PublicURL = %q", cfg.Server.PublicURL.String()) + if cfg.Auth.IDPEndpoint != "https://accounts.google.com" || cfg.Auth.Audience != "stick-api" || cfg.Auth.Scope != "stick:use" { + t.Fatalf("auth = %+v", cfg.Auth) } - if cfg.Timezone != time.UTC { - t.Errorf("Timezone = %v, want UTC", cfg.Timezone) - } - if len(cfg.Auth.AdminEmails) != 0 { - t.Errorf("AdminEmails = %v, want empty", cfg.Auth.AdminEmails) + if cfg.Server.ListenAddr != ":8080" || cfg.Timezone != time.UTC { + t.Fatalf("server/timezone = %+v, %v", cfg.Server, cfg.Timezone) } } -func TestLoad_InfersPostgresFromURL(t *testing.T) { +func TestLoadDefaultsPublicURL(t *testing.T) { setRequiredEnv(t) - t.Setenv("STICK_DATABASE", "postgres://user:secret@database.example/stick") + t.Setenv("STICK_SERVER_PUBLIC_URL", "") cfg := loadFromEnv(t) - - if cfg.Database.Driver != config.DatabaseDriverPostgres || cfg.Database.DSN != "postgres://user:secret@database.example/stick" { - t.Fatalf("database = %+v", cfg.Database) - } -} - -func TestLoad_InfersMongoDBFromURL(t *testing.T) { - for _, dsn := range []string{ - "mongodb://user:secret@database.example/stick", - "mongodb+srv://user:secret@cluster.example/stick", - } { - t.Run(dsn[:strings.IndexByte(dsn, ':')], func(t *testing.T) { - setRequiredEnv(t) - t.Setenv("STICK_DATABASE", dsn) - cfg := loadFromEnv(t) - if cfg.Database.Driver != config.DatabaseDriverMongoDB || cfg.Database.DSN != dsn { - t.Fatalf("database = %+v", cfg.Database) - } - }) + if got := cfg.Server.PublicURL.String(); got != "http://localhost" { + t.Fatalf("PublicURL = %q, want http://localhost", got) } } -func TestLoad_FromYAML(t *testing.T) { +func TestLoadFromYAMLAndEnvironmentOverride(t *testing.T) { clearConfigEnv(t) path := writeConfig(t, ` -database: /tmp/yaml.db +database: /tmp/from-yaml.db server: public_url: https://yaml.example.com/ops/stick/ listen_addr: :9090 auth: - oidc: - issuer: https://yaml.example.com - client_id: yaml-client - client_secret: yaml-secret - session_secret: yaml-session-secret-that-is-long-enough + idp_endpoint: https://yaml.example.com + audience: yaml-api + scope: stick:read admin_emails: - Alice@example.com - - bob@example.com timezone: America/New_York `) - + t.Setenv("STICK_AUTH_AUDIENCE", "env-api") + t.Setenv("STICK_SERVER_PUBLIC_URL", "https://env.example.com/stick/") cfg, err := config.Load(context.Background(), config.YAMLProvider{Path: path}, config.EnvironmentProvider{}) if err != nil { t.Fatalf("Load: %v", err) } - if cfg.Database.DSN != "/tmp/yaml.db" || cfg.Server.ListenAddr != ":9090" { + if cfg.Database.DSN != "/tmp/from-yaml.db" || cfg.Server.ListenAddr != ":9090" { t.Fatalf("config = %+v", cfg) } - if got := cfg.Server.PublicURL.String(); got != "https://yaml.example.com/ops/stick" { - t.Errorf("PublicURL = %q", got) + if cfg.Auth.Audience != "env-api" || cfg.Auth.IDPEndpoint != "https://yaml.example.com" || cfg.Auth.Scope != "stick:read" { + t.Fatalf("auth = %+v", cfg.Auth) } - if got := cfg.Auth.AdminEmails; len(got) != 2 || got[0] != "Alice@example.com" || got[1] != "bob@example.com" { - t.Errorf("AdminEmails = %v", got) + if got := cfg.Server.PublicURL.String(); got != "https://env.example.com/stick" { + t.Errorf("PublicURL = %q", got) } want, _ := time.LoadLocation("America/New_York") if cfg.Timezone.String() != want.String() { @@ -165,18 +123,16 @@ timezone: America/New_York } } -func TestLoad_EnvironmentOverridesYAML(t *testing.T) { +func TestLoadEnvironmentOverridesYAML(t *testing.T) { clearConfigEnv(t) path := writeConfig(t, ` database: /tmp/from-yaml.db server: - public_url: http://yaml.example.com + public_url: http://localhost:8080 auth: - oidc: - issuer: https://yaml.example.com - client_id: yaml-client - client_secret: yaml-secret - session_secret: yaml-session-secret-that-is-long-enough + idp_endpoint: https://yaml.example.com + audience: yaml-api + scope: stick:read `) t.Setenv("STICK_DATABASE", "/tmp/from-env.db") t.Setenv("STICK_SERVER_PUBLIC_URL", "https://env.example.com/stick/") @@ -197,7 +153,7 @@ auth: } } -func TestLoad_ProvidersApplyInSuppliedOrder(t *testing.T) { +func TestLoadProvidersApplyInSuppliedOrder(t *testing.T) { setRequiredEnv(t) t.Setenv("STICK_SERVER_LISTEN_ADDR", ":7070") path := writeConfig(t, ` @@ -233,18 +189,36 @@ server: } } -func TestLoad_NotificationConfig(t *testing.T) { +func TestLoadInfersDatabaseDrivers(t *testing.T) { + setRequiredEnv(t) + for _, test := range []struct { + dsn string + driver string + }{ + {dsn: "postgres://user:secret@database.example/stick", driver: config.DatabaseDriverPostgres}, + {dsn: "mongodb://user:secret@database.example/stick", driver: config.DatabaseDriverMongoDB}, + {dsn: "mongodb+srv://user:secret@cluster.example/stick", driver: config.DatabaseDriverMongoDB}, + } { + t.Run(test.driver, func(t *testing.T) { + t.Setenv("STICK_DATABASE", test.dsn) + cfg := loadFromEnv(t) + if cfg.Database.Driver != test.driver || cfg.Database.DSN != test.dsn { + t.Fatalf("database = %+v", cfg.Database) + } + }) + } +} + +func TestLoadNotificationConfig(t *testing.T) { clearConfigEnv(t) path := writeConfig(t, ` database: /tmp/test.db server: public_url: http://localhost:8080 auth: - oidc: - issuer: https://example.com - client_id: c - client_secret: s - session_secret: yaml-session-secret-that-is-long-enough + idp_endpoint: https://example.com + audience: api + scope: stick:use notifications: smtp: host: smtp.example.com @@ -268,7 +242,7 @@ notifications: } } -func TestLoad_TeamsNotificationConfig(t *testing.T) { +func TestLoadTeamsNotificationConfig(t *testing.T) { setRequiredEnv(t) t.Setenv("STICK_NOTIFICATIONS_TEAMS_URL", " https://teams.example.com/webhook ") cfg := loadFromEnv(t) @@ -277,18 +251,16 @@ func TestLoad_TeamsNotificationConfig(t *testing.T) { } } -func TestLoad_AllowsMultipleNotificationBackends(t *testing.T) { +func TestLoadAllowsMultipleNotificationBackends(t *testing.T) { clearConfigEnv(t) path := writeConfig(t, ` database: /tmp/test.db server: public_url: http://localhost:8080 auth: - oidc: - issuer: https://example.com - client_id: c - client_secret: s - session_secret: yaml-session-secret-that-is-long-enough + idp_endpoint: https://example.com + audience: api + scope: stick:use notifications: smtp: - host: smtp.example.com @@ -312,18 +284,16 @@ notifications: } } -func TestLoad_TimezoneInvalid(t *testing.T) { +func TestLoadTimezoneInvalid(t *testing.T) { clearConfigEnv(t) path := writeConfig(t, ` database: /tmp/test.db server: public_url: http://localhost:8080 auth: - oidc: - issuer: https://example.com - client_id: c - client_secret: s - session_secret: yaml-session-secret-that-is-long-enough + idp_endpoint: https://example.com + audience: api + scope: stick:use timezone: Not/ATimezone `) if _, err := config.Load(context.Background(), config.YAMLProvider{Path: path}, config.EnvironmentProvider{}); err == nil || !strings.Contains(err.Error(), "timezone") { @@ -331,26 +301,16 @@ timezone: Not/ATimezone } } -func TestLoad_RejectsShortSessionSecret(t *testing.T) { - setRequiredEnv(t) - t.Setenv("STICK_AUTH_SESSION_SECRET", "too-short") - if _, err := config.Load(context.Background(), config.YAMLProvider{}, config.EnvironmentProvider{}); err == nil || !strings.Contains(err.Error(), "auth.session_secret") { - t.Fatalf("Load error = %v", err) - } -} - -func TestLoad_RejectsUnknownYAMLFields(t *testing.T) { +func TestLoadRejectsUnknownYAMLFields(t *testing.T) { clearConfigEnv(t) path := writeConfig(t, ` database: /tmp/test.db server: public_url: https://stick.example.com auth: - oidc: - issuer: https://issuer.example.com - client_id: client - client_secret: secret - session_secret: 0123456789abcdef0123456789abcdef + idp_endpoint: https://issuer.example.com + audience: api + scope: stick:use unknown_setting: true `) if _, err := config.Load(context.Background(), config.YAMLProvider{Path: path}, config.EnvironmentProvider{}); err == nil || !strings.Contains(err.Error(), "field unknown_setting not found") { @@ -358,7 +318,7 @@ unknown_setting: true } } -func TestLoad_RejectsInvalidURLs(t *testing.T) { +func TestLoadRejectsInvalidURLs(t *testing.T) { for _, test := range []struct { name string key string @@ -366,8 +326,8 @@ func TestLoad_RejectsInvalidURLs(t *testing.T) { }{ {name: "public URL scheme", key: "STICK_SERVER_PUBLIC_URL", value: "ftp://example.com"}, {name: "public URL transport", key: "STICK_SERVER_PUBLIC_URL", value: "http://example.com"}, - {name: "OIDC issuer scheme", key: "STICK_AUTH_OIDC_ISSUER", value: "file:///issuer"}, - {name: "OIDC issuer transport", key: "STICK_AUTH_OIDC_ISSUER", value: "http://issuer.example.com"}, + {name: "IDP endpoint scheme", key: "STICK_AUTH_IDP_ENDPOINT", value: "file:///issuer"}, + {name: "IDP endpoint transport", key: "STICK_AUTH_IDP_ENDPOINT", value: "http://issuer.example.com"}, } { t.Run(test.name, func(t *testing.T) { setRequiredEnv(t) @@ -379,13 +339,13 @@ func TestLoad_RejectsInvalidURLs(t *testing.T) { } } -func TestLoad_ExplicitPathNotFound(t *testing.T) { +func TestLoadExplicitPathNotFound(t *testing.T) { if _, err := config.Load(context.Background(), config.YAMLProvider{Path: "/nonexistent/path/config.yaml"}, config.EnvironmentProvider{}); err == nil { t.Fatal("expected error for explicit missing config") } } -func TestLoad_MissingRequired(t *testing.T) { +func TestLoadMissingRequired(t *testing.T) { clearConfigEnv(t) _, err := loadFromEnvWithoutRequired(t) if err == nil || !strings.Contains(err.Error(), "missing required config") { diff --git a/internal/config/environment_provider.go b/internal/config/environment_provider.go index 60130a9..f9a9f34 100644 --- a/internal/config/environment_provider.go +++ b/internal/config/environment_provider.go @@ -32,17 +32,14 @@ func (EnvironmentProvider) Apply(_ context.Context, config *Config) error { return err } } - if value := os.Getenv("STICK_AUTH_OIDC_ISSUER"); value != "" { - config.Auth.OIDC.Issuer = value + if value := os.Getenv("STICK_AUTH_IDP_ENDPOINT"); value != "" { + config.Auth.IDPEndpoint = value } - if value := os.Getenv("STICK_AUTH_OIDC_CLIENT_ID"); value != "" { - config.Auth.OIDC.ClientID = value + if value := os.Getenv("STICK_AUTH_AUDIENCE"); value != "" { + config.Auth.Audience = value } - if value := os.Getenv("STICK_AUTH_OIDC_CLIENT_SECRET"); value != "" { - config.Auth.OIDC.ClientSecret = value - } - if value := os.Getenv("STICK_AUTH_SESSION_SECRET"); value != "" { - setSessionSecret(config, value) + if value := os.Getenv("STICK_AUTH_SCOPE"); value != "" { + config.Auth.Scope = value } if value := os.Getenv("STICK_AUTH_ADMIN_EMAILS"); value != "" { config.Auth.AdminEmails = strings.Split(value, ",") diff --git a/internal/config/normalize.go b/internal/config/normalize.go index 1f0281b..d361e15 100644 --- a/internal/config/normalize.go +++ b/internal/config/normalize.go @@ -11,17 +11,22 @@ import ( "stick/internal/publicurl" ) -const minSessionSecretBytes = 32 - func normalize(config Config) (Config, error) { config.Server.ListenAddr = strings.TrimSpace(config.Server.ListenAddr) if config.Server.ListenAddr == "" { config.Server.ListenAddr = ":8080" } + if err := config.Server.PublicURL.Validate(); err != nil { + if err := setPublicURL(&config, "http://localhost"); err != nil { + return Config{}, err + } + } if config.Timezone == nil { config.Timezone = time.UTC } - config.Auth.SessionSecret = []byte(strings.TrimSpace(string(config.Auth.SessionSecret))) + config.Auth.IDPEndpoint = strings.TrimSpace(config.Auth.IDPEndpoint) + config.Auth.Audience = strings.TrimSpace(config.Auth.Audience) + config.Auth.Scope = strings.TrimSpace(config.Auth.Scope) notifications, err := normalizeNotifications(config.Notifications) if err != nil { @@ -38,15 +43,12 @@ func normalize(config Config) (Config, error) { if !config.Server.PublicURL.IsHTTPS() && !config.Server.PublicURL.IsLoopback() { return Config{}, fmt.Errorf("invalid server.public_url %q: HTTPS is required for non-local addresses", config.Server.PublicURL) } - issuer, err := parseHTTPURL("auth.oidc.issuer", config.Auth.OIDC.Issuer) + endpoint, err := parseHTTPURL("auth.idp_endpoint", config.Auth.IDPEndpoint) if err != nil { return Config{}, err } - if issuer.RawQuery != "" || issuer.Fragment != "" { - return Config{}, fmt.Errorf("invalid auth.oidc.issuer %q: must not include a query or fragment", config.Auth.OIDC.Issuer) - } - if err := validateSessionSecret(config.Auth.SessionSecret); err != nil { - return Config{}, err + if endpoint.RawQuery != "" || endpoint.Fragment != "" { + return Config{}, fmt.Errorf("invalid auth.idp_endpoint %q: must not include a query or fragment", config.Auth.IDPEndpoint) } config.Auth.AdminEmails = append([]string(nil), config.Auth.AdminEmails...) @@ -55,12 +57,10 @@ func normalize(config Config) (Config, error) { func validateRequired(config Config) error { required := map[string]bool{ - "database": strings.TrimSpace(config.Database.DSN) != "", - "server.public_url": config.Server.PublicURL.Validate() == nil, - "auth.oidc.issuer": strings.TrimSpace(config.Auth.OIDC.Issuer) != "", - "auth.oidc.client_id": strings.TrimSpace(config.Auth.OIDC.ClientID) != "", - "auth.oidc.client_secret": strings.TrimSpace(config.Auth.OIDC.ClientSecret) != "", - "auth.session_secret": len(config.Auth.SessionSecret) > 0, + "database": strings.TrimSpace(config.Database.DSN) != "", + "auth.idp_endpoint": strings.TrimSpace(config.Auth.IDPEndpoint) != "", + "auth.audience": strings.TrimSpace(config.Auth.Audience) != "", + "auth.scope": strings.TrimSpace(config.Auth.Scope) != "", } var missing []string for field, present := range required { @@ -150,13 +150,6 @@ func parseHTTPURL(name, value string) (*url.URL, error) { return parsed, nil } -func validateSessionSecret(secret []byte) error { - if len(secret) < minSessionSecretBytes { - return fmt.Errorf("auth.session_secret must be at least %d bytes", minSessionSecretBytes) - } - return nil -} - func setDatabase(config *Config, value string) error { database, err := normalizeDatabase(value) if err != nil { @@ -167,7 +160,7 @@ func setDatabase(config *Config, value string) error { } func setPublicURL(config *Config, value string) error { - publicURL, err := publicurl.Parse(value) + publicURL, err := publicurl.Parse(strings.TrimSpace(value)) if err != nil { return err } @@ -176,14 +169,10 @@ func setPublicURL(config *Config, value string) error { } func setTimezone(config *Config, value string) error { - location, err := time.LoadLocation(value) + location, err := time.LoadLocation(strings.TrimSpace(value)) if err != nil { return fmt.Errorf("invalid timezone %q: %w", value, err) } config.Timezone = location return nil } - -func setSessionSecret(config *Config, value string) { - config.Auth.SessionSecret = []byte(strings.TrimSpace(value)) -} diff --git a/internal/config/yaml_provider.go b/internal/config/yaml_provider.go index fffbba4..68e973b 100644 --- a/internal/config/yaml_provider.go +++ b/internal/config/yaml_provider.go @@ -83,15 +83,10 @@ type yamlServerConfig struct { } type yamlAuthConfig struct { - OIDC yamlOIDCConfig `yaml:"oidc" json:"oidc"` - SessionSecret *string `yaml:"session_secret" json:"session_secret"` - AdminEmails *[]string `yaml:"admin_emails" json:"admin_emails"` -} - -type yamlOIDCConfig struct { - Issuer *string `yaml:"issuer" json:"issuer"` - ClientID *string `yaml:"client_id" json:"client_id"` - ClientSecret *string `yaml:"client_secret" json:"client_secret"` + IDPEndpoint *string `yaml:"idp_endpoint" json:"idp_endpoint"` + Audience *string `yaml:"audience" json:"audience"` + Scope *string `yaml:"scope" json:"scope"` + AdminEmails *[]string `yaml:"admin_emails" json:"admin_emails"` } type yamlNotificationsConfig struct { @@ -137,17 +132,14 @@ func applyYAMLConfig(source yamlConfig, config *Config) error { if source.Server.ListenAddr != nil { config.Server.ListenAddr = strings.TrimSpace(*source.Server.ListenAddr) } - if source.Auth.OIDC.Issuer != nil { - config.Auth.OIDC.Issuer = *source.Auth.OIDC.Issuer - } - if source.Auth.OIDC.ClientID != nil { - config.Auth.OIDC.ClientID = *source.Auth.OIDC.ClientID + if source.Auth.IDPEndpoint != nil { + config.Auth.IDPEndpoint = *source.Auth.IDPEndpoint } - if source.Auth.OIDC.ClientSecret != nil { - config.Auth.OIDC.ClientSecret = *source.Auth.OIDC.ClientSecret + if source.Auth.Audience != nil { + config.Auth.Audience = *source.Auth.Audience } - if source.Auth.SessionSecret != nil { - setSessionSecret(config, *source.Auth.SessionSecret) + if source.Auth.Scope != nil { + config.Auth.Scope = *source.Auth.Scope } if source.Auth.AdminEmails != nil { config.Auth.AdminEmails = append([]string(nil), (*source.Auth.AdminEmails)...) diff --git a/internal/web/auth/handler.go b/internal/web/auth/handler.go deleted file mode 100644 index 535a68b..0000000 --- a/internal/web/auth/handler.go +++ /dev/null @@ -1,315 +0,0 @@ -// Package auth owns the browser's /auth OIDC routes. -package auth - -import ( - "context" - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "errors" - "io" - "net/http" - "strings" - "sync" - "time" - - coreauth "stick/internal/auth" - domain "stick/internal/core" - "stick/internal/publicurl" - "stick/internal/web/httpx" - "stick/internal/web/security" - - "github.com/coreos/go-oidc/v3/oidc" - "golang.org/x/oauth2" -) - -const ( - pkceStateCookie = "stick_state" - pkceVerifierCookie = "stick_pkce" - defaultOIDCDiscoveryTimeout = 10 * time.Second - defaultOIDCFailureBackoff = time.Second - maxOIDCFailureBackoff = 30 * time.Second -) - -// Handler serves the OIDC login, callback, and logout flow for the browser UI. -type Handler struct { - providerOptions coreauth.OIDCConfig - publicURL publicurl.URL - sessionSecret []byte - providerMu sync.Mutex - provider *oidc.Provider - oauth2 oauth2.Config - discoveryDone chan struct{} - lastDiscoveryErr error - retryDiscoveryAt time.Time - failureBackoff time.Duration - initialBackoff time.Duration - discover func(context.Context, string) (*oidc.Provider, error) - discoveryTimeout time.Duration - randomReader io.Reader -} - -// OIDCHandler is the descriptive name retained by the original API. -type OIDCHandler = Handler - -// SessionCookieName exposes the shared session cookie name to authentication -// package callers without coupling them to the root composition package. -func SessionCookieName() string { return security.SessionCookieName() } - -// NewOIDCHandler returns an OIDC handler with deferred provider discovery. -func NewOIDCHandler(providerOptions coreauth.OIDCConfig, publicURL publicurl.URL, sessionSecret []byte) *Handler { - // Resolve all derived values now so an invalid zero-value PublicURL fails at - // composition rather than during the first authentication request. - _ = httpx.Absolute(publicURL, "/auth/callback") - h := &Handler{ - providerOptions: providerOptions, - publicURL: publicURL, - sessionSecret: append([]byte(nil), sessionSecret...), - discover: oidc.NewProvider, - discoveryTimeout: defaultOIDCDiscoveryTimeout, - randomReader: rand.Reader, - initialBackoff: defaultOIDCFailureBackoff, - } - // Provider discovery is deferred to first use to allow startup without network. - return h -} - -// Login begins the OIDC authorization flow. -func (h *Handler) Login(w http.ResponseWriter, r *http.Request) { - _, oauthConfig, err := h.providerConfig(r.Context()) - if err != nil { - h.internalError(w, r, "discover OIDC provider", err, "OIDC provider unavailable", http.StatusServiceUnavailable) - return - } - - verifier, err := randomBase64(h.randomReader, 32) - if err != nil { - h.internalError(w, r, "generate PKCE verifier", err, "failed to generate PKCE verifier", http.StatusInternalServerError) - return - } - state, err := randomBase64(h.randomReader, 16) - if err != nil { - h.internalError(w, r, "generate OAuth state", err, "failed to generate OAuth state", http.StatusInternalServerError) - return - } - - sum := sha256.Sum256([]byte(verifier)) - challenge := base64.RawURLEncoding.EncodeToString(sum[:]) - path := httpx.CookiePath(h.publicURL) - // Remove cookies created by older root-mounted deployments. Without this, - // a browser can send both the stale Path=/ cookie and the current mounted - // cookie; net/http may then read the stale value and reject the callback. - if path != "/" { - clearCookies(w, "/", security.SessionCookieName(), pkceStateCookie, pkceVerifierCookie) - } - setCookie(w, pkceStateCookie, state, 10*time.Minute, h.publicURL.IsHTTPS(), path) - setCookie(w, pkceVerifierCookie, verifier, 10*time.Minute, h.publicURL.IsHTTPS(), path) - - redirectURL := oauthConfig.AuthCodeURL(state, - oauth2.SetAuthURLParam("code_challenge", challenge), - oauth2.SetAuthURLParam("code_challenge_method", "S256"), - ) - http.Redirect(w, r, redirectURL, http.StatusFound) -} - -// Callback completes the OIDC authorization flow and creates a session. -func (h *Handler) Callback(w http.ResponseWriter, r *http.Request) { - provider, oauthConfig, err := h.providerConfig(r.Context()) - if err != nil { - h.internalError(w, r, "discover OIDC provider", err, "OIDC provider unavailable", http.StatusServiceUnavailable) - return - } - - stateCookie, err := r.Cookie(pkceStateCookie) - if err != nil || stateCookie.Value != r.URL.Query().Get("state") { - http.Error(w, "invalid state", http.StatusBadRequest) - return - } - verifierCookie, err := r.Cookie(pkceVerifierCookie) - if err != nil { - http.Error(w, "missing PKCE verifier", http.StatusBadRequest) - return - } - - token, err := oauthConfig.Exchange(r.Context(), r.URL.Query().Get("code"), - oauth2.SetAuthURLParam("code_verifier", verifierCookie.Value)) - if err != nil { - h.internalError(w, r, "exchange OIDC token", err, "authentication failed", http.StatusInternalServerError) - return - } - rawIDToken, ok := token.Extra("id_token").(string) - if !ok { - h.internalError(w, r, "read OIDC ID token", errors.New("token response did not include id_token"), "authentication failed", http.StatusInternalServerError) - return - } - - verifier := provider.Verifier(&oidc.Config{ClientID: h.providerOptions.ClientID}) - idToken, err := verifier.Verify(r.Context(), rawIDToken) - if err != nil { - h.internalError(w, r, "verify OIDC ID token", err, "authentication failed", http.StatusInternalServerError) - return - } - var claims oidcClaims - if err := idToken.Claims(&claims); err != nil { - h.internalError(w, r, "parse OIDC claims", err, "authentication failed", http.StatusInternalServerError) - return - } - - identity, err := identityFromOIDCClaims(claims) - if err != nil { - h.internalError(w, r, "validate OIDC claims", err, "authentication failed", http.StatusInternalServerError) - return - } - jwtString, err := coreauth.Issue(identity, h.sessionSecret) - if err != nil { - h.internalError(w, r, "issue session token", err, "authentication failed", http.StatusInternalServerError) - return - } - - path := httpx.CookiePath(h.publicURL) - setCookie(w, security.SessionCookieName(), jwtString, coreauth.SessionTTL, h.publicURL.IsHTTPS(), path) - clearCookies(w, path, pkceStateCookie, pkceVerifierCookie) - if path != "/" { - clearCookies(w, "/", security.SessionCookieName(), pkceStateCookie, pkceVerifierCookie) - } - http.Redirect(w, r, httpx.Path(h.publicURL, "/"), http.StatusFound) -} - -// Logout clears the authentication cookies and redirects to login. -func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) { - path := httpx.CookiePath(h.publicURL) - clearCookies(w, path, security.SessionCookieName(), pkceStateCookie, pkceVerifierCookie) - if path != "/" { - clearCookies(w, "/", security.SessionCookieName(), pkceStateCookie, pkceVerifierCookie) - } - http.Redirect(w, r, httpx.Path(h.publicURL, "/auth/login"), http.StatusFound) -} - -type oidcClaims struct { - Sub string `json:"sub"` - Name string `json:"name"` - Email string `json:"email"` - EmailVerified bool `json:"email_verified"` -} - -func identityFromOIDCClaims(cl oidcClaims) (domain.Identity, error) { - if strings.TrimSpace(cl.Sub) == "" { - return domain.Identity{}, errors.New("oidc subject is required") - } - return domain.Identity{ - Sub: cl.Sub, - Name: cl.Name, - Email: cl.Email, - EmailVerified: cl.EmailVerified, - }, nil -} - -func (h *Handler) internalError(w http.ResponseWriter, r *http.Request, operation string, err error, message string, status int) { - httpx.LogError(r.Context(), "authentication request failed", operation, err) - http.Error(w, message, status) -} - -func randomBase64(reader io.Reader, n int) (string, error) { - b := make([]byte, n) - if _, err := io.ReadFull(reader, b); err != nil { - return "", err - } - return base64.RawURLEncoding.EncodeToString(b), nil -} - -func setCookie(w http.ResponseWriter, name, value string, ttl time.Duration, secure bool, path string) { - http.SetCookie(w, &http.Cookie{ - Name: name, - Value: value, - Path: path, - MaxAge: int(ttl.Seconds()), - HttpOnly: true, - Secure: secure, - SameSite: http.SameSiteLaxMode, - }) -} - -func clearCookies(w http.ResponseWriter, path string, names ...string) { - for _, name := range names { - http.SetCookie(w, &http.Cookie{Name: name, Path: path, MaxAge: -1}) - } -} - -func (h *Handler) providerConfig(ctx context.Context) (*oidc.Provider, oauth2.Config, error) { - for { - h.providerMu.Lock() - if h.provider != nil { - provider, oauthCfg := h.provider, h.oauth2 - h.providerMu.Unlock() - return provider, oauthCfg, nil - } - if h.lastDiscoveryErr != nil && time.Now().Before(h.retryDiscoveryAt) { - err := h.lastDiscoveryErr - h.providerMu.Unlock() - return nil, oauth2.Config{}, err - } - if done := h.discoveryDone; done != nil { - h.providerMu.Unlock() - select { - case <-done: - continue - case <-ctx.Done(): - return nil, oauth2.Config{}, ctx.Err() - } - } - done := make(chan struct{}) - h.discoveryDone = done - h.providerMu.Unlock() - - provider, oauthCfg, err := h.discoverProvider(ctx) - - h.providerMu.Lock() - if err == nil { - h.provider = provider - h.oauth2 = oauthCfg - h.lastDiscoveryErr = nil - h.retryDiscoveryAt = time.Time{} - h.failureBackoff = 0 - } else { - h.lastDiscoveryErr = err - h.failureBackoff = nextDiscoveryBackoff(h.failureBackoff, h.initialBackoff) - h.retryDiscoveryAt = time.Now().Add(h.failureBackoff) - } - h.discoveryDone = nil - close(done) - h.providerMu.Unlock() - return provider, oauthCfg, err - } -} - -func (h *Handler) discoverProvider(parent context.Context) (*oidc.Provider, oauth2.Config, error) { - // Discovery is shared by concurrent callers, so the first caller canceling - // must not cancel the single in-flight operation for every waiter. - discoveryCtx, cancel := context.WithTimeout(context.WithoutCancel(parent), h.discoveryTimeout) - defer cancel() - provider, err := h.discover(discoveryCtx, h.providerOptions.Issuer) - if err != nil { - return nil, oauth2.Config{}, err - } - oauthCfg := oauth2.Config{ - ClientID: h.providerOptions.ClientID, - ClientSecret: h.providerOptions.ClientSecret, - Endpoint: provider.Endpoint(), - RedirectURL: httpx.Absolute(h.publicURL, "/auth/callback"), - Scopes: []string{oidc.ScopeOpenID, "profile", "email"}, - } - return provider, oauthCfg, nil -} - -func nextDiscoveryBackoff(current, initial time.Duration) time.Duration { - if current <= 0 { - if initial > maxOIDCFailureBackoff { - return maxOIDCFailureBackoff - } - return initial - } - if current >= maxOIDCFailureBackoff/2 { - return maxOIDCFailureBackoff - } - return current * 2 -} diff --git a/internal/web/auth/oidc_test.go b/internal/web/auth/oidc_test.go deleted file mode 100644 index 62b9e01..0000000 --- a/internal/web/auth/oidc_test.go +++ /dev/null @@ -1,710 +0,0 @@ -package auth - -import ( - "bytes" - "context" - "crypto/rand" - "crypto/rsa" - "encoding/base64" - "encoding/json" - "errors" - "io" - "log/slog" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "stick/internal/auth" - "stick/internal/publicurl" - "stick/internal/web/httpx" - - "github.com/coreos/go-oidc/v3/oidc" - "github.com/golang-jwt/jwt/v5" - "golang.org/x/oauth2" -) - -func TestHandler_LoginRedirects(t *testing.T) { - h := NewOIDCHandler(auth.OIDCConfig{ - ClientID: "client-id", - ClientSecret: "client-secret", - }, authPublicURL(t, "http://localhost:8080", ""), []byte("secret-32-bytes-minimum-length!!")) - h.provider = &oidc.Provider{} - h.oauth2 = oauth2.Config{ - ClientID: "client-id", - ClientSecret: "client-secret", - RedirectURL: "http://localhost:8080/auth/callback", - Endpoint: oauth2.Endpoint{AuthURL: "https://accounts.example.com/authorize"}, - } - h.randomReader = bytes.NewReader(make([]byte, 48)) - - req := httptest.NewRequest(http.MethodGet, "/auth/login", nil) - rr := httptest.NewRecorder() - h.Login(rr, req) - - if rr.Code != http.StatusFound { - t.Fatalf("status = %d, want %d: %s", rr.Code, http.StatusFound, rr.Body.String()) - } - location, err := url.Parse(rr.Header().Get("Location")) - if err != nil { - t.Fatalf("parse redirect: %v", err) - } - if got := location.Scheme + "://" + location.Host + location.Path; got != "https://accounts.example.com/authorize" { - t.Errorf("redirect endpoint = %q", got) - } - if got := location.Query().Get("redirect_uri"); got != "http://localhost:8080/auth/callback" { - t.Errorf("redirect_uri = %q", got) - } - if got := location.Query().Get("code_challenge_method"); got != "S256" { - t.Errorf("code_challenge_method = %q, want S256", got) - } - if got := location.Query().Get("code_challenge"); got == "" { - t.Error("code_challenge is empty") - } -} - -func TestIdentityFromOIDCClaims_RequiresSubject(t *testing.T) { - _, err := identityFromOIDCClaims(oidcClaims{ - Name: "Alice", - Email: "alice@example.com", - EmailVerified: true, - }) - if err == nil { - t.Fatal("expected missing OIDC subject to be rejected") - } -} - -func TestIdentityFromOIDCClaims_PreservesVerifiedEmail(t *testing.T) { - identity, err := identityFromOIDCClaims(oidcClaims{ - Sub: "user123", - Email: "alice@example.com", - EmailVerified: true, - }) - if err != nil { - t.Fatalf("identityFromOIDCClaims: %v", err) - } - if !identity.EmailVerified { - t.Fatal("expected email_verified to be preserved") - } -} - -func TestProviderDiscoveryRetriesAfterFailure(t *testing.T) { - h := NewOIDCHandler(auth.OIDCConfig{Issuer: "https://accounts.example.com"}, authPublicURL(t, "http://example.test", ""), nil) - h.initialBackoff = time.Nanosecond - var calls int - h.discover = func(context.Context, string) (*oidc.Provider, error) { - calls++ - if calls == 1 { - return nil, errors.New("temporary discovery failure") - } - return &oidc.Provider{}, nil - } - - if _, _, err := h.providerConfig(context.Background()); err == nil { - t.Fatal("first discovery unexpectedly succeeded") - } - time.Sleep(time.Microsecond) - provider, _, err := h.providerConfig(context.Background()) - if err != nil { - t.Fatalf("second discovery failed: %v", err) - } - if provider == nil { - t.Fatal("second discovery returned a nil provider") - } - if _, _, err := h.providerConfig(context.Background()); err != nil { - t.Fatalf("cached provider lookup failed: %v", err) - } - if calls != 2 { - t.Fatalf("discovery called %d times, want 2", calls) - } -} - -func TestProviderDiscoverySingleFlightDoesNotHoldMutexDuringNetworkIO(t *testing.T) { - h := NewOIDCHandler(auth.OIDCConfig{Issuer: "https://accounts.example.com"}, authPublicURL(t, "http://example.test", ""), nil) - started := make(chan struct{}) - release := make(chan struct{}) - var calls atomic.Int32 - h.discover = func(context.Context, string) (*oidc.Provider, error) { - if calls.Add(1) == 1 { - close(started) - } - <-release - return &oidc.Provider{}, nil - } - - const callers = 20 - var wg sync.WaitGroup - wg.Add(callers) - for range callers { - go func() { - defer wg.Done() - if _, _, err := h.providerConfig(context.Background()); err != nil { - t.Errorf("providerConfig: %v", err) - } - }() - } - <-started - // The state mutex remains independently acquirable while discovery blocks. - locked := make(chan bool, 1) - go func() { - h.providerMu.Lock() - providerWasNil := h.provider == nil - h.providerMu.Unlock() - locked <- providerWasNil - }() - select { - case providerWasNil := <-locked: - if !providerWasNil { - t.Fatal("provider was populated before discovery completed") - } - case <-time.After(time.Second): - t.Fatal("provider mutex was held during discovery network I/O") - } - close(release) - wg.Wait() - if got := calls.Load(); got != 1 { - t.Fatalf("discovery calls = %d, want 1", got) - } -} - -func TestProviderDiscoveryFailureBackoffSuppressesRepeatedNetworkCalls(t *testing.T) { - h := NewOIDCHandler(auth.OIDCConfig{Issuer: "https://accounts.example.com"}, authPublicURL(t, "http://example.test", ""), nil) - h.initialBackoff = time.Hour - var calls int - h.discover = func(context.Context, string) (*oidc.Provider, error) { - calls++ - return nil, errors.New("provider unavailable") - } - for range 5 { - if _, _, err := h.providerConfig(context.Background()); err == nil { - t.Fatal("discovery unexpectedly succeeded") - } - } - if calls != 1 { - t.Fatalf("discovery calls during backoff = %d, want 1", calls) - } -} - -func TestProviderDiscoveryUsesBoundedContext(t *testing.T) { - h := NewOIDCHandler(auth.OIDCConfig{Issuer: "https://accounts.example.com"}, authPublicURL(t, "http://example.test", ""), nil) - h.discoveryTimeout = 10 * time.Millisecond - h.discover = func(ctx context.Context, _ string) (*oidc.Provider, error) { - deadline, ok := ctx.Deadline() - if !ok { - t.Error("discovery context has no deadline") - } else if remaining := time.Until(deadline); remaining > h.discoveryTimeout { - t.Errorf("discovery deadline is too far away: %v", remaining) - } - - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-time.After(time.Second): - return nil, errors.New("discovery context was not canceled") - } - } - - started := time.Now() - _, _, err := h.providerConfig(context.Background()) - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("discovery error = %v, want context deadline exceeded", err) - } - if elapsed := time.Since(started); elapsed > time.Second { - t.Fatalf("discovery took too long: %v", elapsed) - } -} - -func TestLogin_UsesBasePathForRedirectURLAndCookies(t *testing.T) { - tests := []struct { - name string - baseURL string - basePath string - redirectURL string - wantPath string - wantSecure bool - }{ - {name: "root", baseURL: "http://localhost:8080", redirectURL: "http://localhost:8080/auth/callback", wantPath: "/"}, - {name: "mounted", baseURL: "http://localhost:8080", basePath: "/basepath", redirectURL: "http://localhost:8080/basepath/auth/callback", wantPath: "/basepath"}, - {name: "secure nested mount", baseURL: "https://example.com", basePath: "/ops/stick", redirectURL: "https://example.com/ops/stick/auth/callback", wantPath: "/ops/stick", wantSecure: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - h := NewOIDCHandler(auth.OIDCConfig{}, authPublicURL(t, tt.baseURL, tt.basePath), nil) - h.provider = &oidc.Provider{} - h.oauth2 = oauth2.Config{ - RedirectURL: tt.redirectURL, - Endpoint: oauth2.Endpoint{AuthURL: "https://issuer.example/auth"}, - } - h.randomReader = bytes.NewReader(make([]byte, 48)) - - rr := httptest.NewRecorder() - h.Login(rr, httptest.NewRequest(http.MethodGet, "/auth/login", nil)) - if rr.Code != http.StatusFound { - t.Fatalf("status = %d, want %d", rr.Code, http.StatusFound) - } - location, err := url.Parse(rr.Header().Get("Location")) - if err != nil { - t.Fatalf("parse redirect location: %v", err) - } - if got := location.Query().Get("redirect_uri"); got != tt.redirectURL { - t.Errorf("redirect_uri = %q, want %q", got, tt.redirectURL) - } - cookies := rr.Result().Cookies() - wantCookies := 2 - if tt.wantPath != "/" { - wantCookies = 5 // legacy root session/OAuth deletions plus two current cookies - } - if len(cookies) != wantCookies { - t.Fatalf("got %d cookies, want %d", len(cookies), wantCookies) - } - currentCookies := 0 - legacySessionCleared := false - for _, cookie := range cookies { - if cookie.Path == tt.wantPath && cookie.MaxAge > 0 { - currentCookies++ - if cookie.Secure != tt.wantSecure { - t.Errorf("cookie %s Secure = %v, want %v", cookie.Name, cookie.Secure, tt.wantSecure) - } - continue - } - if tt.wantPath != "/" && cookie.Path == "/" && cookie.MaxAge != -1 { - t.Errorf("legacy cookie %s MaxAge = %d, want -1", cookie.Name, cookie.MaxAge) - } - if tt.wantPath != "/" && cookie.Name == SessionCookieName() && cookie.Path == "/" && cookie.MaxAge == -1 { - legacySessionCleared = true - } - if cookie.Path != tt.wantPath && cookie.Path != "/" { - t.Errorf("cookie %s Path = %q, want %q or legacy /", cookie.Name, cookie.Path, tt.wantPath) - } - } - if currentCookies != 2 { - t.Errorf("got %d current cookies, want 2", currentCookies) - } - if tt.wantPath != "/" && !legacySessionCleared { - t.Error("login did not clear the legacy root-scoped session") - } - }) - } -} - -func TestLogout_UsesBasePathForRedirectAndClearingCookie(t *testing.T) { - tests := []struct { - name string - basePath string - wantPath string - wantURL string - }{ - {name: "root", wantPath: "/", wantURL: "/auth/login"}, - {name: "mounted", basePath: "/basepath", wantPath: "/basepath", wantURL: "/basepath/auth/login"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - h := NewOIDCHandler(auth.OIDCConfig{}, authPublicURL(t, "http://example.test", tt.basePath), nil) - rr := httptest.NewRecorder() - h.Logout(rr, httptest.NewRequest(http.MethodPost, "/auth/logout", nil)) - - if rr.Code != http.StatusFound { - t.Fatalf("status = %d, want %d", rr.Code, http.StatusFound) - } - if got := rr.Header().Get("Location"); got != tt.wantURL { - t.Errorf("Location = %q, want %q", got, tt.wantURL) - } - cookies := rr.Result().Cookies() - wantCookies := 3 - if tt.wantPath != "/" { - wantCookies = 6 - } - if len(cookies) != wantCookies { - t.Fatalf("got %d cookies, want %d", len(cookies), wantCookies) - } - cleared := make(map[string]bool) - for _, cookie := range cookies { - if cookie.MaxAge != -1 || cookie.Path != tt.wantPath && cookie.Path != "/" { - t.Errorf("clearing cookie = %+v", cookie) - } - cleared[cookie.Name+"|"+cookie.Path] = true - } - for _, name := range []string{SessionCookieName(), pkceStateCookie, pkceVerifierCookie} { - if !cleared[name+"|"+tt.wantPath] { - t.Errorf("cookie %s was not cleared at %s", name, tt.wantPath) - } - if tt.wantPath != "/" && !cleared[name+"|/"] { - t.Errorf("legacy root cookie %s was not cleared", name) - } - } - }) - } -} - -func TestCallback_UsesBasePathForSuccessRedirectAndCookies(t *testing.T) { - key, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Fatalf("GenerateKey: %v", err) - } - - var idToken string - var providerServer *httptest.Server - providerServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch r.URL.Path { - case "/.well-known/openid-configuration": - _ = json.NewEncoder(w).Encode(map[string]string{ - "issuer": providerServer.URL, - "authorization_endpoint": providerServer.URL + "/authorize", - "token_endpoint": providerServer.URL + "/token", - "jwks_uri": providerServer.URL + "/keys", - }) - case "/token": - _ = json.NewEncoder(w).Encode(map[string]any{ - "access_token": "access-token", - "token_type": "Bearer", - "id_token": idToken, - "expires_in": 3600, - }) - case "/keys": - _ = json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]string{{ - "kty": "RSA", - "use": "sig", - "alg": "RS256", - "kid": "test-key", - "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()), - "e": base64.RawURLEncoding.EncodeToString([]byte{1, 0, 1}), - }}}) - default: - http.NotFound(w, r) - } - })) - t.Cleanup(providerServer.Close) - - signed := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ - "iss": providerServer.URL, - "sub": "user-1", - "aud": "client-id", - "exp": time.Now().Add(time.Hour).Unix(), - "iat": time.Now().Unix(), - "name": "Alice", - "email": "alice@example.com", - "email_verified": true, - }, nil) - signed.Header["kid"] = "test-key" - idToken, err = signed.SignedString(key) - if err != nil { - t.Fatalf("SignedString: %v", err) - } - - h := NewOIDCHandler(auth.OIDCConfig{ - Issuer: providerServer.URL, - ClientID: "client-id", - ClientSecret: "client-secret", - }, authPublicURL(t, "http://localhost:8080", "/basepath"), []byte("secret-32-bytes-minimum-length!!")) - req := httptest.NewRequest(http.MethodGet, "/auth/callback?code=code&state=state", nil) - req.AddCookie(&http.Cookie{Name: pkceStateCookie, Value: "state"}) - req.AddCookie(&http.Cookie{Name: pkceVerifierCookie, Value: "verifier"}) - rr := httptest.NewRecorder() - h.Callback(rr, req) - - if rr.Code != http.StatusFound { - t.Fatalf("status = %d, want %d: %s", rr.Code, http.StatusFound, rr.Body.String()) - } - if got := rr.Header().Get("Location"); got != "/basepath/" { - t.Errorf("Location = %q, want /basepath/", got) - } - clearedLegacySession := false - for _, cookie := range rr.Result().Cookies() { - if cookie.Path == "/" && cookie.MaxAge == -1 { - if cookie.Name == SessionCookieName() { - clearedLegacySession = true - } - continue // legacy root OAuth cookie cleanup - } - if cookie.Path != "/basepath" { - t.Errorf("cookie %s Path = %q, want /basepath or legacy /", cookie.Name, cookie.Path) - } - } - if !clearedLegacySession { - t.Error("callback did not clear the legacy root-scoped session") - } -} - -func TestCallbackRejectsInvalidStateAndMissingVerifier(t *testing.T) { - tests := []struct { - name string - queryState string - stateCookie string - verifier string - wantBody string - }{ - { - name: "mismatched state", - queryState: "different", - stateCookie: "expected", - wantBody: "invalid state\n", - }, - { - name: "missing verifier", - queryState: "expected", - stateCookie: "expected", - wantBody: "missing PKCE verifier\n", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - h := NewOIDCHandler(auth.OIDCConfig{}, authPublicURL(t, "http://example.test", ""), nil) - h.provider = &oidc.Provider{} - h.oauth2 = oauth2.Config{} - request := httptest.NewRequest(http.MethodGet, "/auth/callback?code=code&state="+tt.queryState, nil) - request.AddCookie(&http.Cookie{Name: pkceStateCookie, Value: tt.stateCookie}) - if tt.verifier != "" { - request.AddCookie(&http.Cookie{Name: pkceVerifierCookie, Value: tt.verifier}) - } - recorder := httptest.NewRecorder() - - h.Callback(recorder, request) - - if recorder.Code != http.StatusBadRequest || recorder.Body.String() != tt.wantBody { - t.Fatalf("response = %d %q, want 400 %q", recorder.Code, recorder.Body.String(), tt.wantBody) - } - }) - } -} - -func TestCallbackRejectsTokenExchangeFailureAndMissingIDToken(t *testing.T) { - tests := []struct { - name string - status int - body string - wantStatus int - wantBody string - }{ - { - name: "token exchange failure", - status: http.StatusBadGateway, - body: "upstream failure", - wantStatus: http.StatusInternalServerError, - wantBody: "authentication failed\n", - }, - { - name: "missing id token", - status: http.StatusOK, - body: `{"access_token":"access-token","token_type":"Bearer"}`, - wantStatus: http.StatusInternalServerError, - wantBody: "authentication failed\n", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - h, tokenServer := callbackHandlerWithTokenEndpoint(t, tt.status, tt.body) - defer tokenServer.Close() - request := callbackRequest("expected", "verifier") - recorder := httptest.NewRecorder() - - h.Callback(recorder, request) - - if recorder.Code != tt.wantStatus || recorder.Body.String() != tt.wantBody { - t.Fatalf("response = %d %q, want %d %q", recorder.Code, recorder.Body.String(), tt.wantStatus, tt.wantBody) - } - }) - } -} - -func TestCallbackRejectsOIDCClaimsWithoutSubject(t *testing.T) { - key, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Fatalf("GenerateKey: %v", err) - } - var idToken string - var providerServer *httptest.Server - providerServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch r.URL.Path { - case "/.well-known/openid-configuration": - _ = json.NewEncoder(w).Encode(map[string]string{ - "issuer": providerServer.URL, - "authorization_endpoint": providerServer.URL + "/authorize", - "token_endpoint": providerServer.URL + "/token", - "jwks_uri": providerServer.URL + "/keys", - }) - case "/token": - _ = json.NewEncoder(w).Encode(map[string]any{"access_token": "access-token", "token_type": "Bearer", "id_token": idToken}) - case "/keys": - _ = json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]string{{ - "kty": "RSA", "use": "sig", "alg": "RS256", "kid": "test-key", - "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()), - "e": base64.RawURLEncoding.EncodeToString([]byte{1, 0, 1}), - }}}) - default: - http.NotFound(w, r) - } - })) - defer providerServer.Close() - - signed := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ - "iss": providerServer.URL, - "aud": "client-id", - "exp": time.Now().Add(time.Hour).Unix(), - "iat": time.Now().Unix(), - "name": "Alice", "email": "alice@example.com", "email_verified": true, - }) - signed.Header["kid"] = "test-key" - idToken, err = signed.SignedString(key) - if err != nil { - t.Fatalf("SignedString: %v", err) - } - - h := NewOIDCHandler(auth.OIDCConfig{ - Issuer: providerServer.URL, - ClientID: "client-id", - ClientSecret: "client-secret", - }, authPublicURL(t, "http://example.test", ""), []byte("secret-32-bytes-minimum-length!!")) - recorder := httptest.NewRecorder() - h.Callback(recorder, callbackRequest("expected", "verifier")) - - if recorder.Code != http.StatusInternalServerError || recorder.Body.String() != "authentication failed\n" { - t.Fatalf("response = %d %q, want 500 authentication failed", recorder.Code, recorder.Body.String()) - } -} - -func callbackHandlerWithTokenEndpoint(t *testing.T, status int, body string) (*OIDCHandler, *httptest.Server) { - t.Helper() - tokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(status) - _, _ = io.WriteString(w, body) - })) - h := NewOIDCHandler(auth.OIDCConfig{ - ClientID: "client-id", - ClientSecret: "client-secret", - }, authPublicURL(t, "http://example.test", ""), []byte("secret-32-bytes-minimum-length!!")) - h.provider = &oidc.Provider{} - h.oauth2 = oauth2.Config{ - ClientID: "client-id", - ClientSecret: "client-secret", - Endpoint: oauth2.Endpoint{TokenURL: tokenServer.URL}, - } - return h, tokenServer -} - -func callbackRequest(state, verifier string) *http.Request { - request := httptest.NewRequest(http.MethodGet, "/auth/callback?code=code&state="+state, nil) - request.AddCookie(&http.Cookie{Name: pkceStateCookie, Value: state}) - request.AddCookie(&http.Cookie{Name: pkceVerifierCookie, Value: verifier}) - return request -} - -type randomErrorReader struct { - err error -} - -func (r randomErrorReader) Read([]byte) (int, error) { - return 0, r.err -} - -type partialRandomErrorReader struct { - err error -} - -func (r partialRandomErrorReader) Read(p []byte) (int, error) { - if len(p) == 0 { - return 0, r.err - } - p[0] = 1 - return 1, r.err -} - -func TestRandomBase64ReturnsErrorWithoutPartialValue(t *testing.T) { - wantErr := errors.New("random source failed") - - got, err := randomBase64(partialRandomErrorReader{err: wantErr}, 32) - if !errors.Is(err, wantErr) { - t.Fatalf("randomBase64 error = %v, want %v", err, wantErr) - } - if got != "" { - t.Fatalf("randomBase64 value = %q, want empty value on error", got) - } -} - -func TestLoginAbortsWhenRandomGenerationFails(t *testing.T) { - wantErr := errors.New("random source failed") - tests := []struct { - name string - reader io.Reader - wantResponse string - }{ - { - name: "PKCE verifier", - reader: partialRandomErrorReader{err: wantErr}, - wantResponse: "failed to generate PKCE verifier", - }, - { - name: "OAuth state", - reader: io.MultiReader( - bytes.NewReader(make([]byte, 32)), - randomErrorReader{err: wantErr}, - ), - wantResponse: "failed to generate OAuth state", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - h := NewOIDCHandler(auth.OIDCConfig{}, authPublicURL(t, "http://example.test", ""), nil) - h.provider = &oidc.Provider{} - h.oauth2 = oauth2.Config{Endpoint: oauth2.Endpoint{AuthURL: "https://issuer.example/auth"}} - h.randomReader = tt.reader - - rr := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/auth/login", nil) - h.Login(rr, req) - - if rr.Code != http.StatusInternalServerError { - t.Fatalf("status = %d, want %d", rr.Code, http.StatusInternalServerError) - } - if !strings.Contains(rr.Body.String(), tt.wantResponse) { - t.Fatalf("response body = %q, want %q", rr.Body.String(), tt.wantResponse) - } - if location := rr.Header().Get("Location"); location != "" { - t.Fatalf("unexpected redirect location %q", location) - } - if cookies := rr.Result().Cookies(); len(cookies) != 0 { - t.Fatalf("got %d cookies after random generation failure, want none", len(cookies)) - } - }) - } -} - -func TestLoginFailureLogIncludesContextRequestID(t *testing.T) { - var logs bytes.Buffer - previous := slog.Default() - slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) - t.Cleanup(func() { slog.SetDefault(previous) }) - h := NewOIDCHandler(auth.OIDCConfig{}, authPublicURL(t, "http://example.test", ""), nil) - h.provider = &oidc.Provider{} - h.oauth2 = oauth2.Config{Endpoint: oauth2.Endpoint{AuthURL: "https://issuer.example/auth"}} - h.randomReader = randomErrorReader{err: errors.New("random source failed")} - - rr := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/auth/login", nil) - req = req.WithContext(httpx.WithRequestID(req.Context(), "request-42")) - h.Login(rr, req) - - got := logs.String() - for _, want := range []string{`"msg":"authentication request failed"`, `"request_id":"request-42"`} { - if !strings.Contains(got, want) { - t.Errorf("authentication failure log = %q, want %s", got, want) - } - } -} - -func authPublicURL(t *testing.T, baseURL, basePath string) publicurl.URL { - t.Helper() - publicURL, err := publicurl.Parse(baseURL + basePath) - if err != nil { - t.Fatal(err) - } - return publicURL -} diff --git a/internal/web/auth/routes.go b/internal/web/auth/routes.go deleted file mode 100644 index 3a7327f..0000000 --- a/internal/web/auth/routes.go +++ /dev/null @@ -1,14 +0,0 @@ -package auth - -import ( - "net/http" - - "stick/internal/web/httpx" -) - -// Register registers the /auth routes. -func Register(router *httpx.Router, handler *Handler) { - router.HandleFunc(http.MethodGet, "/auth/login", handler.Login) - router.HandleFunc(http.MethodGet, "/auth/callback", handler.Callback) - router.HandleFunc(http.MethodPost, "/auth/logout", handler.Logout) -} diff --git a/internal/web/content/assets/styles.css b/internal/web/content/assets/styles.css deleted file mode 100644 index 79a2128..0000000 --- a/internal/web/content/assets/styles.css +++ /dev/null @@ -1,466 +0,0 @@ -:root { - --font-sans: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; - --bg: #1a2e1a; - --surface: #0f1f0f; - --text: #d4e8c2; - --text-bright: #e8f5d0; - --green-border: #3d6b2c; - --green: #4a7c35; - --green-muted: #7ab05a; - --green-bright: #8bc34a; - --green-title: #a8d878; - --green-button: #2d5a1e; - --amber-bg: #3a2810; - --amber-border: #7c5a2a; - --amber-text: #c8a060; - --teal-bg: #1a3a38; - --teal-border: #2a7c6e; - --teal-text: #4db6ac; - --red-bg: #2e1a1a; - --red-border: #7c2a2a; - --red-text: #e88080; - --pill-radius: 20px; -} - -* { box-sizing: border-box; margin: 0; padding: 0; } -html { font-size: 16px; } -body { - min-height: 100vh; - padding: 2.667em 1em 1.667em; - background-color: var(--bg); - background-image: radial-gradient(circle, rgba(255, 255, 255, .025) 1px, transparent 1px); - background-size: 28px 28px; - color: var(--text); - font-family: var(--font-sans); - font-size: 1.5em; -} -button, input { font-family: var(--font-sans); } - -.topbar { - position: fixed; - top: 14px; - right: 20px; - z-index: 100; - display: flex; - align-items: center; - gap: .568em; - color: #6b8f4a; - font-size: 1.1rem; -} -.topbar-email { font-size: .8em; } -.topbar form { display: inline; } -.topbar button { - padding: .364em 1.091em; - border: 1px solid var(--green-border); - border-radius: var(--pill-radius); - background: #1e3b1e; - color: var(--green); - font-size: .625em; - font-weight: 700; - cursor: pointer; -} -.topbar button:hover { background: var(--green-button); color: var(--green-bright); } -.back { - display: inline-flex; - align-items: center; - gap: .462em; - margin-bottom: 1.846em; - color: var(--green); - font-size: .542em; - font-weight: 700; - text-decoration: none; -} -.back:hover { color: var(--green-bright); } -.error { - margin-bottom: 1.231em; - padding: .769em 1.231em; - border: 1px solid var(--red-border); - border-radius: 8px; - background: #2a1010; - color: var(--red-text); - font-size: .542em; -} -.field-error { - color: var(--red-text); - font-size: .458em; -} -input[aria-invalid="true"] { border-color: var(--red-border); } -.sr-only { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; -} -.pill--admin { - padding: .3em 1em; - border: 1px solid #8b1a1a; - border-radius: var(--pill-radius); - background: #c0392b; - color: #fff; - font-size: .568em; - font-weight: 800; - letter-spacing: 1px; - text-transform: uppercase; -} - -/* Shared detail and creation page layout. */ -.container { max-width: 28.333em; margin: 0 auto; font-size: 1.25em; } -.page-header { display: flex; align-items: center; gap: .583em; margin-bottom: 1.167em; } -.new-stick-page .page-header { margin-bottom: 1em; } -.page-icon { font-size: 1.5em; } -.page-name { color: var(--green-title); font-size: 1.167em; font-weight: 800; } - -/* New stick form. */ -.create-form { - display: flex; - flex-direction: column; - gap: .583em; - padding: 1em; - border: 2px dashed var(--green-border); - border-radius: 14px; - background: var(--surface); -} -.form-label { - display: block; - margin-bottom: .364em; - color: var(--green); - font-size: .458em; - font-weight: 800; - letter-spacing: 1px; - text-transform: uppercase; -} -.form-input { - width: 100%; - padding: .714em 1.143em; - border: 1px solid var(--green-border); - border-radius: 10px; - outline: none; - background: var(--bg); - color: var(--text); - font-size: .583em; -} -.form-input::placeholder, .claim-form input::placeholder { color: #3d5a30; } -.form-hint { color: var(--green-muted); font-size: .458em; } -.form-actions { display: flex; align-items: center; gap: .5em; } -.btn-create { - padding: .667em 1.667em; - border: 2px solid var(--green); - border-radius: var(--pill-radius); - background: var(--green-button); - color: var(--green-bright); - font-size: .5em; - font-weight: 800; - cursor: pointer; -} -.btn-create:hover { background: var(--green); color: var(--text-bright); } -.btn-cancel { color: var(--green-muted); font-size: .5em; font-weight: 800; text-decoration: none; } -.btn-cancel:hover { color: var(--green-bright); } -.error-page { padding-top: 2em; } -.error-page p { margin-bottom: 1em; font-size: .583em; line-height: 1.6; } -.error-page .request-id { color: var(--green-muted); font-size: .458em; } -.error-page code { overflow-wrap: anywhere; } -.error-home { color: var(--green-bright); font-size: .5em; font-weight: 800; } - -/* Dashboard cards. */ -.grove { - display: grid; - width: 90vw; - max-width: 80em; - margin: 0 auto; - grid-template-columns: repeat(auto-fill, minmax(12em, 1fr)); - gap: .75em; -} -.stick-card { - position: relative; - display: flex; - min-height: 9em; - padding: .917em .833em .75em; - flex-direction: column; - gap: .417em; - border-radius: 16px; - color: inherit; - text-decoration: none; - cursor: pointer; - transition: transform .15s, box-shadow .15s; -} -.stick-card:hover { transform: translateY(-3px); box-shadow: 0 8px 24px rgba(0, 0, 0, .3); } -.stick-card.available { border: 2px solid var(--green); background: #1b3818; } -.stick-card.taken { border: 2px solid var(--amber-border); background: #2a1f10; } -.stick-card.mine { border: 2px solid var(--teal-border); background: #152e2a; } -.stick-card.new-stick { - min-height: 5em; - align-items: center; - justify-content: center; - border: 2px dashed #3a5a30; - background: none; -} -.stick-card.new-stick:hover { border-color: #6b8f4a; box-shadow: 0 8px 24px rgba(0, 0, 0, .3); } -.new-plus { color: #6ba84a; font-size: 1.333em; line-height: 1; } -.new-label { - margin-top: .6em; - color: var(--green-muted); - font-size: .417em; - font-weight: 800; - letter-spacing: 1px; - text-transform: uppercase; -} -.card-top { - display: flex; - align-items: flex-start; - justify-content: space-between; - padding-bottom: .417em; - border-bottom: 1px solid rgba(255, 255, 255, .05); -} -.card-top-right { display: flex; flex-direction: column; align-items: flex-end; gap: .208em; } -.pill-row { display: flex; align-items: center; gap: .333em; } -.stick-icon { font-size: 1.333em; line-height: 1; } -.grove .status-pill { - padding: .3em 1em; - border-radius: var(--pill-radius); - font-size: .521em; - font-weight: 800; - letter-spacing: 1px; - text-transform: uppercase; -} -.grove .available .status-pill { border: 1px solid var(--green); background: var(--green-button); color: var(--green-bright); } -.grove .taken .status-pill { border: 1px solid var(--amber-border); background: var(--amber-bg); color: var(--amber-text); } -.grove .mine .status-pill { border: 1px solid var(--teal-border); background: #1a3a36; color: var(--teal-text); } -.stick-duration { font-size: .505em; font-weight: 700; } -.taken .stick-duration { color: #a07850; } -.mine .stick-duration { color: #5ab69e; } -.stick-name { font-size: .708em; font-weight: 800; line-height: 1.2; } -.grove .available .stick-name { - display: flex; - flex: 1; - align-items: center; - justify-content: center; - color: var(--green-title); - font-size: 1.333em; - text-align: center; -} -.grove .taken .stick-name { color: var(--amber-text); font-size: .857em; } -.grove .mine .stick-name { color: var(--teal-text); font-size: .857em; } -.stick-meta { display: flex; flex: 1; flex-direction: column; font-size: .5em; line-height: 1.6; } -.stick-meta span { font-weight: 800; } -.grove .taken .stick-meta { color: #7a6040; font-size: .605em; } -.grove .mine .stick-meta { color: #3a8a80; font-size: .605em; } -.stick-meta em { font-style: italic; } -.card-footer { - position: relative; - z-index: 1; - margin-top: .167em; - padding-top: .5em; - border-top: 1px solid rgba(255, 255, 255, .05); -} -.mine .card-footer, .taken .card-footer { border-top: none; } -.card-link { position: absolute; z-index: 0; inset: 0; border-radius: 16px; } -.grove .btn, .grove .btn-notify, .grove .btn-notify-cancel { - display: block; - width: 100%; - padding: .583em 0; - border: 2px solid; - border-radius: var(--pill-radius); - font-size: .5em; - font-weight: 800; - text-align: center; - text-decoration: none; - cursor: pointer; -} -.grove .btn { transition: all .15s; } -.grove .btn-release { border-color: var(--teal-border); background: var(--teal-bg); color: var(--teal-text); } -.grove .btn-release:hover { background: var(--teal-border); color: #e0f7f4; } -.grove .btn-notify { border-color: var(--amber-border); background: var(--amber-bg); color: var(--amber-text); } -.grove .btn-notify:hover { background: var(--amber-border); color: #f5e0c0; } -.grove .btn-notify-cancel { border-color: var(--red-border); background: var(--red-bg); color: #c06060; } -.grove .btn-notify-cancel:hover { background: var(--red-border); color: #f5c0c0; } -.archived-section { width: 90vw; max-width: 80em; margin: 1.5em auto 0; } -.archived-heading { - margin-bottom: .75em; - color: var(--green-muted); - font-size: .5em; - font-weight: 800; - letter-spacing: 1.5px; - text-transform: uppercase; -} -.archived-list { display: flex; flex-wrap: wrap; gap: .5em; } -.archived-item { - display: flex; - align-items: center; - gap: .667em; - padding: .5em .667em; - border: 1px solid #2a4a22; - border-radius: 10px; - background: #101d10; - color: #7a9660; - font-size: .5em; -} -.archived-item a { color: var(--green-title); font-weight: 800; text-decoration: none; } -.archived-item form { display: inline; } -.archived-item button { padding: 0; border: 0; background: none; color: var(--green-bright); font: inherit; font-weight: 800; cursor: pointer; } - -/* Stick detail. */ -.page-title { display: flex; flex-direction: column; gap: .167em; } -.page-name-row { display: flex; align-items: center; justify-content: space-between; gap: .5em; } -.page-id { color: #5a8a50; font-family: monospace; font-size: .458em; letter-spacing: 1px; } -.detail-page .status-pill { - padding: .3em 1em; - border-radius: var(--pill-radius); - font-size: .417em; - font-weight: 800; - letter-spacing: 1px; - text-transform: uppercase; -} -.detail-page .status-pill.available { border: 1px solid var(--green); background: var(--green-button); color: var(--green-bright); } -.detail-page .status-pill.taken { border: 1px solid var(--amber-border); background: var(--amber-bg); color: var(--amber-text); } -.detail-page .status-pill.mine { border: 1px solid var(--teal-border); background: #1a3a36; color: var(--teal-text); } -.detail-page .status-pill.archived { border: 1px solid #5a6a50; background: #283026; color: #b0bea5; } -.state-banner { - display: flex; - align-items: center; - justify-content: space-between; - margin-bottom: 1.167em; - padding: .583em .75em; - border-radius: 12px; -} -.state-taken { border: 2px solid var(--amber-border); background: #2a1f10; } -.state-mine { border: 2px solid var(--teal-border); background: #152e2a; } -.state-archived { border: 2px solid #5a6a50; background: #20281f; } -.banner-label { font-size: .625em; font-weight: 700; } -.state-taken .banner-label { color: var(--amber-text); } -.state-mine .banner-label { color: var(--teal-text); } -.state-archived .banner-label { color: #b0bea5; } -.banner-meta { margin-top: .25em; font-size: .5em; font-style: italic; } -.state-taken .banner-meta { color: #7a6040; } -.state-mine .banner-meta { color: #3a8a80; } -.state-archived .banner-meta { color: #829078; } -.banner-since { margin-top: .182em; font-size: .458em; } -.state-taken .banner-since { color: #906040; } -.state-mine .banner-since { color: #3a8a80; } -.claim-form { - display: flex; - align-items: center; - gap: .417em; - margin-bottom: 1.167em; - padding: .833em; - border: 2px dashed var(--green-border); - border-radius: 14px; - background: var(--surface); - flex-wrap: wrap; -} -.claim-form input { - flex: 1; - padding: .615em 1.231em; - border: 1px solid var(--green-border); - border-radius: var(--pill-radius); - outline: none; - background: var(--bg); - color: var(--text); - font-size: .542em; -} -.claim-form .field-error { width: 100%; } -.detail-page .btn-claim, .detail-page .btn-release, .detail-page .btn-notify, .detail-page .btn-notify-cancel { - padding: .667em 1.5em; - border: 2px solid; - border-radius: var(--pill-radius); - font-size: .5em; - font-weight: 800; - cursor: pointer; -} -.detail-page .btn-claim { border-color: var(--green); background: var(--green-button); color: var(--green-bright); white-space: nowrap; } -.detail-page .btn-claim:hover { background: var(--green); color: var(--text-bright); } -.detail-page .btn-release { border-color: var(--teal-border); background: var(--teal-bg); color: var(--teal-text); } -.detail-page .btn-release:hover { background: var(--teal-border); color: #e0f7f4; } -.detail-page .btn-notify { border-color: var(--amber-border); background: var(--amber-bg); color: var(--amber-text); } -.detail-page .btn-notify:hover { background: var(--amber-border); color: #f5e0c0; } -.detail-page .btn-notify-cancel { border-color: var(--red-border); background: var(--red-bg); color: #c06060; } -.detail-page .btn-notify-cancel:hover { background: var(--red-border); color: #f5c0c0; } -.section-label { - display: flex; - align-items: center; - gap: .909em; - margin-bottom: 1.273em; - color: var(--green-muted); - font-size: .458em; - font-weight: 800; - letter-spacing: 1.5px; - text-transform: uppercase; -} -.section-label::after { height: 1px; flex: 1; background: #1e3a1e; content: ""; } -.history-list { display: flex; flex-direction: column; gap: .083em; } -.session { - display: grid; - padding: .583em .75em; - border: 1px solid var(--bg); - border-radius: 10px; - background: var(--surface); - grid-template-columns: 1fr auto; - grid-template-rows: auto auto; - gap: .125em .667em; -} -.session:hover { border-color: #2a4a22; } -.session-who { grid-column: 1; color: #5a7a50; font-size: .5em; } -.session-reason { grid-column: 1; color: #a5c882; font-size: .542em; font-weight: 700; } -.session-duration { grid-row: 1; grid-column: 2; align-self: center; color: var(--green); font-size: .5em; font-weight: 800; text-align: right; } -.session-when { grid-row: 2; grid-column: 2; color: #5a8a50; font-size: .417em; text-align: right; } -.pagination { display: flex; align-items: center; justify-content: center; gap: .333em; margin-top: 1.167em; } -.page-btn { - padding: .417em 1.167em; - border: 1px solid var(--green-border); - border-radius: 8px; - background: #1b3818; - color: #6b8f4a; - font-size: .5em; - font-weight: 700; - text-decoration: none; - cursor: pointer; -} -.page-btn:hover { border-color: var(--green); color: var(--green-bright); } -.page-btn.current { border-color: var(--green); background: var(--green-button); color: var(--green-bright); } -.page-info { color: var(--green-muted); font-size: .5em; } -.no-history { padding: .667em 0; color: #3a5a30; font-size: .5em; font-style: italic; } -.admin-tools { - margin-bottom: 1.167em; - padding: .833em; - border: 1px solid #2a4a22; - border-radius: 14px; - background: var(--surface); -} -.admin-tools-title { - margin-bottom: .667em; - color: var(--green-muted); - font-size: .458em; - font-weight: 800; - letter-spacing: 1px; - text-transform: uppercase; -} -.admin-tools form { display: flex; align-items: center; gap: .417em; margin-bottom: .5em; flex-wrap: wrap; } -.admin-tools form:last-child { margin-bottom: 0; } -.admin-tools input { - min-width: 0; - flex: 1; - padding: .615em 1em; - border: 1px solid var(--green-border); - border-radius: 10px; - outline: none; - background: var(--bg); - color: var(--text); - font-size: .5em; -} -.admin-tools .field-error { width: 100%; } -.admin-tools button { - padding: .615em 1em; - border: 1px solid var(--green); - border-radius: var(--pill-radius); - background: var(--green-button); - color: var(--green-bright); - font-size: .458em; - font-weight: 800; - white-space: nowrap; - cursor: pointer; -} -.admin-tools .danger { border-color: var(--red-border); background: var(--red-bg); color: var(--red-text); } diff --git a/internal/web/content/content.go b/internal/web/content/content.go deleted file mode 100644 index 8ed21f1..0000000 --- a/internal/web/content/content.go +++ /dev/null @@ -1,61 +0,0 @@ -// Package content owns the static browser content embedded by the Web UI. -package content - -import ( - "embed" - "fmt" - "html/template" - "io/fs" -) - -// Page identifies a complete page template set. Each page is parsed -// separately because pages define shared template blocks such as title and -// content. -type Page string - -const ( - // Dashboard identifies the dashboard page template set. - Dashboard Page = "dashboard" - // Detail identifies the stick detail page template set. - Detail Page = "detail" - // NewStick identifies the new-stick page template set. - NewStick Page = "new-stick" - // Error identifies the error page template set. - Error Page = "error" -) - -//go:embed templates -var templateFiles embed.FS - -// The Web UI deliberately has no client-side runtime. Keep its only browser -// asset explicit so adding executable assets requires an architectural change. -// -//go:embed assets/styles.css -var assetFiles embed.FS - -var pagePartials = map[Page]string{ - Dashboard: "templates/partials/dashboard/*.html", - Detail: "templates/partials/detail/*.html", - NewStick: "templates/partials/new-stick/*.html", -} - -// ParsePage parses the shared components and one page into an isolated -// template set. -func ParsePage(page Page) (*template.Template, error) { - pageFile := "templates/" + string(page) + ".html" - if page != Error && page != Dashboard && page != Detail && page != NewStick { - return nil, fmt.Errorf("unknown page %q", page) - } - patterns := []string{"templates/base.html", "templates/components/*.html"} - if partials, ok := pagePartials[page]; ok { - patterns = append(patterns, partials) - } - patterns = append(patterns, pageFile) - return template.New("").ParseFS(templateFiles, patterns...) -} - -// Templates returns the embedded HTML content for static content checks. -func Templates() fs.FS { return templateFiles } - -// Assets returns the embedded browser assets. -func Assets() fs.FS { return assetFiles } diff --git a/internal/web/content/content_test.go b/internal/web/content/content_test.go deleted file mode 100644 index bc0a22b..0000000 --- a/internal/web/content/content_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package content_test - -import ( - "testing" - - "stick/internal/web/content" -) - -func TestParsePage(t *testing.T) { - for _, page := range []content.Page{ - content.Dashboard, - content.Detail, - content.NewStick, - content.Error, - } { - t.Run(string(page), func(t *testing.T) { - if _, err := content.ParsePage(page); err != nil { - t.Fatalf("ParsePage: %v", err) - } - }) - } -} - -func TestParsePageRejectsUnknownPage(t *testing.T) { - if _, err := content.ParsePage("unknown"); err == nil { - t.Fatal("ParsePage accepted an unknown page") - } -} diff --git a/internal/web/content/routes.go b/internal/web/content/routes.go deleted file mode 100644 index 965580b..0000000 --- a/internal/web/content/routes.go +++ /dev/null @@ -1,19 +0,0 @@ -package content - -import ( - "net/http" - - "stick/internal/web/httpx" -) - -// RegisterAssets registers the UI's embedded stylesheet under /assets. -func RegisterAssets(router *httpx.Router) { - router.Handle(http.MethodGet, "/assets/styles.css", stylesheet()) -} - -func stylesheet() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "public, no-cache") - http.ServeFileFS(w, r, Assets(), "assets/styles.css") - }) -} diff --git a/internal/web/content/templates/base.html b/internal/web/content/templates/base.html deleted file mode 100644 index cf9a3bb..0000000 --- a/internal/web/content/templates/base.html +++ /dev/null @@ -1,16 +0,0 @@ -{{/* templates/base.html */}} -{{define "base"}} - - - - - -{{block "title" .}}stick{{end}} - - - -{{template "topbar" .}} -{{block "content" .}}{{end}} - - -{{end}} diff --git a/internal/web/content/templates/components/alert.html b/internal/web/content/templates/components/alert.html deleted file mode 100644 index 2de1099..0000000 --- a/internal/web/content/templates/components/alert.html +++ /dev/null @@ -1,2 +0,0 @@ -{{/* templates/components/alert.html */}} -{{define "alert"}}{{if .}}{{end}}{{end}} diff --git a/internal/web/content/templates/components/field-error.html b/internal/web/content/templates/components/field-error.html deleted file mode 100644 index da86565..0000000 --- a/internal/web/content/templates/components/field-error.html +++ /dev/null @@ -1,2 +0,0 @@ -{{/* templates/components/field-error.html */}} -{{define "field-error"}}{{if .HasError}}{{end}}{{end}} diff --git a/internal/web/content/templates/components/pagination.html b/internal/web/content/templates/components/pagination.html deleted file mode 100644 index f5793ad..0000000 --- a/internal/web/content/templates/components/pagination.html +++ /dev/null @@ -1,11 +0,0 @@ -{{/* templates/components/pagination.html */}} -{{define "pagination"}} -{{if .PageLinks}} - -{{end}} -{{end}} diff --git a/internal/web/content/templates/components/stick-action-form.html b/internal/web/content/templates/components/stick-action-form.html deleted file mode 100644 index 60d5127..0000000 --- a/internal/web/content/templates/components/stick-action-form.html +++ /dev/null @@ -1,9 +0,0 @@ -{{/* templates/components/stick-action-form.html */}} -{{define "stick-action-form"}} -
- - - {{if .RedirectTo}}{{end}} - -
-{{end}} diff --git a/internal/web/content/templates/components/topbar.html b/internal/web/content/templates/components/topbar.html deleted file mode 100644 index 3208d36..0000000 --- a/internal/web/content/templates/components/topbar.html +++ /dev/null @@ -1,13 +0,0 @@ -{{/* templates/components/topbar.html */}} -{{define "topbar"}} -{{if .ShowTopbar}} -
- {{if .CurrentUser.ShowAdminBadge}}admin{{end}} - 🌱 {{.CurrentUser.Email}} -
- - -
-
-{{end}} -{{end}} diff --git a/internal/web/content/templates/dashboard.html b/internal/web/content/templates/dashboard.html deleted file mode 100644 index bcab26e..0000000 --- a/internal/web/content/templates/dashboard.html +++ /dev/null @@ -1,17 +0,0 @@ -{{/* templates/dashboard.html */}} -{{template "base" .}} - -{{define "title"}}🌿 the grove{{end}} - -{{define "content"}} -
- {{template "dashboard-stick-cards" .Sticks}} - {{if .CanCreateStick}} - -
+
-
New stick
-
- {{end}} -
-{{template "dashboard-archived-sticks" .}} -{{end}} diff --git a/internal/web/content/templates/detail.html b/internal/web/content/templates/detail.html deleted file mode 100644 index cfe8399..0000000 --- a/internal/web/content/templates/detail.html +++ /dev/null @@ -1,16 +0,0 @@ -{{/* templates/detail.html */}} -{{template "base" .}} - -{{define "title"}}{{.Stick.Icon}} {{.Stick.Name}}{{end}} - -{{define "content"}} -
- ← back to the grove - - {{template "detail-stick-header" .Stick}} - {{template "alert" .Error}} - {{template "detail-admin-controls" .}} - {{template "detail-stick-state" .}} - {{template "detail-history" .}} -
-{{end}} diff --git a/internal/web/content/templates/error.html b/internal/web/content/templates/error.html deleted file mode 100644 index d4c56dc..0000000 --- a/internal/web/content/templates/error.html +++ /dev/null @@ -1,16 +0,0 @@ -{{/* templates/error.html */}} -{{template "base" .}} - -{{define "title"}}{{.Title}}{{end}} - -{{define "content"}} -
- -

{{.Message}}

- {{if .RequestID}}

Request ID: {{.RequestID}}

{{end}} - Return to the grove -
-{{end}} diff --git a/internal/web/content/templates/new-stick.html b/internal/web/content/templates/new-stick.html deleted file mode 100644 index 0f7ab0c..0000000 --- a/internal/web/content/templates/new-stick.html +++ /dev/null @@ -1,16 +0,0 @@ -{{/* templates/new-stick.html */}} -{{template "base" .}} - -{{define "title"}}🌿 new stick{{end}} - -{{define "content"}} -
- ← back to the grove - - {{template "alert" .Error}} - {{template "new-stick-create-form" .}} -
-{{end}} diff --git a/internal/web/content/templates/partials/dashboard/archived-sticks.html b/internal/web/content/templates/partials/dashboard/archived-sticks.html deleted file mode 100644 index a3dacd6..0000000 --- a/internal/web/content/templates/partials/dashboard/archived-sticks.html +++ /dev/null @@ -1,16 +0,0 @@ -{{/* templates/partials/dashboard/archived-sticks.html */}} -{{define "dashboard-archived-sticks"}} -{{if .ShowArchivedSticks}} -
-

Archived sticks

-
- {{range .ArchivedSticks}} -
- {{.Name}} - {{if .RestoreForm}}{{template "stick-action-form" .RestoreForm}}{{end}} -
- {{end}} -
-
-{{end}} -{{end}} diff --git a/internal/web/content/templates/partials/dashboard/stick-cards.html b/internal/web/content/templates/partials/dashboard/stick-cards.html deleted file mode 100644 index 4d549a4..0000000 --- a/internal/web/content/templates/partials/dashboard/stick-cards.html +++ /dev/null @@ -1,70 +0,0 @@ -{{/* templates/partials/dashboard/stick-cards.html */}} -{{define "dashboard-stick-cards"}} -{{range .}} -{{if .HeldByMe}} -{{template "dashboard-stick-card-mine" .}} -{{else if .HeldByOther}} -{{template "dashboard-stick-card-taken" .}} -{{else if .CanClaim}} -{{template "dashboard-stick-card-available" .}} -{{end}} -{{end}} -{{end}} - -{{define "dashboard-stick-card-mine"}} -
- -
-
✋
-
-
- held for {{.HeldDuration}} - yours -
-
-
-
{{.Name}}
-
- {{.HolderEmail}} - {{.Reason}} -
- -
-{{end}} - -{{define "dashboard-stick-card-taken"}} -
- -
-
🪓
-
-
- 🍂 held for {{.HeldDuration}} - in use -
-
-
-
{{.Name}}
-
- {{.HolderEmail}} - {{.Reason}} -
- -
-{{end}} - -{{define "dashboard-stick-card-available"}} - -
-
🌳
-
- available -
-
-
{{.Name}}
-
-{{end}} diff --git a/internal/web/content/templates/partials/detail/admin-controls.html b/internal/web/content/templates/partials/detail/admin-controls.html deleted file mode 100644 index 9f50c54..0000000 --- a/internal/web/content/templates/partials/detail/admin-controls.html +++ /dev/null @@ -1,19 +0,0 @@ -{{/* templates/partials/detail/admin-controls.html */}} -{{define "detail-admin-controls"}} -{{if .Stick.ShowAdminControls}} -
-

Admin controls

- {{if .Stick.CanRename}} -
- - - - - - {{template "field-error" .Stick.RenameField}} -
- {{end}} - {{if .Stick.AdminActionForm}}{{template "stick-action-form" .Stick.AdminActionForm}}{{end}} -
-{{end}} -{{end}} diff --git a/internal/web/content/templates/partials/detail/history.html b/internal/web/content/templates/partials/detail/history.html deleted file mode 100644 index b814401..0000000 --- a/internal/web/content/templates/partials/detail/history.html +++ /dev/null @@ -1,19 +0,0 @@ -{{/* templates/partials/detail/history.html */}} -{{define "detail-history"}} - -
- {{if .Sessions}} - {{range .Sessions}} -
-
{{.Reason}}
-
{{.HolderEmail}}
-
{{.Duration}}
-
{{.TimeRange}}
-
- {{end}} - {{else}} -
This stick has not been used yet.
- {{end}} -
-{{template "pagination" .}} -{{end}} diff --git a/internal/web/content/templates/partials/detail/stick-header.html b/internal/web/content/templates/partials/detail/stick-header.html deleted file mode 100644 index ee5e1cc..0000000 --- a/internal/web/content/templates/partials/detail/stick-header.html +++ /dev/null @@ -1,13 +0,0 @@ -{{/* templates/partials/detail/stick-header.html */}} -{{define "detail-stick-header"}} - -{{end}} diff --git a/internal/web/content/templates/partials/detail/stick-state.html b/internal/web/content/templates/partials/detail/stick-state.html deleted file mode 100644 index 8263f0d..0000000 --- a/internal/web/content/templates/partials/detail/stick-state.html +++ /dev/null @@ -1,38 +0,0 @@ -{{/* templates/partials/detail/stick-state.html */}} -{{define "detail-stick-state"}} -{{if .Stick.IsArchived}} -
-
- - -
-
-{{else if .Stick.CanClaim}} -
- - - - - - {{template "field-error" .Stick.ClaimReasonField}} -
-{{else if .Stick.HeldByMe}} -
-
- - - -
- {{if .Stick.StateActionForm}}{{template "stick-action-form" .Stick.StateActionForm}}{{end}} -
-{{else if .Stick.HeldByOther}} -
-
- - - -
- {{if .Stick.StateActionForm}}{{template "stick-action-form" .Stick.StateActionForm}}{{end}} -
-{{end}} -{{end}} diff --git a/internal/web/content/templates/partials/new-stick/create-form.html b/internal/web/content/templates/partials/new-stick/create-form.html deleted file mode 100644 index 1be1137..0000000 --- a/internal/web/content/templates/partials/new-stick/create-form.html +++ /dev/null @@ -1,16 +0,0 @@ -{{/* templates/partials/new-stick/create-form.html */}} -{{define "new-stick-create-form"}} -
- -
- - -
Letters, digits, hyphens and spaces.
- {{template "field-error" .NameField}} -
-
- - Cancel -
-
-{{end}} diff --git a/internal/web/dashboard/handler.go b/internal/web/dashboard/handler.go deleted file mode 100644 index ba640c1..0000000 --- a/internal/web/dashboard/handler.go +++ /dev/null @@ -1,82 +0,0 @@ -// Package dashboard owns the browser dashboard at the application root. -package dashboard - -import ( - "errors" - "html/template" - "net/http" - - "stick/internal/application" - "stick/internal/auth" - domain "stick/internal/core" - "stick/internal/web/render" -) - -// Handler serves the dashboard route. -type Handler struct { - service *application.Service - renderer render.Renderer - notificationsEnabled bool - dashboardTemplate *template.Template -} - -// New returns a dashboard handler. The template is supplied separately by the -// root composition package because content parsing is a composition concern. -func New(service *application.Service, renderer render.Renderer, dashboardTemplate *template.Template, notificationsEnabled bool) *Handler { - return &Handler{ - service: service, - renderer: renderer, - notificationsEnabled: notificationsEnabled, - dashboardTemplate: dashboardTemplate, - } -} - -// Dashboard renders the active-stick dashboard. -func (h *Handler) Dashboard(w http.ResponseWriter, r *http.Request) { - identity := auth.IdentityFromContext(r.Context()) - sticks, err := h.service.ListSticks(r.Context()) - if err != nil { - h.renderer.InternalError(w, r, "list sticks", err) - return - } - archivedSticks := []domain.Stick(nil) - if identity.IsAdmin { - archivedSticks, err = h.service.ListArchivedSticks(r.Context(), identity) - if err != nil { - h.handlePageError(w, r, err) - return - } - } - var subscribedStickIDs []string - if h.notificationsEnabled && needsSubscriptionViewState(sticks, identity) { - subscribedStickIDs, err = h.service.SubscribedStickIDs(r.Context(), identity) - if err != nil { - h.renderer.InternalError(w, r, "list subscriptions", err) - return - } - } - - h.renderer.Render(w, r, "render dashboard", h.dashboardTemplate, h.renderer.Mapper.Dashboard( - r, identity, sticks, subscribedStickIDs, archivedSticks, - )) -} - -func (h *Handler) handlePageError(w http.ResponseWriter, r *http.Request, err error) { - switch { - case errors.Is(err, application.ErrNotFound): - h.renderer.ErrorPage(w, r, http.StatusNotFound) - case errors.Is(err, application.ErrForbidden): - h.renderer.ErrorPage(w, r, http.StatusForbidden) - default: - h.renderer.InternalError(w, r, "list archived sticks", err) - } -} - -func needsSubscriptionViewState(sticks []domain.Stick, identity domain.Identity) bool { - for _, stick := range sticks { - if !stick.Archived() && !stick.Available() && stick.Holder.Sub != identity.Sub { - return true - } - } - return false -} diff --git a/internal/web/dashboard/routes.go b/internal/web/dashboard/routes.go deleted file mode 100644 index d38f557..0000000 --- a/internal/web/dashboard/routes.go +++ /dev/null @@ -1,12 +0,0 @@ -package dashboard - -import ( - "net/http" - - "stick/internal/web/httpx" -) - -// Register registers the dashboard route under /. -func Register(router *httpx.Router, handler *Handler) { - router.HandleFunc(http.MethodGet, "/{$}", handler.Dashboard) -} diff --git a/internal/web/health/handler.go b/internal/web/health/handler.go index ae0dc1b..7e404ac 100644 --- a/internal/web/health/handler.go +++ b/internal/web/health/handler.go @@ -35,8 +35,8 @@ func (h *Handler) Readiness(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), readinessTimeout) defer cancel() // Readiness deliberately reflects only the required database dependency. - // OIDC discovery is lazy, so an identity-provider outage does not remove - // otherwise healthy instances from service. + // Identity-provider discovery is lazy, so an identity-provider outage does + // not remove otherwise healthy instances from service. if h.readiness == nil || h.readiness.PingContext(ctx) != nil { h.writeStatus(w, http.StatusServiceUnavailable, "not ready\n") return diff --git a/internal/web/httpx/middleware.go b/internal/web/httpx/middleware.go index fea7901..d7fa938 100644 --- a/internal/web/httpx/middleware.go +++ b/internal/web/httpx/middleware.go @@ -1,5 +1,5 @@ -// Package httpx provides the small net/http toolkit shared by the web -// application's endpoints and middleware. +// Package httpx provides the small net/http toolkit shared by the service's +// endpoints and middleware. package httpx import "net/http" diff --git a/internal/web/httpx/middleware_test.go b/internal/web/httpx/middleware_test.go index 8d380b5..18f4344 100644 --- a/internal/web/httpx/middleware_test.go +++ b/internal/web/httpx/middleware_test.go @@ -1,7 +1,6 @@ package httpx_test import ( - "bytes" "log/slog" "net/http" "net/http/httptest" @@ -9,7 +8,6 @@ import ( "testing" "stick/internal/web/httpx" - "stick/internal/web/security" ) func TestChainAppliesMiddlewareInOrder(t *testing.T) { @@ -39,29 +37,26 @@ func TestChainAppliesMiddlewareInOrder(t *testing.T) { } } -func TestMiddlewareAppliesLoggingAndCSRFInOrder(t *testing.T) { - var logs bytes.Buffer +func TestRequestLoggerAddsRequestIDAndLogs(t *testing.T) { + var logs strings.Builder previous := slog.Default() slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) t.Cleanup(func() { slog.SetDefault(previous) }) - innerCalled := false - inner := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { innerCalled = true }) - root := httpx.Chain( - httpx.RequestLogger, - security.CSRFProtection([]byte("secret-32-bytes-minimum-length!!"), nil), - )(inner) + root := httpx.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + })) recorder := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodPost, "/sticks/aa001/release", nil) + request := httptest.NewRequest(http.MethodGet, "/api/v1/sticks", nil) request.Header.Set("X-Request-ID", "known-request-id") root.ServeHTTP(recorder, request) - if recorder.Code != http.StatusForbidden || innerCalled { - t.Fatalf("status=%d innerCalled=%v, want 403/false", recorder.Code, innerCalled) + if recorder.Code != http.StatusNoContent { + t.Fatalf("status=%d, want 204", recorder.Code) } if recorder.Header().Get("X-Request-ID") != "known-request-id" { t.Fatal("request ID middleware did not run") } - if got := logs.String(); !strings.Contains(got, "status=403") || !strings.Contains(got, "request_id=known-request-id") { + if got := logs.String(); !strings.Contains(got, "status=204") || !strings.Contains(got, "request_id=known-request-id") { t.Errorf("log = %q", got) } } diff --git a/internal/web/httpx/router.go b/internal/web/httpx/router.go index 3d3936d..e05f5e9 100644 --- a/internal/web/httpx/router.go +++ b/internal/web/httpx/router.go @@ -58,12 +58,6 @@ func (r *Router) HandleFunc(method, reference string, handler http.HandlerFunc, r.Handle(method, reference, handler, middlewares...) } -// HandleMount registers a handler for the bare non-root application mount. -func (r *Router) HandleMount(method string, handler http.Handler, middlewares ...Middleware) { - combined := append(slices.Clone(r.middlewares), middlewares...) - r.mux.Handle(method+" "+r.publicURL.MountPath(), Chain(combined...)(handler)) -} - func (r *Router) containsRequestPath(path string) bool { mount := r.publicURL.MountPath() return mount == "" || path == mount || strings.HasPrefix(path, mount+"/") diff --git a/internal/web/httpx/url.go b/internal/web/httpx/url.go index 4c5464f..dfddce4 100644 --- a/internal/web/httpx/url.go +++ b/internal/web/httpx/url.go @@ -2,8 +2,6 @@ package httpx import ( "fmt" - "net/url" - "path" "strings" "stick/internal/publicurl" @@ -26,38 +24,3 @@ func Path(publicURL publicurl.URL, reference string) string { func Absolute(publicURL publicurl.URL, reference string) string { return publicURL.Origin() + Path(publicURL, reference) } - -// CookiePath returns the narrowest cookie path covering the application. -func CookiePath(publicURL publicurl.URL) string { - if mountPath := publicURL.MountPath(); mountPath != "" { - return mountPath - } - return "/" -} - -// ContainsLocation reports whether location is a local absolute-path redirect -// contained by the application mount. Encoded or literal traversal, network -// paths, authorities, and backslashes are rejected. -func ContainsLocation(publicURL publicurl.URL, location string) bool { - if location == "" || location[0] != '/' || strings.HasPrefix(location, "//") || strings.Contains(location, `\`) { - return false - } - parsed, err := url.Parse(location) - if err != nil || parsed.IsAbs() || parsed.Scheme != "" || parsed.Host != "" || parsed.User != nil { - return false - } - if parsed.Path == "" || parsed.Path[0] != '/' || strings.Contains(parsed.Path, `\`) { - return false - } - for _, segment := range strings.Split(parsed.Path, "/") { - if segment == "." || segment == ".." { - return false - } - } - clean := path.Clean(parsed.Path) - mountPath := publicURL.MountPath() - if mountPath == "" { - return strings.HasPrefix(clean, "/") - } - return clean == mountPath || strings.HasPrefix(clean, mountPath+"/") -} diff --git a/internal/web/httpx/url_test.go b/internal/web/httpx/url_test.go index 18ad2de..337d8a4 100644 --- a/internal/web/httpx/url_test.go +++ b/internal/web/httpx/url_test.go @@ -9,36 +9,30 @@ import ( func TestPathComposition(t *testing.T) { tests := []struct { - name string - basePath string - reference string - wantPath string - wantCookie string + name string + basePath string + reference string + want string }{ - {name: "root", reference: "/sticks/{id}", wantPath: "/sticks/{id}", wantCookie: "/"}, - {name: "root query", reference: "/sticks/one?tab=history", wantPath: "/sticks/one?tab=history", wantCookie: "/"}, - {name: "mounted", basePath: "/ops/stick", reference: "/sticks/{id}", wantPath: "/ops/stick/sticks/{id}", wantCookie: "/ops/stick"}, + {name: "root", reference: "/api/v1/sticks", want: "/api/v1/sticks"}, + {name: "mounted", basePath: "/ops/stick", reference: "/api/v1/sticks", want: "/ops/stick/api/v1/sticks"}, } - for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { publicURL := mustParse(t, "https://example.test", tt.basePath) - if got := httpx.Path(publicURL, tt.reference); got != tt.wantPath { - t.Errorf("Path() = %q, want %q", got, tt.wantPath) + if got := httpx.Path(publicURL, tt.reference); got != tt.want { + t.Errorf("Path() = %q, want %q", got, tt.want) } - if got := httpx.Absolute(publicURL, "/auth/callback"); got != publicURL.String()+"/auth/callback" { + if got := httpx.Absolute(publicURL, tt.reference); got != publicURL.String()+tt.reference { t.Errorf("Absolute() = %q", got) } - if got := httpx.CookiePath(publicURL); got != tt.wantCookie { - t.Errorf("CookiePath() = %q, want %q", got, tt.wantCookie) - } }) } } func TestPathRejectsUntrustedReferences(t *testing.T) { publicURL := mustParse(t, "https://example.test", "/stick") - for _, reference := range []string{"", "sticks/one", "//evil.example", `/stick\\one`, "/stick#fragment"} { + for _, reference := range []string{"", "api/v1/sticks", "//evil.example", `/stick\\one`, "/stick#fragment"} { t.Run(reference, func(t *testing.T) { defer func() { if recover() == nil { @@ -50,37 +44,6 @@ func TestPathRejectsUntrustedReferences(t *testing.T) { } } -func TestContainsLocation(t *testing.T) { - root := mustParse(t, "https://example.com", "") - mounted := mustParse(t, "https://example.com", "/ops/stick") - - for _, tt := range []struct { - name string - url publicurl.URL - location string - want bool - }{ - {name: "root path", url: root, location: "/sticks/one?tab=history", want: true}, - {name: "mounted root", url: mounted, location: "/ops/stick/", want: true}, - {name: "mounted child", url: mounted, location: "/ops/stick/sticks/one", want: true}, - {name: "mounted fragment", url: mounted, location: "/ops/stick/sticks/one#history", want: true}, - {name: "bare mount", url: mounted, location: "/ops/stick", want: true}, - {name: "outside mount", url: mounted, location: "/outside"}, - {name: "prefix collision", url: mounted, location: "/ops/stick-other"}, - {name: "traversal", url: mounted, location: "/ops/stick/../outside"}, - {name: "escaped traversal", url: mounted, location: "/ops/stick/%2e%2e/outside"}, - {name: "network path", url: root, location: "//evil.example"}, - {name: "absolute", url: root, location: "https://evil.example/"}, - {name: "backslash", url: root, location: `/\\evil.example`}, - } { - t.Run(tt.name, func(t *testing.T) { - if got := httpx.ContainsLocation(tt.url, tt.location); got != tt.want { - t.Errorf("ContainsLocation(%q) = %v, want %v", tt.location, got, tt.want) - } - }) - } -} - func mustParse(t *testing.T, baseURL, basePath string) publicurl.URL { t.Helper() publicURL, err := publicurl.Parse(baseURL + basePath) diff --git a/internal/web/render/render.go b/internal/web/render/render.go deleted file mode 100644 index c7f245e..0000000 --- a/internal/web/render/render.go +++ /dev/null @@ -1,103 +0,0 @@ -// Package render provides the shared, buffered HTML rendering boundary for -// Web UI route packages. -package render - -import ( - "bytes" - "fmt" - "html" - "html/template" - "net/http" - - "stick/internal/auth" - "stick/internal/web/httpx" - "stick/internal/web/views" -) - -// Renderer renders page templates and the browser-safe error page. A renderer -// is a value so each route package can depend on this boundary without -// depending on the root web composition package. -type Renderer struct { - Mapper views.Mapper - ErrorTemplate *template.Template -} - -// New returns a renderer configured with the shared view mapper and error -// template. -func New(mapper views.Mapper, errorTemplate *template.Template) Renderer { - return Renderer{Mapper: mapper, ErrorTemplate: errorTemplate} -} - -// Render renders a successful page, buffering template output so an execution -// error cannot expose a partial response. -func (r Renderer) Render(w http.ResponseWriter, request *http.Request, operation string, tmpl *template.Template, data any) { - r.RenderStatus(w, request, operation, tmpl, data, http.StatusOK) -} - -// RenderStatus renders a page with an explicit HTTP status. -func (r Renderer) RenderStatus( - w http.ResponseWriter, - request *http.Request, - operation string, - tmpl *template.Template, - data any, - status int, -) { - var buffer bytes.Buffer - if err := tmpl.ExecuteTemplate(&buffer, "base", data); err != nil { - r.InternalError(w, request, operation, err) - return - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - if status >= http.StatusBadRequest { - w.Header().Set("Cache-Control", "no-store") - } - w.WriteHeader(status) - _, _ = buffer.WriteTo(w) -} - -// InternalError logs an implementation error and renders a generic 500 page. -func (r Renderer) InternalError(w http.ResponseWriter, request *http.Request, operation string, err error) { - httpx.LogError(request.Context(), "request failed", operation, err) - r.ErrorPage(w, request, http.StatusInternalServerError) -} - -// ErrorPage renders a local, mount-aware HTML error response. It is safe to -// use as middleware's error callback. -func (r Renderer) ErrorPage(w http.ResponseWriter, request *http.Request, status int) { - if r.ErrorTemplate == nil { - r.writeFallbackErrorPage(w, request, status) - return - } - view := r.Mapper.ErrorPage(request, auth.IdentityFromContext(request.Context()), status) - var buffer bytes.Buffer - if err := r.ErrorTemplate.ExecuteTemplate(&buffer, "base", view); err != nil { - httpx.LogError(request.Context(), "request failed", "render error page", err) - r.writeFallbackErrorPage(w, request, status) - return - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(status) - _, _ = buffer.WriteTo(w) -} - -func (r Renderer) writeFallbackErrorPage(w http.ResponseWriter, request *http.Request, status int) { - requestID := "" - if status >= http.StatusInternalServerError { - requestID = httpx.RequestID(request.Context()) - } - requestIDMarkup := "" - if requestID != "" { - requestIDMarkup = fmt.Sprintf("

Request ID: %s

", html.EscapeString(requestID)) - } - body := fmt.Sprintf( - "%d · stick

Request failed

We could not complete your request.

%s
", - status, - requestIDMarkup, - ) - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(status) - _, _ = w.Write([]byte(body)) -} diff --git a/internal/web/render/render_test.go b/internal/web/render/render_test.go deleted file mode 100644 index 0c9148a..0000000 --- a/internal/web/render/render_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package render - -import ( - "bytes" - "errors" - "html/template" - "io/fs" - "log/slog" - "net/http" - "net/http/httptest" - "regexp" - "strings" - "testing" - - "stick/internal/web/content" - "stick/internal/web/httpx" -) - -func TestUITemplatesUseOnlyTheEmbeddedStylesheet(t *testing.T) { - assets, err := fs.Glob(content.Assets(), "assets/*") - if err != nil { - t.Fatalf("glob assets: %v", err) - } - if len(assets) == 0 { - t.Fatal("UI has no embedded stylesheet") - } - for _, asset := range assets { - if !strings.HasSuffix(asset, ".css") { - t.Errorf("UI embeds non-stylesheet browser asset %q", asset) - } - } - - for _, path := range embeddedTemplatePaths(t) { - contents, err := fs.ReadFile(content.Templates(), path) - if err != nil { - t.Fatalf("read %s: %v", path, err) - } - markup := string(contents) - for _, forbidden := range []string{" 7 { - t.Errorf("page %q: rendered %d page links, want at most 7", page, links) - } - } -} - -func TestUI_Detail_UsesHistoryCountForPageTotals(t *testing.T) { - store := newTestDB(t) - createStick(t, store, "aa001", "prod-deploy") - identity := domain.Identity{Sub: "u1", Name: "Alice", Email: "alice@example.com"} - for range 40 { - claimStick(t, store, "aa001", identity, "deploying") - releaseStick(t, store, "aa001", identity.Sub) - } - claimStick(t, store, "aa001", identity, "still deploying") - - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - for _, page := range []string{"1", "2", "3"} { - req := httptest.NewRequest("GET", "/sticks/aa001?page="+page, nil) - req.SetPathValue("id", "aa001") - req = req.WithContext(auth.WithIdentity(req.Context(), identity)) - rr := httptest.NewRecorder() - - ui.sticksHandler.Detail(rr, req) - - if rr.Code != http.StatusOK { - t.Fatalf("page %s: expected 200, got %d: %s", page, rr.Code, rr.Body.String()) - } - body := rr.Body.String() - if !strings.Contains(body, "40 sessions total") { - t.Errorf("page %s: expected true history total, got body without it", page) - } - if got := strings.Count(body, `class="page-btn`); got != 2 { - t.Errorf("page %s: rendered %d page links, want 2", page, got) - } - if strings.Contains(body, `page=3`) { - t.Errorf("page %s: rendered an out-of-range page link", page) - } - } -} - -func TestUI_Detail_NotFound(t *testing.T) { - store := newTestDB(t) - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - req := httptest.NewRequest("GET", "/sticks/nonexistent", nil) - req.SetPathValue("id", "nonexistent") - identity := domain.Identity{Sub: "u1", Name: "Alice", Email: "alice@example.com"} - ctx := auth.WithIdentity(req.Context(), identity) - req = req.WithContext(ctx) - rr := httptest.NewRecorder() - ui.sticksHandler.Detail(rr, req) - - if rr.Code != http.StatusNotFound { - t.Errorf("expected 404 for non-existent stick, got %d", rr.Code) - } - if got := rr.Header().Get("Content-Type"); got != "text/html; charset=utf-8" || !strings.Contains(rr.Body.String(), "Not found") { - t.Errorf("not-found response = Content-Type %q body %q", got, rr.Body.String()) - } -} - -func TestUI_Detail_ArchivedStickHiddenFromNonAdmin(t *testing.T) { - store := newTestDB(t) - createStick(t, store, "aa001", "archived") - archiveStick(t, store, "aa001") - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatal(err) - } - req := httptest.NewRequest(http.MethodGet, "/sticks/aa001", nil) - req.SetPathValue("id", "aa001") - req = req.WithContext(auth.WithIdentity(req.Context(), domain.Identity{Sub: "u1"})) - recorder := httptest.NewRecorder() - - ui.sticksHandler.Detail(recorder, req) - - if recorder.Code != http.StatusNotFound { - t.Fatalf("archived detail status = %d, want 404", recorder.Code) - } - if body := recorder.Body.String(); !strings.Contains(body, "Not found") || strings.Contains(body, "archived") { - t.Fatalf("archived detail did not preserve authorization hiding: %s", body) - } -} - -func TestDashboard_AdminBadge(t *testing.T) { - store := newTestDB(t) - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - identity := domain.Identity{Sub: "u1", Name: "Alice", Email: "alice@example.com", IsAdmin: true} - ctx := auth.WithIdentity(context.Background(), identity) - req := httptest.NewRequest("GET", "/", nil).WithContext(ctx) - rr := httptest.NewRecorder() - ui.dashboardHandler.Dashboard(rr, req) - - if rr.Code != http.StatusOK { - t.Fatalf("expected 200, got %d", rr.Code) - } - if !strings.Contains(rr.Body.String(), "pill--admin") { - t.Error("expected admin badge (pill--admin) in response for admin user") - } -} - -func TestDashboard_NoAdminBadge(t *testing.T) { - store := newTestDB(t) - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - identity := domain.Identity{Sub: "u2", Name: "Bob", Email: "bob@example.com", IsAdmin: false} - ctx := auth.WithIdentity(context.Background(), identity) - req := httptest.NewRequest("GET", "/", nil).WithContext(ctx) - rr := httptest.NewRecorder() - ui.dashboardHandler.Dashboard(rr, req) - - if rr.Code != http.StatusOK { - t.Fatalf("expected 200, got %d", rr.Code) - } - if strings.Contains(rr.Body.String(), "pill--admin") { - t.Error("expected no admin badge for non-admin user") - } -} - -func TestDashboard_AdminNewStickCard(t *testing.T) { - store := newTestDB(t) - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - identity := domain.Identity{Sub: "u1", Name: "Alice", Email: "alice@example.com", IsAdmin: true} - ctx := auth.WithIdentity(context.Background(), identity) - req := httptest.NewRequest("GET", "/", nil).WithContext(ctx) - rr := httptest.NewRecorder() - ui.dashboardHandler.Dashboard(rr, req) - - if !strings.Contains(rr.Body.String(), "/sticks/new") { - t.Error("expected admin to see new stick card linking to /sticks/new") - } -} - -func TestDashboard_NonAdminNoNewStickCard(t *testing.T) { - store := newTestDB(t) - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - identity := domain.Identity{Sub: "u2", Name: "Bob", Email: "bob@example.com", IsAdmin: false} - ctx := auth.WithIdentity(context.Background(), identity) - req := httptest.NewRequest("GET", "/", nil).WithContext(ctx) - rr := httptest.NewRecorder() - ui.dashboardHandler.Dashboard(rr, req) - - if strings.Contains(rr.Body.String(), "/sticks/new") { - t.Error("expected non-admin to NOT see new stick card") - } -} - -func TestDashboard_AdminArchivedSticks(t *testing.T) { - store := newTestDB(t) - createStick(t, store, "aa001", "retired deploy") - archiveStick(t, store, "aa001") - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatal(err) - } - identity := domain.Identity{Sub: "admin", Name: "Admin", Email: "admin@example.com", IsAdmin: true} - req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(auth.WithIdentity(context.Background(), identity)) - rr := httptest.NewRecorder() - ui.dashboardHandler.Dashboard(rr, req) - if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), "retired deploy") || !strings.Contains(rr.Body.String(), "/unarchive") { - t.Fatalf("dashboard status = %d, body missing archived stick: %s", rr.Code, rr.Body.String()) - } -} - -func TestUI_NewStick_Admin(t *testing.T) { - store := newTestDB(t) - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - identity := domain.Identity{Sub: "admin1", Name: "Admin", Email: "admin@example.com", IsAdmin: true} - ctx := auth.WithIdentity(context.Background(), identity) - req := httptest.NewRequest("GET", "/sticks/new", nil).WithContext(ctx) - rr := httptest.NewRecorder() - ui.sticksHandler.NewStick(rr, req) - - if rr.Code != http.StatusOK { - t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String()) - } - if !strings.Contains(rr.Body.String(), "New stick") { - t.Error("expected new stick form in response") - } -} - -func TestUI_NewStick_NonAdmin(t *testing.T) { - store := newTestDB(t) - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - identity := domain.Identity{Sub: "u1", Name: "Alice", Email: "alice@example.com", IsAdmin: false} - ctx := auth.WithIdentity(context.Background(), identity) - req := httptest.NewRequest("GET", "/sticks/new", nil).WithContext(ctx) - rr := httptest.NewRecorder() - ui.sticksHandler.NewStick(rr, req) - - if rr.Code != http.StatusForbidden { - t.Errorf("expected 403, got %d", rr.Code) - } - if got := rr.Header().Get("Content-Type"); got != "text/html; charset=utf-8" || !strings.Contains(rr.Body.String(), "Not allowed") { - t.Errorf("forbidden response = Content-Type %q body %q", got, rr.Body.String()) - } -} - -func TestUIUnexpectedFailureRendersSafeRequestIDErrorPage(t *testing.T) { - store := newTestDB(t) - handler, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, "/basepath"), true) - if err != nil { - t.Fatal(err) - } - if err := store.Close(); err != nil { - t.Fatal(err) - } - request := httptest.NewRequest(http.MethodGet, "/basepath/", nil) - request = request.WithContext(auth.WithIdentity(request.Context(), domain.Identity{Sub: "u1"})) - request = request.WithContext(httpx.WithRequestID(request.Context(), "request-42")) - recorder := httptest.NewRecorder() - - handler.dashboardHandler.Dashboard(recorder, request) - - if recorder.Code != http.StatusInternalServerError || recorder.Header().Get("Content-Type") != "text/html; charset=utf-8" { - t.Fatalf("response = %d Content-Type %q", recorder.Code, recorder.Header().Get("Content-Type")) - } - body := recorder.Body.String() - for _, want := range []string{"Something went wrong", "request-42", `href="/basepath/"`, `href="/basepath/assets/styles.css"`} { - if !strings.Contains(body, want) { - t.Errorf("error page missing %q", want) - } - } - for _, forbidden := range []string{"database is closed", "sql:", "internal error"} { - if strings.Contains(body, forbidden) { - t.Errorf("error page leaked implementation detail %q", forbidden) - } - } -} - -func TestUI_CreateStick_AdminForm(t *testing.T) { - store := newTestDB(t) - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, "/basepath"), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - req := httptest.NewRequest(http.MethodPost, "/sticks/new", strings.NewReader("name=Deploy+Key")) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req = req.WithContext(auth.WithIdentity(req.Context(), domain.Identity{Sub: "admin1", IsAdmin: true})) - recorder := httptest.NewRecorder() - ui.sticksHandler.CreateStick(recorder, req) - - if recorder.Code != http.StatusSeeOther || recorder.Header().Get("Location") != "/basepath/" { - t.Fatalf("status = %d, Location = %q", recorder.Code, recorder.Header().Get("Location")) - } - sticks, err := store.ListSticks(context.Background()) - if err != nil { - t.Fatal(err) - } - if len(sticks) != 1 || sticks[0].Name != "Deploy Key" { - t.Fatalf("created sticks = %+v", sticks) - } - if _, err := uuid.Parse(sticks[0].ID); err != nil { - t.Fatalf("created stick ID = %q, want UUID: %v", sticks[0].ID, err) - } -} - -func TestUI_CreateStick_RendersNonAdminErrorPage(t *testing.T) { - store := newTestDB(t) - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - req := httptest.NewRequest(http.MethodPost, "/sticks/new", strings.NewReader("name=Deploy+Key")) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req = req.WithContext(auth.WithIdentity(req.Context(), domain.Identity{Sub: "u1"})) - recorder := httptest.NewRecorder() - - ui.sticksHandler.CreateStick(recorder, req) - - if recorder.Code != http.StatusForbidden || recorder.Header().Get("Content-Type") != "text/html; charset=utf-8" { - t.Fatalf("status = %d, Content-Type = %q", recorder.Code, recorder.Header().Get("Content-Type")) - } - if got := recorder.Body.String(); !strings.Contains(got, "Not allowed") || strings.Contains(got, "forbidden\n") { - t.Fatalf("unsafe or unclear error page: %q", got) - } -} - -func TestUI_CreateStick_InvalidFormInputs(t *testing.T) { - for _, test := range []struct { - name string - body string - wantStatus int - wantValue string - wantFieldError bool - }{ - { - name: "invalid name", - body: "name=bad%21name", - wantStatus: http.StatusUnprocessableEntity, - wantValue: "bad!name", - wantFieldError: true, - }, - { - name: "oversized name", - body: "name=" + url.QueryEscape(strings.Repeat("x", 101)), - wantStatus: http.StatusUnprocessableEntity, - wantValue: strings.Repeat("x", 101), - wantFieldError: true, - }, - { - name: "oversized body", - body: "name=Deploy+Key&padding=" + strings.Repeat("x", 9*1024), - wantStatus: http.StatusBadRequest, - }, - } { - t.Run(test.name, func(t *testing.T) { - store := newTestDB(t) - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, "/basepath"), true) - if err != nil { - t.Fatalf("New: %v", err) - } - req := httptest.NewRequest(http.MethodPost, "/sticks/new", strings.NewReader(test.body)) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req = req.WithContext(auth.WithIdentity(req.Context(), domain.Identity{Sub: "admin1", IsAdmin: true})) - recorder := httptest.NewRecorder() - - ui.sticksHandler.CreateStick(recorder, req) - - if recorder.Code != test.wantStatus || recorder.Header().Get("Location") != "" { - t.Fatalf("status = %d, Location = %q, want %d without redirect", recorder.Code, recorder.Header().Get("Location"), test.wantStatus) - } - if got := recorder.Header().Get("Content-Type"); got != "text/html; charset=utf-8" { - t.Errorf("Content-Type = %q, want HTML", got) - } - body := recorder.Body.String() - if strings.Contains(body, "?error=") { - t.Error("validation response contains query-string error transport") - } - if test.wantFieldError { - for _, want := range []string{ - `value="` + test.wantValue + `"`, - `aria-invalid="true"`, - `aria-describedby="name-hint name-error"`, - `id="name-error" role="alert"`, - } { - if !strings.Contains(body, want) { - t.Errorf("validation response missing %q", want) - } - } - } else if !strings.Contains(body, "invalid or too large") { - t.Error("bad request page does not explain the invalid or oversized form") - } - sticks, err := store.ListSticks(context.Background()) - if err != nil { - t.Fatal(err) - } - if len(sticks) != 0 { - t.Fatalf("invalid form persisted sticks: %+v", sticks) - } - }) - } -} - -func TestUI_Claim_RejectsOversizedReason(t *testing.T) { - store := newTestDB(t) - ctx := context.Background() - createStick(t, store, "aa001", "prod") - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - form := url.Values{"reason": {strings.Repeat("x", 501)}, "version": {stickVersion(t, store, "aa001")}} - req := httptest.NewRequest("POST", "/sticks/aa001/claim", strings.NewReader(form.Encode())) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.SetPathValue("id", "aa001") - req = req.WithContext(auth.WithIdentity(req.Context(), domain.Identity{Sub: "u1"})) - rr := httptest.NewRecorder() - ui.sticksHandler.Claim(rr, req) - - if rr.Code != http.StatusUnprocessableEntity { - t.Fatalf("expected 422, got %d", rr.Code) - } - for _, want := range []string{`value="` + strings.Repeat("x", 501) + `"`, `aria-invalid="true"`, `aria-describedby="claim-reason-error"`, `id="claim-reason-error" role="alert"`} { - if !strings.Contains(rr.Body.String(), want) { - t.Errorf("claim validation response missing %q", want) - } - } - stick, err := store.GetStick(ctx, "aa001") - if err != nil { - t.Fatal(err) - } - if !stick.Available() { - t.Fatal("oversized reason should not claim the stick") - } -} - -func TestUI_Claim_RejectsOversizedBody(t *testing.T) { - store := newTestDB(t) - ctx := context.Background() - createStick(t, store, "aa001", "prod") - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - body := "reason=deploying&padding=" + strings.Repeat("x", 9*1024) - req := httptest.NewRequest("POST", "/sticks/aa001/claim", strings.NewReader(body)) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.SetPathValue("id", "aa001") - req = req.WithContext(auth.WithIdentity(req.Context(), domain.Identity{Sub: "u1"})) - rr := httptest.NewRecorder() - ui.sticksHandler.Claim(rr, req) - - if rr.Code != http.StatusBadRequest { - t.Fatalf("expected 400, got %d", rr.Code) - } - if got := rr.Header().Get("Content-Type"); got != "text/html; charset=utf-8" || !strings.Contains(rr.Body.String(), "invalid or too large") { - t.Errorf("oversized form response = Content-Type %q body %q", got, rr.Body.String()) - } - stick, err := store.GetStick(ctx, "aa001") - if err != nil { - t.Fatal(err) - } - if !stick.Available() { - t.Fatal("oversized body should not claim the stick") - } -} - -func TestUI_Claim_RejectsWhitespaceOnlyReason(t *testing.T) { - store := newTestDB(t) - ctx := context.Background() - createStick(t, store, "aa001", "prod") - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - form := url.Values{"reason": {" \t"}, "version": {stickVersion(t, store, "aa001")}} - req := httptest.NewRequest("POST", "/sticks/aa001/claim", strings.NewReader(form.Encode())) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.SetPathValue("id", "aa001") - req = req.WithContext(auth.WithIdentity(req.Context(), domain.Identity{Sub: "u1"})) - rr := httptest.NewRecorder() - ui.sticksHandler.Claim(rr, req) - - if rr.Code != http.StatusUnprocessableEntity { - t.Fatalf("expected 422, got %d", rr.Code) - } - if body := rr.Body.String(); !strings.Contains(body, `aria-invalid="true"`) || - !strings.Contains(body, "Reason must be non-empty") || strings.Contains(body, "?error=") { - t.Errorf("whitespace validation response is not accessible/safe: %s", body) - } - stick, err := store.GetStick(ctx, "aa001") - if err != nil { - t.Fatal(err) - } - if !stick.Available() { - t.Fatal("whitespace-only reason should not claim the stick") - } -} - -func TestFormatTime_UsesConfiguredTimezone(t *testing.T) { - store := newTestDB(t) - loc, err := time.LoadLocation("America/New_York") - if err != nil { - t.Fatalf("LoadLocation: %v", err) - } - uiHandler, err := newUI(application.NewService(store), loc, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - createStick(t, store, "tz001", "tz-stick") - id := domain.Identity{Sub: "u1", Name: "Alice", Email: "alice@example.com"} - claimStick(t, store, "tz001", id, "testing") - - req := httptest.NewRequest("GET", "/sticks/tz001", nil) - req.SetPathValue("id", "tz001") - reqCtx := auth.WithIdentity(req.Context(), id) - req = req.WithContext(reqCtx) - rr := httptest.NewRecorder() - uiHandler.sticksHandler.Detail(rr, req) - - if rr.Code != http.StatusOK { - t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String()) - } - // The timestamp was stored as UTC. With America/New_York (UTC-4 or UTC-5), - // the rendered time should NOT contain "UTC" in the time offset sense, - // and should differ from a UTC-rendered time. - // We can't predict the exact time, but we can verify the page rendered and - // contains a timestamp (formatTime produces "Jan 2 · 15:04" format). - body := rr.Body.String() - if !strings.Contains(body, "·") { - t.Error("expected formatted timestamp with '·' separator in detail page") - } - - // Render again with UTC to confirm they produce different output when time crosses hour boundary. - // Use a fixed timestamp to make this deterministic. - uiUTC, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New UTC: %v", err) - } - req2 := httptest.NewRequest("GET", "/sticks/tz001", nil) - req2.SetPathValue("id", "tz001") - req2 = req2.WithContext(auth.WithIdentity(req2.Context(), id)) - rr2 := httptest.NewRecorder() - uiUTC.sticksHandler.Detail(rr2, req2) - if rr2.Code != http.StatusOK { - t.Fatalf("expected 200, got %d", rr2.Code) - } - // Both renders should produce a timestamp with '·' — the test validates the - // template function is wired correctly in both cases. - if !strings.Contains(rr2.Body.String(), "·") { - t.Error("expected formatted timestamp with '·' separator in UTC detail page") - } -} - -func TestUI_Subscribe_And_Unsubscribe(t *testing.T) { - store := newTestDB(t) - ctx := context.Background() - createStick(t, store, "aa001", "prod-deploy") - id := domain.Identity{Sub: "u1", Name: "Alice", Email: "alice@example.com"} - claimStick(t, store, "aa001", domain.Identity{Sub: "u2", Name: "Bob", Email: "bob@example.com"}, "deploying") - - service := application.NewService(store) - ui, err := newUI(service, time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - // Subscribe - version := stickVersion(t, store, "aa001") - req := httptest.NewRequest("POST", "/sticks/aa001/notify", strings.NewReader(url.Values{"version": {version}}.Encode())) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.SetPathValue("id", "aa001") - req = req.WithContext(auth.WithIdentity(req.Context(), id)) - rr := httptest.NewRecorder() - ui.sticksHandler.Subscribe(rr, req) - if rr.Code != http.StatusSeeOther { - t.Fatalf("Subscribe: expected 303, got %d", rr.Code) - } - - // Verify subscribed - ids, _ := service.SubscribedStickIDs(ctx, id) - if len(ids) != 1 || ids[0] != "aa001" { - t.Error("expected user to be subscribed after Subscribe handler") - } - - // Unsubscribe - req2 := httptest.NewRequest("POST", "/sticks/aa001/notify/cancel", strings.NewReader(url.Values{"version": {version}}.Encode())) - req2.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req2.SetPathValue("id", "aa001") - req2 = req2.WithContext(auth.WithIdentity(req2.Context(), id)) - rr2 := httptest.NewRecorder() - ui.sticksHandler.Unsubscribe(rr2, req2) - if rr2.Code != http.StatusSeeOther { - t.Fatalf("Unsubscribe: expected 303, got %d", rr2.Code) - } - - ids, _ = service.SubscribedStickIDs(ctx, id) - if len(ids) != 0 { - t.Error("expected user to not be subscribed after Unsubscribe handler") - } -} - -func TestUI_DetailRendersSubscribedState(t *testing.T) { - store := newTestDB(t) - createStick(t, store, "aa001", "prod-deploy") - claimStick(t, store, "aa001", domain.Identity{Sub: "u1", Name: "Alice", Email: "alice@example.com"}, "deploying") - - watcher := domain.Identity{Sub: "u2", Name: "Bob", Email: "bob@example.com"} - subscribeStick(t, store, "aa001", watcher.Sub, watcher.Name, watcher.Email) - - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatalf("New: %v", err) - } - - req := httptest.NewRequest("GET", "/sticks/aa001", nil) - req.SetPathValue("id", "aa001") - req = req.WithContext(auth.WithIdentity(req.Context(), watcher)) - rr := httptest.NewRecorder() - ui.sticksHandler.Detail(rr, req) - - if rr.Code != http.StatusOK { - t.Fatalf("expected 200, got %d", rr.Code) - } - // Bob is subscribed, so the cancel form should appear - if !strings.Contains(rr.Body.String(), "/notify/cancel") { - t.Error("expected cancel notification form for subscribed user") - } -} - -func TestUI_DetailComparesHolderBySubjectNotEmail(t *testing.T) { - store := newTestDB(t) - createStick(t, store, "aa001", "prod-deploy") - holder := domain.Identity{Sub: "holder-sub", Name: "Alice", Email: "shared@example.com"} - claimStick(t, store, "aa001", holder, "deploying") - viewer := domain.Identity{Sub: "different-sub", Name: "Other Alice", Email: "shared@example.com"} - ui, err := newUI(application.NewService(store), time.UTC, uiPublicURL(t, ""), true) - if err != nil { - t.Fatal(err) - } - req := httptest.NewRequest(http.MethodGet, "/sticks/aa001", nil) - req.SetPathValue("id", "aa001") - req = req.WithContext(auth.WithIdentity(req.Context(), viewer)) - recorder := httptest.NewRecorder() - - ui.sticksHandler.Detail(recorder, req) - - if recorder.Code != http.StatusOK { - t.Fatalf("status = %d: %s", recorder.Code, recorder.Body.String()) - } - if strings.Contains(recorder.Body.String(), "/sticks/aa001/release") { - t.Error("viewer with the holder's email but a different subject was offered release") - } - if !strings.Contains(recorder.Body.String(), "/sticks/aa001/notify") { - t.Error("viewer with a different subject was not offered notification subscription") - } -} - -func uiPublicURL(t *testing.T, mountPath string) publicurl.URL { - t.Helper() - publicURL, err := publicurl.Parse("http://example.test" + mountPath) - if err != nil { - t.Fatal(err) - } - return publicURL -} diff --git a/internal/web/sticks/form.go b/internal/web/sticks/form.go deleted file mode 100644 index a72d47d..0000000 --- a/internal/web/sticks/form.go +++ /dev/null @@ -1,16 +0,0 @@ -package sticks - -import ( - "net/http" - "strconv" - - "stick/internal/web/security" -) - -// parseBoundedForm parses a browser form request body with a conservative -// limit. The limit is a UI transport policy rather than a generic HTTP rule. -func parseBoundedForm(response http.ResponseWriter, request *http.Request) error { - return security.ParseBoundedForm(response, request) -} - -func parseVersion(raw string) (int64, error) { return strconv.ParseInt(raw, 10, 64) } diff --git a/internal/web/sticks/form_test.go b/internal/web/sticks/form_test.go deleted file mode 100644 index 929252a..0000000 --- a/internal/web/sticks/form_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package sticks - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestParseFormBoundsAndParsesBody(t *testing.T) { - request := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("name=Deploy+Key")) - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - response := httptest.NewRecorder() - if err := parseBoundedForm(response, request); err != nil { - t.Fatalf("ParseForm: %v", err) - } - if got := request.Form.Get("name"); got != "Deploy Key" { - t.Fatalf("name = %q, want Deploy Key", got) - } - - oversized := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("padding="+strings.Repeat("x", 9<<10))) - oversized.Header.Set("Content-Type", "application/x-www-form-urlencoded") - if err := parseBoundedForm(httptest.NewRecorder(), oversized); err == nil { - t.Fatal("ParseForm accepted an oversized body") - } -} diff --git a/internal/web/sticks/handler.go b/internal/web/sticks/handler.go deleted file mode 100644 index 1a636ab..0000000 --- a/internal/web/sticks/handler.go +++ /dev/null @@ -1,201 +0,0 @@ -// Package sticks owns the browser routes below /sticks, including pages and -// their form mutations. -package sticks - -import ( - "errors" - "html/template" - "net/http" - - "stick/internal/application" - "stick/internal/auth" - domain "stick/internal/core" - "stick/internal/publicurl" - "stick/internal/web/render" - "stick/internal/web/views" -) - -const ( - invalidStickNameMessage = "Name must be non-empty, at most 100 characters, and contain only letters, digits, hyphens, and spaces." - invalidClaimReasonMessage = "Reason must be non-empty and at most 500 characters." - staleStickError = "This stick changed since the page was loaded. Review its current state and try again." -) - -// DetailFormState is the detail form state used at the route boundary. -type DetailFormState = views.DetailFormState - -// NewStickFormState is the new-stick form state used at the route boundary. -type NewStickFormState = views.NewStickFormState - -// Handler serves the /sticks pages and mutations. -type Handler struct { - service *application.Service - publicURL publicurl.URL - notificationsEnabled bool - renderer render.Renderer - detailTemplate *template.Template - newStickTemplate *template.Template -} - -// New returns a handler for the /sticks route family. -func New( - service *application.Service, - publicURL publicurl.URL, - renderer render.Renderer, - detailTemplate, newStickTemplate *template.Template, - notificationsEnabled bool, -) *Handler { - return &Handler{ - service: service, - publicURL: publicURL, - notificationsEnabled: notificationsEnabled, - renderer: renderer, - detailTemplate: detailTemplate, - newStickTemplate: newStickTemplate, - } -} - -// NewStick renders the new-stick form. -func (h *Handler) NewStick(w http.ResponseWriter, r *http.Request) { - identity := auth.IdentityFromContext(r.Context()) - if !identity.IsAdmin { - h.renderer.ErrorPage(w, r, http.StatusForbidden) - return - } - h.renderNewStick(w, r, http.StatusOK, NewStickFormState{}) -} - -// Detail renders the stick detail page and session history. -func (h *Handler) Detail(w http.ResponseWriter, r *http.Request) { - identity := auth.IdentityFromContext(r.Context()) - currentStick, err := h.service.GetStick(r.Context(), identity, r.PathValue("id")) - if err != nil { - h.handlePageError(w, r, "get stick", err) - return - } - h.renderStickDetail(w, r, currentStick, http.StatusOK, DetailFormState{}) -} - -func (h *Handler) renderNewStick(w http.ResponseWriter, r *http.Request, status int, form NewStickFormState) { - h.renderer.RenderStatus(w, r, "render new stick", h.newStickTemplate, - h.renderer.Mapper.NewStick(r, auth.IdentityFromContext(r.Context()), form), status) -} - -func (h *Handler) renderCurrentStickDetail( - w http.ResponseWriter, - r *http.Request, - id string, - status int, - form DetailFormState, -) { - identity := auth.IdentityFromContext(r.Context()) - stick, err := h.service.GetStick(r.Context(), identity, id) - if err != nil { - h.handlePageError(w, r, "get current stick", err) - return - } - h.renderStickDetail(w, r, stick, status, form) -} - -func (h *Handler) renderStickDetail( - w http.ResponseWriter, - r *http.Request, - currentStick domain.Stick, - status int, - form DetailFormState, -) { - identity := auth.IdentityFromContext(r.Context()) - id := currentStick.ID - page := parseHistoryPage(r.URL.Query().Get("page")) - offset := (page - 1) * pageSize - - sessions, totalSessions, err := h.service.GetHistory(r.Context(), identity, id, pageSize, offset) - if err != nil { - h.handlePageError(w, r, "get stick history", err) - return - } - totalPages := (totalSessions + pageSize - 1) / pageSize - if totalPages < 1 { - totalPages = 1 - } - - var subscribedStickIDs []string - if h.notificationsEnabled && needsStickSubscriptionViewState(currentStick, identity) { - subscribedStickIDs, err = h.service.SubscribedStickIDs(r.Context(), identity) - if err != nil { - h.handlePageError(w, r, "list subscriptions", err) - return - } - } - - h.renderer.RenderStatus(w, r, "render stick detail", h.detailTemplate, h.renderer.Mapper.Detail( - r, - identity, - currentStick, - sessions, - page, - totalPages, - totalSessions, - historyPageLinks(page, totalPages), - subscribedStickIDs, - form, - ), status) -} - -func (h *Handler) handlePageError(w http.ResponseWriter, r *http.Request, operation string, err error) { - switch { - case errors.Is(err, application.ErrNotFound): - h.renderer.ErrorPage(w, r, http.StatusNotFound) - case errors.Is(err, application.ErrForbidden): - h.renderer.ErrorPage(w, r, http.StatusForbidden) - default: - h.renderer.InternalError(w, r, operation, err) - } -} - -func needsStickSubscriptionViewState(stick domain.Stick, identity domain.Identity) bool { - return !stick.Archived() && !stick.Available() && stick.Holder.Sub != identity.Sub -} - -func (h *Handler) requireAdminMutation(w http.ResponseWriter, r *http.Request) bool { - if auth.IdentityFromContext(r.Context()).IsAdmin { - return true - } - h.renderer.ErrorPage(w, r, http.StatusForbidden) - return false -} - -func (h *Handler) parseForm(w http.ResponseWriter, r *http.Request) bool { - if err := parseBoundedForm(w, r); err == nil { - return true - } - h.renderer.ErrorPage(w, r, http.StatusBadRequest) - return false -} - -func (h *Handler) handleCommonMutationError(w http.ResponseWriter, r *http.Request, id string, err error) bool { - switch { - case errors.Is(err, application.ErrNotFound): - h.renderer.ErrorPage(w, r, http.StatusNotFound) - case errors.Is(err, application.ErrForbidden): - h.renderer.ErrorPage(w, r, http.StatusForbidden) - case errors.Is(err, application.ErrVersionConflict): - h.renderCurrentStickDetail(w, r, id, http.StatusConflict, DetailFormState{Alert: staleStickError}) - case errors.Is(err, domain.ErrVersionExhausted): - h.renderCurrentStickDetail(w, r, id, http.StatusConflict, DetailFormState{ - Alert: "This stick can no longer be changed. Review its current state and contact an administrator.", - }) - default: - return false - } - return true -} - -func (h *Handler) expectedFormVersion(w http.ResponseWriter, r *http.Request) (int64, bool) { - version, err := parseVersion(r.Form.Get("version")) - if err != nil || version < 1 { - h.renderer.ErrorPage(w, r, http.StatusBadRequest) - return 0, false - } - return version, true -} diff --git a/internal/web/sticks/mutations.go b/internal/web/sticks/mutations.go deleted file mode 100644 index f558f62..0000000 --- a/internal/web/sticks/mutations.go +++ /dev/null @@ -1,253 +0,0 @@ -package sticks - -import ( - "errors" - "net/http" - - "stick/internal/application" - "stick/internal/auth" - domain "stick/internal/core" - "stick/internal/web/httpx" -) - -// CreateStick handles the new-stick form submission. -func (h *Handler) CreateStick(w http.ResponseWriter, r *http.Request) { - if !auth.IdentityFromContext(r.Context()).IsAdmin { - h.renderer.ErrorPage(w, r, http.StatusForbidden) - return - } - if !h.parseForm(w, r) { - return - } - name := r.Form.Get("name") - if _, err := h.service.CreateStick(r.Context(), auth.IdentityFromContext(r.Context()), name); err != nil { - if errors.Is(err, domain.ErrInvalidStickName) { - h.renderNewStick(w, r, http.StatusUnprocessableEntity, NewStickFormState{ - Name: name, - NameError: invalidStickNameMessage, - }) - return - } - if errors.Is(err, application.ErrAlreadyExists) { - h.renderNewStick(w, r, http.StatusConflict, NewStickFormState{ - Name: name, - Alert: "The stick could not be created because it conflicts with current data. Review it and try again.", - }) - return - } - if errors.Is(err, application.ErrForbidden) { - h.renderer.ErrorPage(w, r, http.StatusForbidden) - return - } - h.renderer.InternalError(w, r, "create stick", err) - return - } - http.Redirect(w, r, httpx.Path(h.publicURL, "/"), http.StatusSeeOther) -} - -// Rename handles the stick rename form submission. -func (h *Handler) Rename(w http.ResponseWriter, r *http.Request) { - if !h.requireAdminMutation(w, r) { - return - } - id := r.PathValue("id") - if !h.parseForm(w, r) { - return - } - name := r.Form.Get("name") - expectedVersion, ok := h.expectedFormVersion(w, r) - if !ok { - return - } - if _, err := h.service.RenameStick(r.Context(), auth.IdentityFromContext(r.Context()), id, name, expectedVersion); err != nil { - if errors.Is(err, domain.ErrInvalidStickName) { - h.renderCurrentStickDetail(w, r, id, http.StatusUnprocessableEntity, DetailFormState{ - RenameValue: &name, - RenameError: invalidStickNameMessage, - }) - return - } - if h.handleCommonMutationError(w, r, id, err) { - return - } - h.renderer.InternalError(w, r, "rename stick", err) - return - } - http.Redirect(w, r, h.stickPath(id, ""), http.StatusSeeOther) -} - -// Archive handles the stick archive form submission. -func (h *Handler) Archive(w http.ResponseWriter, r *http.Request) { - if !h.requireAdminMutation(w, r) { - return - } - id := r.PathValue("id") - if !h.parseForm(w, r) { - return - } - expectedVersion, ok := h.expectedFormVersion(w, r) - if !ok { - return - } - if _, err := h.service.ArchiveStick(r.Context(), auth.IdentityFromContext(r.Context()), id, expectedVersion); err != nil { - if errors.Is(err, domain.ErrHeld) { - h.renderCurrentStickDetail(w, r, id, http.StatusConflict, DetailFormState{ - Alert: "This stick is currently held. It must be put down before it can be archived.", - }) - return - } - if errors.Is(err, domain.ErrAlreadyArchived) { - h.renderCurrentStickDetail(w, r, id, http.StatusConflict, DetailFormState{ - Alert: "This stick is already archived. Review its current state before trying another action.", - }) - return - } - if h.handleCommonMutationError(w, r, id, err) { - return - } - h.renderer.InternalError(w, r, "archive stick", err) - return - } - http.Redirect(w, r, httpx.Path(h.publicURL, "/"), http.StatusSeeOther) -} - -// Unarchive handles the stick restore form submission. -func (h *Handler) Unarchive(w http.ResponseWriter, r *http.Request) { - if !h.requireAdminMutation(w, r) { - return - } - id := r.PathValue("id") - if !h.parseForm(w, r) { - return - } - expectedVersion, ok := h.expectedFormVersion(w, r) - if !ok { - return - } - if _, err := h.service.UnarchiveStick(r.Context(), auth.IdentityFromContext(r.Context()), id, expectedVersion); err != nil { - if errors.Is(err, domain.ErrNotArchived) { - h.renderCurrentStickDetail(w, r, id, http.StatusConflict, DetailFormState{ - Alert: "This stick is not archived. Review its current state before trying another action.", - }) - return - } - if h.handleCommonMutationError(w, r, id, err) { - return - } - h.renderer.InternalError(w, r, "unarchive stick", err) - return - } - http.Redirect(w, r, httpx.Path(h.publicURL, "/"), http.StatusSeeOther) -} - -// Claim handles the stick claim form submission. -func (h *Handler) Claim(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - identity := auth.IdentityFromContext(r.Context()) - if !h.parseForm(w, r) { - return - } - reason := r.Form.Get("reason") - expectedVersion, ok := h.expectedFormVersion(w, r) - if !ok { - return - } - if _, err := h.service.ClaimStick(r.Context(), identity, id, reason, expectedVersion); err != nil { - if errors.Is(err, domain.ErrInvalidClaimReason) { - h.renderCurrentStickDetail(w, r, id, http.StatusUnprocessableEntity, DetailFormState{ - ClaimReasonValue: reason, - ClaimReasonError: invalidClaimReasonMessage, - }) - return - } - if errors.Is(err, domain.ErrAlreadyHeld) { - h.renderCurrentStickDetail(w, r, id, http.StatusConflict, DetailFormState{ - Alert: "This stick is already held. Review its current state and try again when it is available.", - }) - return - } - if errors.Is(err, domain.ErrAlreadyArchived) { - h.renderCurrentStickDetail(w, r, id, http.StatusConflict, DetailFormState{ - Alert: "This stick is archived and cannot be claimed. Review its current state before trying another action.", - }) - return - } - if h.handleCommonMutationError(w, r, id, err) { - return - } - h.renderer.InternalError(w, r, "claim stick", err) - return - } - http.Redirect(w, r, h.stickPath(id, ""), http.StatusSeeOther) -} - -// Release handles the stick release form submission. -func (h *Handler) Release(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - identity := auth.IdentityFromContext(r.Context()) - if !h.parseForm(w, r) { - return - } - expectedVersion, ok := h.expectedFormVersion(w, r) - if !ok { - return - } - - if _, err := h.service.ReleaseStick(r.Context(), identity, id, expectedVersion); err != nil { - if errors.Is(err, domain.ErrNotHolder) { - h.renderCurrentStickDetail(w, r, id, http.StatusForbidden, DetailFormState{ - Alert: "You can only put down a stick that you currently hold.", - }) - return - } - if h.handleCommonMutationError(w, r, id, err) { - return - } - h.renderer.InternalError(w, r, "release stick", err) - return - } - - http.Redirect(w, r, safeRedirect(r, h.publicURL, stickReference(id, "")), http.StatusSeeOther) -} - -// Subscribe handles the notification subscription form submission. -func (h *Handler) Subscribe(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - identity := auth.IdentityFromContext(r.Context()) - if !h.parseForm(w, r) { - return - } - expectedVersion, ok := h.expectedFormVersion(w, r) - if !ok { - return - } - if err := h.service.Subscribe(r.Context(), identity, id, expectedVersion); err != nil { - if h.handleCommonMutationError(w, r, id, err) { - return - } - h.renderer.InternalError(w, r, "subscribe to stick", err) - return - } - http.Redirect(w, r, safeRedirect(r, h.publicURL, stickReference(id, "")), http.StatusSeeOther) -} - -// Unsubscribe handles the notification unsubscription form submission. -func (h *Handler) Unsubscribe(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - identity := auth.IdentityFromContext(r.Context()) - if !h.parseForm(w, r) { - return - } - expectedVersion, ok := h.expectedFormVersion(w, r) - if !ok { - return - } - if err := h.service.Unsubscribe(r.Context(), identity, id, expectedVersion); err != nil { - if h.handleCommonMutationError(w, r, id, err) { - return - } - h.renderer.InternalError(w, r, "unsubscribe from stick", err) - return - } - http.Redirect(w, r, safeRedirect(r, h.publicURL, stickReference(id, "")), http.StatusSeeOther) -} diff --git a/internal/web/sticks/pagination.go b/internal/web/sticks/pagination.go deleted file mode 100644 index 3f52110..0000000 --- a/internal/web/sticks/pagination.go +++ /dev/null @@ -1,59 +0,0 @@ -package sticks - -import "strconv" - -const ( - maxHistoryPageLinks = 7 - pageSize = 20 - maxHistoryOffset = 100_000 - maxHistoryPage = maxHistoryOffset/pageSize + 1 -) - -func parseHistoryPage(raw string) int { - page, err := strconv.Atoi(raw) - if err != nil || page < 1 { - return 1 - } - if page > maxHistoryPage { - return maxHistoryPage - } - return page -} - -// ParseHistoryPage normalizes and bounds a history page number. -func ParseHistoryPage(raw string) int { return parseHistoryPage(raw) } - -func historyPageLinks(page, totalPages int) []int { - if totalPages < 1 { - return nil - } - if page > totalPages { - page = totalPages - } - - window := maxHistoryPageLinks - if totalPages < window { - window = totalPages - } - start := page - window/2 - if start < 1 { - start = 1 - } - end := start + window - 1 - if end < start || end > totalPages { - end = totalPages - start = end - window + 1 - if start < 1 { - start = 1 - } - } - - links := make([]int, end-start+1) - for i := range links { - links[i] = start + i - } - return links -} - -// HistoryPageLinks returns the bounded pagination window used by stick pages. -func HistoryPageLinks(page, totalPages int) []int { return historyPageLinks(page, totalPages) } diff --git a/internal/web/sticks/pagination_test.go b/internal/web/sticks/pagination_test.go deleted file mode 100644 index a090ef1..0000000 --- a/internal/web/sticks/pagination_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package sticks - -import "testing" - -func TestHistoryPageParser(t *testing.T) { - tests := []struct { - name string - raw string - parse func(string) int - want int - }{ - {name: "page default", raw: "invalid", parse: parseHistoryPage, want: 1}, - {name: "page negative", raw: "-1", parse: parseHistoryPage, want: 1}, - {name: "page bounded", raw: "999999999", parse: parseHistoryPage, want: maxHistoryPage}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if got := test.parse(test.raw); got != test.want { - t.Fatalf("parse(%q) = %d, want %d", test.raw, got, test.want) - } - }) - } -} - -func TestHistoryPageLinksAreBounded(t *testing.T) { - links := historyPageLinks(5000, 10_000) - if len(links) != maxHistoryPageLinks { - t.Fatalf("links = %v, want %d entries", links, maxHistoryPageLinks) - } - for i := 1; i < len(links); i++ { - if links[i] != links[i-1]+1 { - t.Fatalf("links are not contiguous: %v", links) - } - } -} diff --git a/internal/web/sticks/path.go b/internal/web/sticks/path.go deleted file mode 100644 index f0f9ac8..0000000 --- a/internal/web/sticks/path.go +++ /dev/null @@ -1,28 +0,0 @@ -package sticks - -import ( - "net/http" - "net/url" - - "stick/internal/publicurl" - "stick/internal/web/httpx" -) - -func (h *Handler) stickPath(id, suffix string) string { - return httpx.Path(h.publicURL, stickReference(id, suffix)) -} - -func stickReference(id, suffix string) string { - return "/sticks/" + url.PathEscape(id) + suffix -} - -// safeRedirect returns redirect_to when it is safely contained by the -// application mount, otherwise the mounted fallback. -func safeRedirect(r *http.Request, publicURL publicurl.URL, fallback string) string { - fallback = httpx.Path(publicURL, fallback) - to := r.Form.Get("redirect_to") - if !httpx.ContainsLocation(publicURL, to) { - return fallback - } - return to -} diff --git a/internal/web/sticks/path_test.go b/internal/web/sticks/path_test.go deleted file mode 100644 index c3002df..0000000 --- a/internal/web/sticks/path_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package sticks - -import ( - "net/http/httptest" - "testing" - - "stick/internal/publicurl" -) - -func TestSafeRedirect_StaysInsideBasePath(t *testing.T) { - for _, tt := range []struct { - name string - basePath string - to string - want string - }{ - {name: "root deployment allows internal path", to: "/sticks/aa001", want: "/sticks/aa001"}, - {name: "root deployment rejects host-relative path", to: "//evil.example", want: "/sticks/aa001"}, - {name: "root deployment rejects backslash host-relative path", to: "/\\evil.example", want: "/sticks/aa001"}, - {name: "mounted deployment allows mounted path", basePath: "/basepath", to: "/basepath/", want: "/basepath/"}, - {name: "mounted deployment rejects outside path", basePath: "/basepath", to: "/outside", want: "/basepath/sticks/aa001"}, - {name: "mounted deployment rejects prefix collision", basePath: "/basepath", to: "/basepath-other", want: "/basepath/sticks/aa001"}, - {name: "mounted deployment rejects traversal", basePath: "/basepath", to: "/basepath/../outside", want: "/basepath/sticks/aa001"}, - } { - t.Run(tt.name, func(t *testing.T) { - req := httptest.NewRequest("POST", "/", nil) - q := req.URL.Query() - q.Set("redirect_to", tt.to) - req.URL.RawQuery = q.Encode() - if err := req.ParseForm(); err != nil { - t.Fatalf("ParseForm: %v", err) - } - publicURL, err := publicurl.Parse("http://example.test" + tt.basePath) - if err != nil { - t.Fatal(err) - } - if got := safeRedirect(req, publicURL, "/sticks/aa001"); got != tt.want { - t.Errorf("safeRedirect() = %q, want %q", got, tt.want) - } - }) - } -} diff --git a/internal/web/sticks/routes.go b/internal/web/sticks/routes.go deleted file mode 100644 index 177d481..0000000 --- a/internal/web/sticks/routes.go +++ /dev/null @@ -1,23 +0,0 @@ -package sticks - -import ( - "net/http" - - "stick/internal/web/httpx" -) - -// Register registers every route below /sticks. -func Register(router *httpx.Router, handler *Handler) { - router.HandleFunc(http.MethodGet, "/sticks/new", handler.NewStick) - router.HandleFunc(http.MethodPost, "/sticks/new", handler.CreateStick) - router.HandleFunc(http.MethodGet, "/sticks/{id}", handler.Detail) - router.HandleFunc(http.MethodPost, "/sticks/{id}/rename", handler.Rename) - router.HandleFunc(http.MethodPost, "/sticks/{id}/archive", handler.Archive) - router.HandleFunc(http.MethodPost, "/sticks/{id}/unarchive", handler.Unarchive) - router.HandleFunc(http.MethodPost, "/sticks/{id}/claim", handler.Claim) - router.HandleFunc(http.MethodPost, "/sticks/{id}/release", handler.Release) - if handler.notificationsEnabled { - router.HandleFunc(http.MethodPost, "/sticks/{id}/notify", handler.Subscribe) - router.HandleFunc(http.MethodPost, "/sticks/{id}/notify/cancel", handler.Unsubscribe) - } -} diff --git a/internal/web/views/views.go b/internal/web/views/views.go deleted file mode 100644 index 175c339..0000000 --- a/internal/web/views/views.go +++ /dev/null @@ -1,564 +0,0 @@ -// Package views maps application values to the data rendered by Web UI -// templates. It deliberately has no dependency on a route package. -package views - -import ( - "fmt" - "net/http" - "net/url" - "strconv" - "time" - - domain "stick/internal/core" - "stick/internal/format" - "stick/internal/publicurl" - "stick/internal/web/httpx" - "stick/internal/web/security" -) - -// CurrentUserViewModel contains the user details displayed by a page. -type CurrentUserViewModel struct { - Email string - ShowAdminBadge bool -} - -// PageViewModel contains data shared by all page templates. -type PageViewModel struct { - CurrentUser CurrentUserViewModel - CSRFToken string - StylesheetURL string - LogoutAction string - HomeURL string - ShowTopbar bool -} - -// TextFieldViewModel contains the values and validation state for a text field. -type TextFieldViewModel struct { - Value string - DescribedBy string - ErrorID string - ErrorMessage string - HasError bool -} - -// DashboardViewModel contains the data rendered by the dashboard page. -type DashboardViewModel struct { - PageViewModel - Sticks []StickCardViewModel - CanCreateStick bool - NewStickURL string - ShowArchivedSticks bool - ArchivedSticks []ArchivedStickViewModel -} - -// StickActionFormViewModel contains the data needed to render a stick action form. -type StickActionFormViewModel struct { - Action string - CSRFToken string - FormVersion int64 - RedirectTo string - ButtonClass string - ButtonLabel string -} - -// StickCardViewModel contains the data rendered for a stick on the dashboard. -type StickCardViewModel struct { - Name string - DetailURL string - DetailAriaLabel string - HolderEmail string - Reason string - HeldDuration string - HeldByMe bool - HeldByOther bool - CanClaim bool - ActionForm *StickActionFormViewModel -} - -// ArchivedStickViewModel contains the data rendered for an archived stick. -type ArchivedStickViewModel struct { - Name string - DetailURL string - RestoreForm *StickActionFormViewModel -} - -// DetailViewModel contains the data rendered by the stick detail page. -type DetailViewModel struct { - PageViewModel - Stick StickDetailViewModel - Sessions []HistorySessionViewModel - PageLinks []PaginationLinkViewModel - TotalSessionsLabel string - Error string -} - -// DetailFormState contains submitted values and validation errors for the detail page. -type DetailFormState struct { - Alert string - RenameValue *string - RenameError string - ClaimReasonValue string - ClaimReasonError string -} - -// StickDetailViewModel contains the data rendered for a stick's details. -type StickDetailViewModel struct { - Name string - DisplayID string - FormVersion int64 - Icon string - StatusLabel string - StatusClass string - HolderEmail string - Reason string - HeldSince string - HeldDuration string - IsArchived bool - HeldByMe bool - HeldByOther bool - CanClaim bool - ShowAdminControls bool - CanRename bool - RenameAction string - ClaimAction string - AdminActionForm *StickActionFormViewModel - StateActionForm *StickActionFormViewModel - RenameField TextFieldViewModel - ClaimReasonField TextFieldViewModel -} - -// HistorySessionViewModel contains the data rendered for one history session. -type HistorySessionViewModel struct { - Reason string - HolderEmail string - Duration string - TimeRange string -} - -// PaginationLinkViewModel contains the data rendered for one pagination link. -type PaginationLinkViewModel struct { - Number int - URL string - IsCurrent bool -} - -// NewStickViewModel contains the data rendered by the new-stick page. -type NewStickViewModel struct { - PageViewModel - CreateAction string - Error string - NameField TextFieldViewModel -} - -// NewStickFormState contains submitted values and validation errors for the new-stick page. -type NewStickFormState struct { - Name string - NameError string - Alert string -} - -// ErrorPageViewModel contains the data rendered by an error page. -type ErrorPageViewModel struct { - PageViewModel - Title string - Icon string - Heading string - Message string - RequestID string -} - -// Mapper is the boundary between application/domain values and data that -// templates may render. Its action flags control presentation only; the -// application service remains responsible for authorizing every mutation. -type Mapper struct { - PublicURL publicurl.URL - Location *time.Location - NotificationsEnabled bool - // Now is injectable for deterministic presentation tests. A nil value uses - // time.Now. - Now func() time.Time -} - -// NewMapper returns a view mapper configured for an application mount. -func NewMapper(publicURL publicurl.URL, location *time.Location, notificationsEnabled bool) Mapper { - if location == nil { - location = time.UTC - } - return Mapper{ - PublicURL: publicURL, - Location: location, - NotificationsEnabled: notificationsEnabled, - Now: time.Now, - } -} - -func (m Mapper) now() time.Time { - if m.Now == nil { - return time.Now() - } - return m.Now() -} - -// Dashboard maps application values to the dashboard view model. -func (m Mapper) Dashboard( - r *http.Request, - identity domain.Identity, - sticks []domain.Stick, - subscribedStickIDs []string, - archivedSticks []domain.Stick, -) DashboardViewModel { - pageView := m.page(r, identity) - subscribed := stringSet(subscribedStickIDs) - now := m.now() - stickViews := make([]StickCardViewModel, 0, len(sticks)) - for _, stick := range sticks { - stickViews = append(stickViews, m.stickCard( - stick, - identity, - subscribed[stick.ID], - now, - pageView.CSRFToken, - pageView.HomeURL, - )) - } - - archivedViews := make([]ArchivedStickViewModel, 0, len(archivedSticks)) - for _, stick := range archivedSticks { - canRestore := identity.IsAdmin && stick.Archived() - archivedView := ArchivedStickViewModel{ - Name: stick.Name, - DetailURL: m.stickURL(stick.ID, ""), - } - if canRestore { - archivedView.RestoreForm = newStickActionForm( - m.stickURL(stick.ID, "/unarchive"), - pageView.CSRFToken, - stick.Version, - "", - "", - "Restore", - ) - } - archivedViews = append(archivedViews, archivedView) - } - - return DashboardViewModel{ - PageViewModel: pageView, - Sticks: stickViews, - CanCreateStick: identity.IsAdmin, - NewStickURL: httpx.Path(m.PublicURL, "/sticks/new"), - ShowArchivedSticks: identity.IsAdmin && len(archivedViews) > 0, - ArchivedSticks: archivedViews, - } -} - -func (m Mapper) stickCard( - stick domain.Stick, - identity domain.Identity, - isSubscribed bool, - now time.Time, - csrfToken string, - redirectTo string, -) StickCardViewModel { - isArchived := stick.Archived() - isAvailable := stick.Available() - heldByMe := !isArchived && !isAvailable && stick.Holder.Sub == identity.Sub - heldByOther := !isArchived && !isAvailable && !heldByMe - isSubscribed = heldByOther && isSubscribed - - view := StickCardViewModel{ - Name: stick.Name, - DetailURL: m.stickURL(stick.ID, ""), - DetailAriaLabel: "View " + stick.Name + " details", - HeldByMe: heldByMe, - HeldByOther: heldByOther, - CanClaim: !isArchived && isAvailable, - } - if stick.Holder != nil { - view.HolderEmail = stick.Holder.Email - view.Reason = stick.Holder.Reason - view.HeldDuration = m.elapsed(stick.Holder.ClaimedAt, now) - } - switch { - case heldByMe: - view.ActionForm = newStickActionForm( - m.stickURL(stick.ID, "/release"), csrfToken, stick.Version, redirectTo, "btn btn-release", "Put down", - ) - case m.NotificationsEnabled && heldByOther && isSubscribed: - view.ActionForm = newStickActionForm( - m.stickURL(stick.ID, "/notify/cancel"), csrfToken, stick.Version, redirectTo, "btn btn-notify-cancel", "Cancel notification", - ) - case m.NotificationsEnabled && heldByOther: - view.ActionForm = newStickActionForm( - m.stickURL(stick.ID, "/notify"), csrfToken, stick.Version, redirectTo, "btn btn-notify", "Notify me", - ) - } - return view -} - -// Detail maps application values to the stick detail view model. -func (m Mapper) Detail( - r *http.Request, - identity domain.Identity, - stick domain.Stick, - sessions []domain.Session, - page, totalPages, totalSessions int, - pageNumbers []int, - subscribedStickIDs []string, - form DetailFormState, -) DetailViewModel { - pageView := m.page(r, identity) - subscribed := stringSet(subscribedStickIDs)[stick.ID] - stickView := m.stickDetail(stick, identity, subscribed, m.now(), pageView.CSRFToken, form) - - sessionViews := make([]HistorySessionViewModel, 0, len(sessions)) - for _, session := range sessions { - sessionViews = append(sessionViews, m.historySession(session)) - } - - var pageLinks []PaginationLinkViewModel - if totalPages > 1 { - pageLinks = make([]PaginationLinkViewModel, 0, len(pageNumbers)) - for _, link := range pageNumbers { - pageLinks = append(pageLinks, PaginationLinkViewModel{ - Number: link, - URL: m.stickURL(stick.ID, "?page="+strconv.Itoa(link)), - IsCurrent: link == page, - }) - } - } - - return DetailViewModel{ - PageViewModel: pageView, - Stick: stickView, - Sessions: sessionViews, - PageLinks: pageLinks, - TotalSessionsLabel: fmt.Sprintf("%d sessions total", totalSessions), - Error: form.Alert, - } -} - -func (m Mapper) stickDetail( - stick domain.Stick, - identity domain.Identity, - isSubscribed bool, - now time.Time, - csrfToken string, - form DetailFormState, -) StickDetailViewModel { - isArchived := stick.Archived() - isAvailable := stick.Available() - heldByMe := !isArchived && !isAvailable && stick.Holder.Sub == identity.Sub - heldByOther := !isArchived && !isAvailable && !heldByMe - isSubscribed = heldByOther && isSubscribed - canRename := identity.IsAdmin - canArchive := identity.IsAdmin && !isArchived && isAvailable - canRestore := identity.IsAdmin && isArchived - renameValue := stick.Name - if form.RenameValue != nil { - renameValue = *form.RenameValue - } - - view := StickDetailViewModel{ - Name: stick.Name, - DisplayID: stick.ID, - FormVersion: stick.Version, - IsArchived: isArchived, - HeldByMe: heldByMe, - HeldByOther: heldByOther, - CanClaim: !isArchived && isAvailable, - ShowAdminControls: canRename || canArchive || canRestore, - CanRename: canRename, - RenameAction: m.stickURL(stick.ID, "/rename"), - ClaimAction: m.stickURL(stick.ID, "/claim"), - RenameField: newTextField(renameValue, "", "rename-name-error", form.RenameError), - ClaimReasonField: newTextField(form.ClaimReasonValue, "", "claim-reason-error", form.ClaimReasonError), - } - - switch { - case isArchived: - view.Icon = "📦" - view.StatusLabel = "archived" - view.StatusClass = "archived" - case isAvailable: - view.Icon = "🌳" - view.StatusLabel = "available" - view.StatusClass = "available" - case heldByMe: - view.Icon = "✋" - view.StatusLabel = "yours" - view.StatusClass = "mine" - default: - view.Icon = "🪓" - view.StatusLabel = "in use" - view.StatusClass = "taken" - } - - if stick.Holder != nil { - view.HolderEmail = stick.Holder.Email - view.Reason = stick.Holder.Reason - view.HeldSince = m.formatTime(stick.Holder.ClaimedAt) - view.HeldDuration = m.elapsed(stick.Holder.ClaimedAt, now) - } - switch { - case canRestore: - view.AdminActionForm = newStickActionForm( - m.stickURL(stick.ID, "/unarchive"), csrfToken, stick.Version, "", "", "Restore stick", - ) - case canArchive: - view.AdminActionForm = newStickActionForm( - m.stickURL(stick.ID, "/archive"), csrfToken, stick.Version, "", "danger", "Archive stick", - ) - } - switch { - case heldByMe: - view.StateActionForm = newStickActionForm( - m.stickURL(stick.ID, "/release"), csrfToken, stick.Version, "", "btn-release", "Put down", - ) - case m.NotificationsEnabled && heldByOther && isSubscribed: - view.StateActionForm = newStickActionForm( - m.stickURL(stick.ID, "/notify/cancel"), csrfToken, stick.Version, "", "btn-notify-cancel", "Cancel notification", - ) - case m.NotificationsEnabled && heldByOther: - view.StateActionForm = newStickActionForm( - m.stickURL(stick.ID, "/notify"), csrfToken, stick.Version, "", "btn-notify", "Notify me", - ) - } - return view -} - -// StickDetail maps one stick's state and action controls. -func (m Mapper) StickDetail( - stick domain.Stick, - identity domain.Identity, - isSubscribed bool, - now time.Time, - csrfToken string, - form DetailFormState, -) StickDetailViewModel { - return m.stickDetail(stick, identity, isSubscribed, now, csrfToken, form) -} - -func (m Mapper) historySession(session domain.Session) HistorySessionViewModel { - claimedAt := m.formatTime(session.ClaimedAt) - releasedAt := "" - view := HistorySessionViewModel{ - Reason: session.Reason, - HolderEmail: session.HolderEmail, - } - if session.ReleasedAt != nil { - view.Duration = format.Duration(session.ReleasedAt.Sub(session.ClaimedAt).Round(time.Minute)) - releasedAt = m.formatTime(*session.ReleasedAt) - } - view.TimeRange = claimedAt + " → " + releasedAt - return view -} - -// NewStick maps form state to the new-stick view model. -func (m Mapper) NewStick(r *http.Request, identity domain.Identity, form NewStickFormState) NewStickViewModel { - return NewStickViewModel{ - PageViewModel: m.page(r, identity), - CreateAction: httpx.Path(m.PublicURL, "/sticks/new"), - Error: form.Alert, - NameField: newTextField(form.Name, "name-hint", "name-error", form.NameError), - } -} - -// ErrorPage maps an HTTP status to the error page view model. -func (m Mapper) ErrorPage(r *http.Request, identity domain.Identity, status int) ErrorPageViewModel { - view := ErrorPageViewModel{ - PageViewModel: m.page(r, identity), - Title: fmt.Sprintf("%d · stick", status), - Icon: "🍂", - } - switch status { - case http.StatusBadRequest: - view.Heading = "Invalid request" - view.Message = "The form submission was invalid or too large. Return to the page and try again." - case http.StatusForbidden: - view.Heading = "Not allowed" - view.Message = "You do not have permission to perform this action." - case http.StatusNotFound: - view.Heading = "Not found" - view.Message = "The page or stick you requested could not be found." - default: - view.Heading = "Something went wrong" - view.Message = "We could not complete your request. Try again later." - if status >= http.StatusInternalServerError { - view.RequestID = httpx.RequestID(r.Context()) - } - } - return view -} - -func (m Mapper) page(r *http.Request, identity domain.Identity) PageViewModel { - return PageViewModel{ - CurrentUser: CurrentUserViewModel{ - Email: identity.Email, - ShowAdminBadge: identity.IsAdmin, - }, - CSRFToken: security.CSRFToken(r), - StylesheetURL: httpx.Path(m.PublicURL, "/assets/styles.css"), - LogoutAction: httpx.Path(m.PublicURL, "/auth/logout"), - HomeURL: httpx.Path(m.PublicURL, "/"), - ShowTopbar: identity.Sub != "", - } -} - -func (m Mapper) formatTime(value time.Time) string { - location := m.Location - if location == nil { - location = time.UTC - } - return value.In(location).Format("Jan 2 · 15:04") -} - -func (m Mapper) elapsed(since, now time.Time) string { - duration := now.Sub(since).Round(time.Minute) - if duration < time.Minute { - return "just now" - } - return format.Duration(duration) -} - -func (m Mapper) stickURL(id, suffix string) string { - return httpx.Path(m.PublicURL, "/sticks/"+url.PathEscape(id)+suffix) -} - -func newStickActionForm( - action, csrfToken string, formVersion int64, redirectTo, buttonClass, buttonLabel string, -) *StickActionFormViewModel { - return &StickActionFormViewModel{ - Action: action, - CSRFToken: csrfToken, - FormVersion: formVersion, - RedirectTo: redirectTo, - ButtonClass: buttonClass, - ButtonLabel: buttonLabel, - } -} - -func newTextField(value, hintID, errorID, errorMessage string) TextFieldViewModel { - describedBy := hintID - if errorMessage != "" { - if describedBy != "" { - describedBy += " " - } - describedBy += errorID - } - return TextFieldViewModel{ - Value: value, - DescribedBy: describedBy, - ErrorID: errorID, - ErrorMessage: errorMessage, - HasError: errorMessage != "", - } -} - -func stringSet(values []string) map[string]bool { - set := make(map[string]bool, len(values)) - for _, value := range values { - set[value] = true - } - return set -} diff --git a/internal/web/views/views_test.go b/internal/web/views/views_test.go deleted file mode 100644 index e195541..0000000 --- a/internal/web/views/views_test.go +++ /dev/null @@ -1,183 +0,0 @@ -package views - -import ( - "net/http/httptest" - "testing" - "time" - - domain "stick/internal/core" - "stick/internal/publicurl" -) - -func TestDashboardViewModelMapsIdentityAndStickActions(t *testing.T) { - now := time.Date(2026, time.August, 27, 18, 0, 0, 0, time.UTC) - claimedAt := now.Add(-time.Hour - 35*time.Minute) - archivedAt := now.Add(-24 * time.Hour) - mapper := testViewModelMapper(t, time.UTC, now) - identity := domain.Identity{ - Sub: "viewer-sub", - Email: "viewer@example.com", - IsAdmin: true, - } - sticks := []domain.Stick{ - {ID: "available", Name: "Available", Version: 3}, - { - ID: "mine", - Name: "Mine", - Version: 4, - Holder: &domain.Holder{ - Sub: "viewer-sub", - Email: "viewer@example.com", - Reason: "deploying", - ClaimedAt: claimedAt, - }, - }, - { - ID: "theirs", - Name: "Theirs", - Version: 5, - Holder: &domain.Holder{ - Sub: "another-sub", - Email: "holder@example.com", - Reason: "testing", - ClaimedAt: claimedAt, - }, - }, - } - archived := []domain.Stick{{ - ID: "retired", - Name: "Retired", - Version: 6, - ArchivedAt: &archivedAt, - }} - request := httptest.NewRequest("GET", "/", nil) - - view := mapper.Dashboard(request, identity, sticks, []string{"theirs"}, archived) - - if view.CurrentUser.Email != identity.Email || !view.CurrentUser.ShowAdminBadge { - t.Fatalf("current user view = %+v", view.CurrentUser) - } - if !view.CanCreateStick || view.NewStickURL != "/base/sticks/new" { - t.Fatalf("create-stick presentation = can create %t, URL %q", view.CanCreateStick, view.NewStickURL) - } - if view.HomeURL != "/base/" || view.StylesheetURL != "/base/assets/styles.css" || view.LogoutAction != "/base/auth/logout" { - t.Fatalf("mounted page URLs = home %q, stylesheet %q, logout %q", view.HomeURL, view.StylesheetURL, view.LogoutAction) - } - if len(view.Sticks) != 3 { - t.Fatalf("stick views = %d, want 3", len(view.Sticks)) - } - - available := view.Sticks[0] - if !available.CanClaim || available.HeldByMe || available.HeldByOther { - t.Fatalf("available stick view = %+v", available) - } - mine := view.Sticks[1] - if !mine.HeldByMe || mine.HeldDuration != "1h 35min" || mine.ActionForm.Action != "/base/sticks/mine/release" { - t.Fatalf("held-by-me stick view = %+v", mine) - } - theirs := view.Sticks[2] - if !theirs.HeldByOther || theirs.ActionForm == nil { - t.Fatalf("subscribed held-by-other stick view = %+v", theirs) - } - if theirs.DetailURL != "/base/sticks/theirs" || theirs.ActionForm.Action != "/base/sticks/theirs/notify/cancel" { - t.Fatalf("held-by-other URLs = detail %q, action %q", theirs.DetailURL, theirs.ActionForm.Action) - } - if !view.ShowArchivedSticks || len(view.ArchivedSticks) != 1 || view.ArchivedSticks[0].RestoreForm == nil { - t.Fatalf("archived stick presentation = show %t, views %+v", view.ShowArchivedSticks, view.ArchivedSticks) - } -} - -func TestDetailViewModelMapsStateActionsAndFormattedHistory(t *testing.T) { - now := time.Date(2026, time.August, 27, 18, 0, 0, 0, time.UTC) - location := time.FixedZone("configured", -4*60*60) - mapper := testViewModelMapper(t, location, now) - claimedAt := time.Date(2026, time.August, 27, 16, 5, 0, 0, time.UTC) - releasedAt := claimedAt.Add(time.Hour + 5*time.Minute) - held := domain.Stick{ - ID: "held", - Name: "Held", - Version: 8, - Holder: &domain.Holder{ - Sub: "holder-sub", - Email: "shared@example.com", - Reason: "shipping", - ClaimedAt: claimedAt, - }, - } - - mine := mapper.StickDetail(held, domain.Identity{Sub: "holder-sub"}, false, now, "csrf-token", DetailFormState{}) - if !mine.HeldByMe || mine.StateActionForm.Action != "/base/sticks/held/release" || mine.StatusLabel != "yours" || mine.StatusClass != "mine" { - t.Fatalf("holder detail view = %+v", mine) - } - if mine.HeldSince != "Aug 27 · 12:05" || mine.HeldDuration != "1h 55min" { - t.Fatalf("formatted hold = since %q, duration %q", mine.HeldSince, mine.HeldDuration) - } - - other := mapper.StickDetail(held, domain.Identity{Sub: "different-sub", Email: "shared@example.com"}, true, now, "csrf-token", DetailFormState{}) - if !other.HeldByOther || other.HeldByMe || other.StateActionForm.Action != "/base/sticks/held/notify/cancel" { - t.Fatalf("non-holder detail view = %+v", other) - } - - available := domain.Stick{ID: "available", Name: "Available", Version: 2} - adminAvailable := mapper.StickDetail(available, domain.Identity{IsAdmin: true}, false, now, "csrf-token", DetailFormState{}) - if !adminAvailable.CanClaim || !adminAvailable.CanRename || !adminAvailable.ShowAdminControls || adminAvailable.AdminActionForm.Action != "/base/sticks/available/archive" { - t.Fatalf("admin available detail view = %+v", adminAvailable) - } - archivedAt := now.Add(-time.Hour) - archived := available - archived.ArchivedAt = &archivedAt - adminArchived := mapper.StickDetail(archived, domain.Identity{IsAdmin: true}, false, now, "csrf-token", DetailFormState{}) - if !adminArchived.IsArchived || adminArchived.CanClaim || adminArchived.AdminActionForm.Action != "/base/sticks/available/unarchive" || adminArchived.StatusLabel != "archived" { - t.Fatalf("admin archived detail view = %+v", adminArchived) - } - - request := httptest.NewRequest("GET", "/sticks/available?page=2", nil) - renameValue := "bad/name" - view := mapper.Detail( - request, - domain.Identity{Sub: "viewer"}, - available, - []domain.Session{{ - HolderEmail: "holder@example.com", - Reason: "deploying", - ClaimedAt: claimedAt, - ReleasedAt: &releasedAt, - }}, - 2, - 3, - 41, - []int{1, 2, 3}, - nil, - DetailFormState{ - Alert: "presentation error", - RenameValue: &renameValue, - RenameError: "rename error", - ClaimReasonValue: "submitted reason", - ClaimReasonError: "claim error", - }, - ) - if len(view.Sessions) == 0 || len(view.PageLinks) == 0 || view.TotalSessionsLabel != "41 sessions total" || view.Error != "presentation error" { - t.Fatalf("detail page presentation = %+v", view) - } - if got := view.Sessions[0]; got.Duration != "1h 05min" || got.TimeRange != "Aug 27 · 12:05 → Aug 27 · 13:10" { - t.Fatalf("history session view = %+v", got) - } - if len(view.PageLinks) != 3 || !view.PageLinks[1].IsCurrent || view.PageLinks[1].URL != "/base/sticks/available?page=2" { - t.Fatalf("pagination views = %+v", view.PageLinks) - } - if view.Stick.RenameField.Value != renameValue || !view.Stick.RenameField.HasError || - view.Stick.ClaimReasonField.Value != "submitted reason" || !view.Stick.ClaimReasonField.HasError { - t.Fatalf("submitted field presentation = rename %+v claim %+v", view.Stick.RenameField, view.Stick.ClaimReasonField) - } -} - -func testViewModelMapper(t *testing.T, location *time.Location, now time.Time) Mapper { - t.Helper() - publicURL, err := publicurl.Parse("http://example.test/base") - if err != nil { - t.Fatal(err) - } - mapper := NewMapper(publicURL, location, true) - mapper.Now = func() time.Time { return now } - return mapper -} diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index d57c52b..0000000 --- a/package-lock.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "name": "the-stick-browser-tests", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "the-stick-browser-tests", - "devDependencies": { - "@playwright/test": "1.62.1" - } - }, - "node_modules/@playwright/test": { - "version": "1.62.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.62.1.tgz", - "integrity": "sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "playwright": "1.62.1" - }, - "bin": { - "playwright": "cli.js" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/playwright": { - "version": "1.62.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", - "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "playwright-core": "1.62.1" - }, - "bin": { - "playwright": "cli.js" - }, - "engines": { - "node": ">=20" - }, - "optionalDependencies": { - "fsevents": "2.3.2" - } - }, - "node_modules/playwright-core": { - "version": "1.62.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz", - "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "playwright-core": "cli.js" - }, - "engines": { - "node": ">=20" - } - } - } -} diff --git a/package.json b/package.json deleted file mode 100644 index 20bae46..0000000 --- a/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "the-stick-browser-tests", - "private": true, - "scripts": { - "test:browser": "playwright test" - }, - "devDependencies": { - "@playwright/test": "1.62.1" - } -} diff --git a/playwright.config.js b/playwright.config.js deleted file mode 100644 index 26f62a4..0000000 --- a/playwright.config.js +++ /dev/null @@ -1,18 +0,0 @@ -const { defineConfig } = require("@playwright/test"); - -module.exports = defineConfig({ - testDir: "./test/browser", - timeout: 120000, - expect: { - timeout: 10000, - }, - forbidOnly: !!process.env.CI, - retries: process.env.CI ? 2 : 0, - reporter: process.env.CI ? "line" : "list", - use: { - browserName: "chromium", - headless: true, - javaScriptEnabled: false, - trace: "retain-on-failure", - }, -}); diff --git a/test/browser/smoke.spec.js b/test/browser/smoke.spec.js deleted file mode 100644 index 9e9aad4..0000000 --- a/test/browser/smoke.spec.js +++ /dev/null @@ -1,561 +0,0 @@ -const { test, expect } = require("@playwright/test"); -const { spawn } = require("node:child_process"); -const { - createSign, - generateKeyPairSync, -} = require("node:crypto"); -const fs = require("node:fs/promises"); -const http = require("node:http"); -const net = require("node:net"); -const os = require("node:os"); -const path = require("node:path"); - -let application; -let stickSequence = 0; - -test.beforeAll(async () => { - application = await startApplication(); -}); - -test.beforeEach(() => { - application.provider.selectAccount("admin"); - application.provider.setAutoLogin(true); -}); - -test.afterAll(async () => { - if (application) { - await application.stop(); - } -}); - -test("authenticates and completes the main browser workflow", async ({ page }) => { - await page.goto(application.url, { waitUntil: "networkidle" }); - await expect(page).toHaveURL(`${application.url}/`); - await expect(page).toHaveTitle(/the grove/); - await expect(page.getByText("admin@example.com", { exact: true })).toBeVisible(); - await expect(page.locator(".pill--admin")).toHaveText("admin"); - - await createStick(page, application, uniqueStickName("main workflow")); - - await page.locator('input[name="reason"]').fill("browser smoke test"); - const claimResponsePromise = page.waitForResponse((response) => - response.request().method() === "POST" && response.url().endsWith("/claim"), - ); - await page.locator("button.btn-claim").click(); - expect((await claimResponsePromise).status()).toBe(303); - await expect(page.getByText("browser smoke test")).toBeVisible(); - - const releaseResponsePromise = page.waitForResponse((response) => - response.request().method() === "POST" && response.url().endsWith("/release"), - ); - await page.locator("button.btn-release").click(); - expect((await releaseResponsePromise).status()).toBe(303); - await expect(page.locator("button.btn-claim")).toBeVisible(); - await expect(page.getByText("browser smoke test", { exact: true })).toBeVisible(); -}); - -test("admin can rename, archive, and restore a stick", async ({ page }) => { - await loginAs(page, application, "admin"); - const originalName = uniqueStickName("admin lifecycle"); - const renamedName = uniqueStickName("renamed"); - await createStick(page, application, originalName); - - await page.locator("#stick-name").fill(renamedName); - await page.getByRole("button", { name: "Rename" }).click(); - await expect(page.getByRole("heading", { name: renamedName, exact: true })).toBeVisible(); - - await page.getByRole("button", { name: "Archive stick" }).click(); - await expect(page).toHaveURL(`${application.url}/`); - await expect(page.getByRole("heading", { name: "Archived sticks" })).toBeVisible(); - await page.getByRole("link", { name: new RegExp(escapeRegExp(renamedName)) }).click(); - await expect(page.getByText("archived", { exact: true })).toBeVisible(); - await expect(page.getByText("This stick is archived and cannot be claimed.")).toBeVisible(); - - await page.getByRole("button", { name: "Restore stick" }).click(); - await expect(page).toHaveURL(`${application.url}/`); - await page.getByRole("link", { name: new RegExp(escapeRegExp(renamedName)) }).click(); - await expect(page.getByRole("button", { name: /Pick up/ })).toBeVisible(); -}); - -test("regular users can use sticks but cannot administer them", async ({ browser, page }) => { - await loginAs(page, application, "admin"); - const detailURL = await createStick(page, application, uniqueStickName("regular user")); - const userContext = await browser.newContext(); - - try { - const userPage = await userContext.newPage(); - await loginAs(userPage, application, "user"); - await expect(userPage.locator(".pill--admin")).toHaveCount(0); - await expect(userPage.getByRole("link", { name: "New stick" })).toHaveCount(0); - - const forbidden = await userPage.goto(`${application.url}/sticks/new`); - expect(forbidden).not.toBeNull(); - expect(forbidden.status()).toBe(403); - await expect(userPage.getByRole("heading", { name: "Not allowed" })).toBeVisible(); - await expect(userPage.locator("body")).not.toContainText("internal error"); - - await userPage.goto(detailURL, { waitUntil: "networkidle" }); - await userPage.locator('input[name="reason"]').fill("regular user work"); - await userPage.getByRole("button", { name: /Pick up/ }).click(); - await expect(userPage.getByText("regular user work", { exact: true })).toBeVisible(); - await userPage.getByRole("button", { name: "Put down" }).click(); - await expect(userPage.getByRole("button", { name: /Pick up/ })).toBeVisible(); - } finally { - await userContext.close(); - } -}); - -test("users can subscribe to a held stick and see it released", async ({ browser, page }) => { - await loginAs(page, application, "admin"); - const detailURL = await createStick(page, application, uniqueStickName("notifications")); - const holderContext = await browser.newContext(); - const watcherContext = await browser.newContext(); - - try { - const holderPage = await holderContext.newPage(); - await loginAs(holderPage, application, "user"); - await holderPage.goto(detailURL, { waitUntil: "networkidle" }); - await holderPage.locator('input[name="reason"]').fill("holder work"); - await holderPage.getByRole("button", { name: /Pick up/ }).click(); - - const watcherPage = await watcherContext.newPage(); - await loginAs(watcherPage, application, "watcher"); - await watcherPage.goto(detailURL, { waitUntil: "networkidle" }); - await expect(watcherPage.getByText("in use", { exact: true })).toBeVisible(); - await expect(watcherPage.getByText("user@example.com", { exact: true })).toBeVisible(); - await watcherPage.getByRole("button", { name: "Notify me" }).click(); - await expect(watcherPage.getByRole("button", { name: "Cancel notification" })).toBeVisible(); - await watcherPage.getByRole("button", { name: "Cancel notification" }).click(); - await expect(watcherPage.getByRole("button", { name: "Notify me" })).toBeVisible(); - - await holderPage.getByRole("button", { name: "Put down" }).click(); - await watcherPage.reload({ waitUntil: "networkidle" }); - await expect(watcherPage.getByRole("button", { name: /Pick up/ })).toBeVisible(); - } finally { - await holderContext.close(); - await watcherContext.close(); - } -}); - -test("stale browser forms show a conflict instead of overwriting changes", async ({ browser, page }) => { - await loginAs(page, application, "admin"); - const originalName = uniqueStickName("stale form"); - const renamedName = uniqueStickName("fresh name"); - const detailURL = await createStick(page, application, originalName); - const staleContext = await browser.newContext(); - - try { - const stalePage = await staleContext.newPage(); - await loginAs(stalePage, application, "admin"); - await stalePage.goto(detailURL, { waitUntil: "networkidle" }); - const staleVersion = await stalePage.locator('form[action$="/rename"] input[name="version"]').inputValue(); - - await page.locator("#stick-name").fill(renamedName); - await page.getByRole("button", { name: "Rename" }).click(); - await expect(page.getByRole("heading", { name: renamedName, exact: true })).toBeVisible(); - - await stalePage.locator("#stick-name").fill(uniqueStickName("stale name")); - const conflictResponsePromise = stalePage.waitForResponse((response) => - response.request().method() === "POST" && response.url().endsWith("/rename"), - ); - await stalePage.getByRole("button", { name: "Rename" }).click(); - const conflictResponse = await conflictResponsePromise; - expect(conflictResponse.status()).toBe(409); - expect(new URL(stalePage.url()).search).toBe(""); - await expect(stalePage.getByText(/This stick changed since the page was loaded/)).toBeVisible(); - await expect(stalePage.getByRole("heading", { name: renamedName, exact: true })).toBeVisible(); - await expect(stalePage.locator("#stick-name")).toHaveValue(renamedName); - const freshVersion = await stalePage.locator('form[action$="/rename"] input[name="version"]').inputValue(); - expect(freshVersion).not.toBe(staleVersion); - } finally { - await staleContext.close(); - } -}); - -test("invalid browser forms display validation errors", async ({ page }) => { - await loginAs(page, application, "admin"); - await page.getByRole("link", { name: "New stick" }).click(); - await page.getByLabel("Stick name").fill("invalid/name"); - const invalidNameResponsePromise = page.waitForResponse((response) => - response.request().method() === "POST" && response.url().endsWith("/sticks/new"), - ); - await page.getByRole("button", { name: /Create stick/ }).click(); - const invalidNameResponse = await invalidNameResponsePromise; - expect(invalidNameResponse.status()).toBe(422); - expect(new URL(page.url()).search).toBe(""); - await expect(page.getByLabel("Stick name")).toHaveValue("invalid/name"); - await expect(page.getByLabel("Stick name")).toHaveAttribute("aria-invalid", "true"); - await expect(page.getByText(/only letters, digits, hyphens, and spaces/)).toBeVisible(); - - await page.goto(`${application.url}/`, { waitUntil: "networkidle" }); - await createStick(page, application, uniqueStickName("invalid reason")); - await page.locator('input[name="reason"]').fill(" "); - const invalidReasonResponsePromise = page.waitForResponse((response) => - response.request().method() === "POST" && response.url().endsWith("/claim"), - ); - await page.getByRole("button", { name: /Pick up/ }).click(); - const invalidReasonResponse = await invalidReasonResponsePromise; - expect(invalidReasonResponse.status()).toBe(422); - expect(new URL(page.url()).search).toBe(""); - await expect(page.locator('input[name="reason"]')).toHaveValue(" "); - await expect(page.locator('input[name="reason"]')).toHaveAttribute("aria-invalid", "true"); - await expect(page.getByText("Reason must be non-empty and at most 500 characters.", { exact: true })).toBeVisible(); -}); - -test("logout clears the browser session", async ({ page }) => { - await loginAs(page, application, "admin"); - const logoutResponsePromise = page.waitForResponse((response) => - response.url() === `${application.url}/auth/logout`, - ); - await page.getByRole("button", { name: "logout" }).click(); - const logoutResponse = await logoutResponsePromise; - expect(logoutResponse.status()).toBe(302); - expect(logoutResponse.headers().location).toBe("/auth/login"); - const cookies = await page.context().cookies(); - expect(cookies.some((cookie) => cookie.name === "stick_session")).toBe(false); -}); - -test("mounted applications keep browser navigation and assets under the mount path", async ({ browser }) => { - const mountedApplication = await startApplication({ mountPath: "/stick" }); - const mountedPage = await browser.newPage(); - const failedRequests = []; - const consoleErrors = []; - mountedPage.on("requestfailed", (request) => failedRequests.push(request.url())); - mountedPage.on("console", (message) => { - if (message.type() === "error") { - consoleErrors.push(message.text()); - } - }); - - try { - await loginAs(mountedPage, mountedApplication, "admin"); - await expect(mountedPage.locator('link[rel="stylesheet"]')).toHaveAttribute( - "href", - "/stick/assets/styles.css", - ); - await expect(mountedPage.getByRole("link", { name: "New stick" })).toHaveAttribute( - "href", - "/stick/sticks/new", - ); - expect(failedRequests).toEqual([]); - expect(consoleErrors).toEqual([]); - - await mountedPage.getByRole("link", { name: "New stick" }).click(); - await mountedPage.getByLabel("Stick name").fill("invalid/name"); - const mountedValidationPromise = mountedPage.waitForResponse((response) => - response.request().method() === "POST" && response.url().endsWith("/stick/sticks/new"), - ); - await mountedPage.getByRole("button", { name: /Create stick/ }).click(); - const mountedValidation = await mountedValidationPromise; - expect(mountedValidation.status()).toBe(422); - expect(new URL(mountedPage.url()).search).toBe(""); - await expect(mountedPage.locator('link[rel="stylesheet"]')).toHaveAttribute("href", "/stick/assets/styles.css"); - await expect(mountedPage.getByLabel("Stick name")).toHaveValue("invalid/name"); - - const unmountedResponse = await mountedPage.goto(mountedApplication.origin); - expect(unmountedResponse).not.toBeNull(); - expect(unmountedResponse.status()).toBe(404); - } finally { - await mountedApplication.stop(); - } -}); - -async function startApplication({ mountPath = "" } = {}) { - const root = path.resolve(__dirname, "../.."); - const directory = await fs.mkdtemp(path.join(os.tmpdir(), "stick-browser-")); - const provider = await startOIDCProvider(); - const port = await freePort(); - const origin = `http://127.0.0.1:${port}`; - const url = `${origin}${mountPath}`; - const configPath = path.join(directory, "config.yaml"); - const config = [ - `database: ${yamlString(path.join(directory, "stick.db"))}`, - "server:", - ` public_url: ${yamlString(url)}`, - ` listen_addr: ${yamlString(`127.0.0.1:${port}`)}`, - "auth:", - " oidc:", - ` issuer: ${yamlString(provider.url)}`, - " client_id: browser-client", - " client_secret: browser-secret", - " session_secret: 0123456789abcdef0123456789abcdef", - " admin_emails:", - " - admin@example.com", - "notifications:", - " webhook:", - ` url: ${yamlString(`${provider.url}/webhook`)}`, - "", - ].join("\n"); - await fs.writeFile(configPath, config, { mode: 0o600 }); - - const output = []; - const child = spawn("go", ["run", "./cmd/stickd", "-config", configPath], { - cwd: root, - env: { ...process.env, GOWORK: "off" }, - stdio: ["ignore", "pipe", "pipe"], - }); - child.stdout.on("data", (chunk) => output.push(chunk.toString())); - child.stderr.on("data", (chunk) => output.push(chunk.toString())); - - try { - await waitForHealth(url, child); - } catch (error) { - await stopProcess(child); - await provider.stop(); - throw new Error(`${error.message}\napplication output:\n${output.join("")}`); - } - - return { - origin, - url, - provider, - stop: async () => { - await stopProcess(child); - await provider.stop(); - await fs.rm(directory, { recursive: true, force: true }); - }, - }; -} - -async function startOIDCProvider() { - const { privateKey, publicKey } = generateKeyPairSync("rsa", { - modulusLength: 2048, - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "jwk" }, - }); - const accounts = { - admin: { - sub: "browser-admin", - name: "Browser Admin", - email: "admin@example.com", - email_verified: true, - }, - user: { - sub: "browser-user", - name: "Browser User", - email: "user@example.com", - email_verified: true, - }, - watcher: { - sub: "browser-watcher", - name: "Browser Watcher", - email: "watcher@example.com", - email_verified: true, - }, - }; - let selectedAccount = "admin"; - let autoLogin = true; - const pendingIdentities = new Map(); - const server = http.createServer(async (request, response) => { - const requestURL = new URL(request.url, providerURL(server)); - if (requestURL.pathname === "/.well-known/openid-configuration") { - return sendJSON(response, { - issuer: providerURL(server), - authorization_endpoint: `${providerURL(server)}/authorize`, - token_endpoint: `${providerURL(server)}/token`, - jwks_uri: `${providerURL(server)}/keys`, - }); - } - if (requestURL.pathname === "/authorize") { - const code = `browser-code-${requestURL.searchParams.get("state")}`; - pendingIdentities.set(code, accounts[selectedAccount]); - if (!autoLogin) { - return sendHTML(response, "

Fake OIDC sign-in

"); - } - const redirect = new URL(requestURL.searchParams.get("redirect_uri")); - redirect.searchParams.set("code", code); - redirect.searchParams.set("state", requestURL.searchParams.get("state")); - response.writeHead(302, { Location: redirect.toString() }); - response.end(); - return; - } - if (requestURL.pathname === "/token") { - const values = new URLSearchParams(await readRequest(request)); - const code = values.get("code"); - const identity = pendingIdentities.get(code) || accounts[selectedAccount]; - pendingIdentities.delete(code); - return sendJSON(response, { - access_token: "browser-access-token", - token_type: "Bearer", - expires_in: 600, - id_token: signIDToken(privateKey, providerURL(server), identity), - }); - } - if (requestURL.pathname === "/keys") { - return sendJSON(response, { - keys: [{ ...publicKey, kid: "browser-e2e", alg: "RS256", use: "sig" }], - }); - } - if (requestURL.pathname === "/webhook") { - await readRequest(request); - response.writeHead(204); - response.end(); - return; - } - response.writeHead(404); - response.end(); - }); - await listen(server); - return { - url: providerURL(server), - selectAccount(account) { - if (!accounts[account]) { - throw new Error(`unknown fake OIDC account: ${account}`); - } - selectedAccount = account; - }, - setAutoLogin(enabled) { - autoLogin = enabled; - }, - stop: () => close(server), - }; -} - -function signIDToken(privateKey, issuer, identity) { - const header = { alg: "RS256", kid: "browser-e2e", typ: "JWT" }; - const now = Math.floor(Date.now() / 1000); - const payload = { - iss: issuer, - sub: identity.sub, - aud: "browser-client", - exp: now + 600, - iat: now, - name: identity.name, - email: identity.email, - email_verified: identity.email_verified, - }; - const encodedHeader = base64url(JSON.stringify(header)); - const encodedPayload = base64url(JSON.stringify(payload)); - const input = `${encodedHeader}.${encodedPayload}`; - const signer = createSign("RSA-SHA256"); - signer.update(input); - signer.end(); - return `${input}.${signer.sign(privateKey).toString("base64url")}`; -} - -async function waitForHealth(url, child) { - const deadline = Date.now() + 90000; - while (Date.now() < deadline) { - if (child.exitCode !== null) { - throw new Error(`stickd exited with code ${child.exitCode}`); - } - try { - const response = await fetch(`${url}/healthz`); - if (response.status === 200) { - return; - } - } catch { - // The binary may still be compiling or starting. - } - await delay(100); - } - throw new Error("stickd did not become healthy"); -} - -async function stopProcess(child) { - if (child.exitCode !== null) { - return; - } - child.kill("SIGINT"); - await new Promise((resolve) => { - const timer = setTimeout(() => { - child.kill("SIGKILL"); - resolve(); - }, 10000); - child.once("exit", () => { - clearTimeout(timer); - resolve(); - }); - }); -} - -function providerURL(server) { - const address = server.address(); - return `http://127.0.0.1:${address.port}`; -} - -function sendJSON(response, body) { - response.writeHead(200, { "Content-Type": "application/json" }); - response.end(JSON.stringify(body)); -} - -function readRequest(request) { - return new Promise((resolve, reject) => { - const chunks = []; - request.on("data", (chunk) => chunks.push(chunk)); - request.on("end", () => resolve(Buffer.concat(chunks).toString())); - request.on("error", reject); - }); -} - -function sendHTML(response, body) { - response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); - response.end(body); -} - -function listen(server) { - return new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", resolve); - }); -} - -function close(server) { - return new Promise((resolve) => server.close(resolve)); -} - -async function loginAs(page, application, account) { - application.provider.selectAccount(account); - await page.goto(`${application.url}/auth/login`, { waitUntil: "networkidle" }); - await expect(page).toHaveURL(`${application.url}/`); -} - -async function createStick(page, application, name) { - await page.getByRole("link", { name: "New stick" }).click(); - await expect(page).toHaveURL(`${application.url}/sticks/new`); - await page.getByLabel("Stick name").fill(name); - const createResponsePromise = page.waitForResponse((response) => - response.request().method() === "POST" && response.url().endsWith("/sticks/new"), - ); - await page.getByRole("button", { name: /Create stick/ }).click(); - const createResponse = await createResponsePromise; - expect(createResponse.status()).toBe(303); - const applicationPath = new URL(application.url).pathname.replace(/\/$/, ""); - expect(createResponse.headers().location).toBe(`${applicationPath}/`); - await expect(page).toHaveURL(`${application.url}/`); - await page.getByRole("link", { name: new RegExp(escapeRegExp(name)) }).click(); - await expect(page.getByRole("heading", { name, exact: true })).toBeVisible(); - return page.url(); -} - -function uniqueStickName(label) { - stickSequence += 1; - return `Browser ${label} ${process.pid} ${stickSequence}`; -} - -function escapeRegExp(value) { - return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} - -function freePort() { - const server = net.createServer(); - return new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", () => { - const port = server.address().port; - server.close(() => resolve(port)); - }); - }); -} - -function yamlString(value) { - return JSON.stringify(value); -} - -function base64url(value) { - return Buffer.from(value).toString("base64url"); -} - -function delay(milliseconds) { - return new Promise((resolve) => setTimeout(resolve, milliseconds)); -} diff --git a/test/e2e/stickd_test.go b/test/e2e/stickd_test.go deleted file mode 100644 index e937512..0000000 --- a/test/e2e/stickd_test.go +++ /dev/null @@ -1,496 +0,0 @@ -// Package e2e_test exercises end-to-end behavior. -package e2e_test - -import ( - "bytes" - "crypto/rand" - "crypto/rsa" - "encoding/base64" - "encoding/json" - "fmt" - "html" - "io" - "net" - "net/http" - "net/http/cookiejar" - "net/http/httptest" - "net/url" - "os" - "os/exec" - "path/filepath" - "regexp" - "runtime" - "strconv" - "strings" - "testing" - "time" - - "github.com/golang-jwt/jwt/v5" - "uuid" - - "stick/test/testsupport/mongotest" -) - -func TestRunningBinarySupportsOIDCSessionCSRFAndReleaseWebhook(t *testing.T) { - runReleaseNotificationE2E(t, "webhook", func(body []byte, createdID string) error { - var payload map[string]any - if err := json.Unmarshal(body, &payload); err != nil { - return fmt.Errorf("webhook payload: %w", err) - } - if payload["stick_id"] != createdID || payload["recipient_email"] != "admin@example.com" { - return fmt.Errorf("webhook payload = %s", body) - } - return nil - }) -} - -func TestRunningBinarySupportsOIDCSessionCSRFAndReleaseTeams(t *testing.T) { - runReleaseNotificationE2E(t, "teams", func(body []byte, createdID string) error { - var payload struct { - Type string `json:"@type"` - Context string `json:"@context"` - Title string `json:"title"` - Sections []struct { - Facts []struct { - Name string `json:"name"` - Value string `json:"value"` - } `json:"facts"` - } `json:"sections"` - PotentialActions []struct { - Targets []struct { - URI string `json:"uri"` - } `json:"targets"` - } `json:"potentialAction"` - } - if err := json.Unmarshal(body, &payload); err != nil { - return fmt.Errorf("Teams payload: %w", err) - } - if payload.Type != "MessageCard" || payload.Context != "http://schema.org/extensions" { - return fmt.Errorf("Teams card metadata = %+v", payload) - } - if payload.Title != "Deploy Key is available" || len(payload.Sections) != 1 || len(payload.Sections[0].Facts) < 1 { - return fmt.Errorf("Teams card content = %+v", payload) - } - if payload.Sections[0].Facts[0].Value != "Deploy Key" { - return fmt.Errorf("Teams stick fact = %+v", payload.Sections[0].Facts[0]) - } - if len(payload.PotentialActions) != 1 || len(payload.PotentialActions[0].Targets) != 1 || - !strings.HasSuffix(payload.PotentialActions[0].Targets[0].URI, "/sticks/"+createdID) { - return fmt.Errorf("Teams action = %+v", payload.PotentialActions) - } - return nil - }) -} - -func TestRunningBinarySupportsMultipleInstancesOfOneNotificationBackend(t *testing.T) { - first := newWebhookEndpoint(t) - second := newWebhookEndpoint(t) - notificationConfig := fmt.Sprintf(" webhook:\n - url: %s\n - url: %s", yamlString(first.server.URL), yamlString(second.server.URL)) - runReleaseNotificationConfigE2E(t, filepath.Join(t.TempDir(), "stick.db"), notificationConfig, []*webhookEndpoint{first, second}, func(body []byte, createdID string) error { - var payload map[string]any - if err := json.Unmarshal(body, &payload); err != nil { - return fmt.Errorf("webhook payload: %w", err) - } - if payload["stick_id"] != createdID || payload["recipient_email"] != "admin@example.com" { - return fmt.Errorf("webhook payload = %s", body) - } - return nil - }) -} - -func TestRunningBinarySupportsMongoDBPersistence(t *testing.T) { - baseURL := mongotest.Start(t) - databaseURL := mongotest.IsolatedURL(t, baseURL, "stick_e2e") - endpoint := newWebhookEndpoint(t) - notificationConfig := fmt.Sprintf(" webhook:\n url: %s", yamlString(endpoint.server.URL)) - runReleaseNotificationConfigE2E(t, databaseURL, notificationConfig, []*webhookEndpoint{endpoint}, func(body []byte, createdID string) error { - var payload map[string]any - if err := json.Unmarshal(body, &payload); err != nil { - return fmt.Errorf("webhook payload: %w", err) - } - if payload["stick_id"] != createdID || payload["recipient_email"] != "admin@example.com" { - return fmt.Errorf("webhook payload = %s", body) - } - return nil - }) -} - -type webhookEndpoint struct { - server *httptest.Server - calls chan []byte -} - -func newWebhookEndpoint(t *testing.T) *webhookEndpoint { - t.Helper() - endpoint := &webhookEndpoint{calls: make(chan []byte, 1)} - endpoint.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - if err != nil { - http.Error(w, "read body", http.StatusInternalServerError) - return - } - endpoint.calls <- body - w.WriteHeader(http.StatusNoContent) - })) - t.Cleanup(endpoint.server.Close) - return endpoint -} - -func runReleaseNotificationE2E(t *testing.T, backend string, validate func([]byte, string) error) { - endpoint := newWebhookEndpoint(t) - notificationConfig := fmt.Sprintf(" %s:\n url: %s", backend, yamlString(endpoint.server.URL)) - runReleaseNotificationConfigE2E(t, filepath.Join(t.TempDir(), "stick.db"), notificationConfig, []*webhookEndpoint{endpoint}, validate) -} - -func runReleaseNotificationConfigE2E( - t *testing.T, - databaseURL string, - notificationConfig string, - endpoints []*webhookEndpoint, - validate func([]byte, string) error, -) { - root := repositoryRoot(t) - binary := filepath.Join(t.TempDir(), "stickd") - build := exec.Command("go", "build", "-o", binary, "./cmd/stickd") - build.Dir = root - if output, err := build.CombinedOutput(); err != nil { - t.Fatalf("build stickd: %v\n%s", err, output) - } - - listenAddr := reserveAddress(t) - oidc := newFakeOIDCProvider(t, "client-id") - configPath := filepath.Join(t.TempDir(), "config.yaml") - config := fmt.Sprintf(`database: %s -server: - public_url: %s - listen_addr: %s -auth: - oidc: - issuer: %s - client_id: client-id - client_secret: client-secret - session_secret: 0123456789abcdef0123456789abcdef - admin_emails: - - admin@example.com -notifications: -%s - `, yamlString(databaseURL), yamlString("http://"+listenAddr+"/stick"), yamlString(listenAddr), yamlString(oidc.server.URL), notificationConfig) - if err := os.WriteFile(configPath, []byte(config), 0600); err != nil { - t.Fatal(err) - } - - var logs bytes.Buffer - process := exec.Command(binary, "-config", configPath) - process.Dir = root - process.Stdout = &logs - process.Stderr = &logs - if err := process.Start(); err != nil { - t.Fatalf("start stickd: %v", err) - } - t.Cleanup(func() { - if process.ProcessState == nil || !process.ProcessState.Exited() { - _ = process.Process.Kill() - _ = process.Wait() - } - }) - - baseURL := "http://" + listenAddr - waitForURL(t, baseURL+"/stick/healthz", process, &logs) - jar, err := cookiejar.New(nil) - if err != nil { - t.Fatal(err) - } - client := &http.Client{Jar: jar} - loginResponse := mustRequest(t, client, http.MethodGet, baseURL+"/stick/auth/login", "", nil) - if loginResponse.StatusCode != http.StatusOK { - t.Fatalf("login final status = %d: %s", loginResponse.StatusCode, readResponseBody(t, loginResponse)) - } - loginResponse.Body.Close() - - uiResponse := mustRequest(t, client, http.MethodGet, baseURL+"/stick/", "", nil) - if uiResponse.StatusCode != http.StatusOK { - t.Fatalf("authenticated UI status = %d: %s", uiResponse.StatusCode, readResponseBody(t, uiResponse)) - } - uiResponse.Body.Close() - - newStickResponse := mustRequest(t, client, http.MethodGet, baseURL+"/stick/sticks/new", "", nil) - if newStickResponse.StatusCode != http.StatusOK { - t.Fatalf("new stick form status = %d: %s", newStickResponse.StatusCode, readResponseBody(t, newStickResponse)) - } - newStickBody := readResponseBody(t, newStickResponse) - csrfToken := formValue(t, newStickBody, "csrf_token") - createForm := url.Values{"csrf_token": {csrfToken}, "name": {"Deploy Key"}} - createResponse := mustRequest(t, client, http.MethodPost, baseURL+"/stick/sticks/new", createForm.Encode(), map[string]string{ - "Content-Type": "application/x-www-form-urlencoded", - }) - if createResponse.StatusCode != http.StatusOK { - t.Fatalf("create status = %d: %s", createResponse.StatusCode, readResponseBody(t, createResponse)) - } - dashboardBody := readResponseBody(t, createResponse) - createdMatch := regexp.MustCompile(`href="/stick/sticks/([^"]+)"`).FindStringSubmatch(dashboardBody) - if len(createdMatch) != 2 { - t.Fatalf("created stick link not found in dashboard: %s", dashboardBody) - } - createdID := createdMatch[1] - if _, err := uuid.Parse(createdID); err != nil { - t.Fatalf("created stick ID = %q, want UUID: %v", createdID, err) - } - - detailResponse := mustRequest(t, client, http.MethodGet, baseURL+"/stick/sticks/"+createdID, "", nil) - detailBody := readResponseBody(t, detailResponse) - csrfToken = formValue(t, detailBody, "csrf_token") - version := formValue(t, detailBody, "version") - if csrfToken == "" || version == "" { - t.Fatalf("detail form missing CSRF token or version: %s", detailBody) - } - subscribeForm := url.Values{"csrf_token": {csrfToken}, "version": {version}} - subscribeResponse := mustRequest(t, client, http.MethodPost, baseURL+"/stick/sticks/"+createdID+"/notify", subscribeForm.Encode(), map[string]string{"Content-Type": "application/x-www-form-urlencoded"}) - if subscribeResponse.StatusCode != http.StatusOK { - t.Fatalf("subscribe status = %d: %s", subscribeResponse.StatusCode, readResponseBody(t, subscribeResponse)) - } - subscribedDetailBody := readResponseBody(t, subscribeResponse) - csrfToken = formValue(t, subscribedDetailBody, "csrf_token") - version = formValue(t, subscribedDetailBody, "version") - claimForm := url.Values{"csrf_token": {csrfToken}, "version": {version}, "reason": {"deploying"}} - claimResponse := mustRequest(t, client, http.MethodPost, baseURL+"/stick/sticks/"+createdID+"/claim", claimForm.Encode(), map[string]string{ - "Content-Type": "application/x-www-form-urlencoded", - }) - if claimResponse.StatusCode != http.StatusOK { - t.Fatalf("claim status = %d: %s", claimResponse.StatusCode, readResponseBody(t, claimResponse)) - } - claimBody := readResponseBody(t, claimResponse) - if !strings.Contains(claimBody, "admin@example.com") || !strings.Contains(claimBody, "deploying") { - t.Fatalf("claim page did not retain the authenticated holder: %s", claimBody) - } - csrfToken = formValue(t, claimBody, "csrf_token") - version = formValue(t, claimBody, "version") - releaseForm := url.Values{"csrf_token": {csrfToken}, "version": {version}} - releaseResponse := mustRequest(t, client, http.MethodPost, baseURL+"/stick/sticks/"+createdID+"/release", releaseForm.Encode(), map[string]string{"Content-Type": "application/x-www-form-urlencoded"}) - if releaseResponse.StatusCode != http.StatusOK { - t.Fatalf("release status = %d: %s\nprocess logs:\n%s", releaseResponse.StatusCode, readResponseBody(t, releaseResponse), logs.String()) - } - releaseResponse.Body.Close() - - for i, endpoint := range endpoints { - select { - case body := <-endpoint.calls: - if err := validate(body, createdID); err != nil { - t.Fatalf("notification endpoint %d: %v", i+1, err) - } - case <-time.After(5 * time.Second): - t.Fatalf("release notification endpoint %d was not delivered; process logs:\n%s", i+1, logs.String()) - } - } - - if err := process.Process.Signal(os.Interrupt); err != nil { - t.Fatalf("interrupt stickd: %v", err) - } - if err := process.Wait(); err != nil { - t.Fatalf("stickd exit: %v\n%s", err, logs.String()) - } -} - -func TestComposeDeclaresContainerRuntimeHardening(t *testing.T) { - root := repositoryRoot(t) - envFile := filepath.Join(t.TempDir(), ".env") - if err := os.WriteFile(envFile, nil, 0600); err != nil { - t.Fatal(err) - } - compose, err := os.ReadFile(filepath.Join(root, "compose.yaml")) - if err != nil { - t.Fatal(err) - } - compose = bytes.Replace(compose, []byte("- .env"), []byte("- "+envFile), 1) - composePath := filepath.Join(t.TempDir(), "compose.yaml") - if err := os.WriteFile(composePath, compose, 0600); err != nil { - t.Fatal(err) - } - command := exec.Command("docker", "compose", "--project-directory", root, "-f", composePath, "config", "--format", "json") - command.Dir = root - output, err := command.CombinedOutput() - if err != nil { - t.Fatalf("docker compose config: %v\n%s", err, output) - } - var config struct { - Services map[string]struct { - ReadOnly bool `json:"read_only"` - CapDrop []string `json:"cap_drop"` - SecurityOpt []string `json:"security_opt"` - Tmpfs []string `json:"tmpfs"` - } `json:"services"` - } - if err := json.Unmarshal(output, &config); err != nil { - t.Fatal(err) - } - service, ok := config.Services["stickd"] - if !ok { - t.Fatal("compose configuration has no stickd service") - } - if !service.ReadOnly { - t.Fatal("stickd container is not read-only") - } - if !containsString(service.CapDrop, "ALL") { - t.Fatalf("cap_drop = %v, want ALL", service.CapDrop) - } - if !containsString(service.SecurityOpt, "no-new-privileges:true") { - t.Fatalf("security_opt = %v, want no-new-privileges:true", service.SecurityOpt) - } - if !containsPrefix(service.Tmpfs, "/tmp:") { - t.Fatalf("tmpfs = %v, want /tmp mount", service.Tmpfs) - } -} - -type fakeOIDCProvider struct { - server *httptest.Server -} - -func newFakeOIDCProvider(t *testing.T, clientID string) fakeOIDCProvider { - t.Helper() - key, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Fatal(err) - } - var providerServer *httptest.Server - var idToken string - providerServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch r.URL.Path { - case "/.well-known/openid-configuration": - _ = json.NewEncoder(w).Encode(map[string]string{ - "issuer": providerServer.URL, "authorization_endpoint": providerServer.URL + "/authorize", - "token_endpoint": providerServer.URL + "/token", "jwks_uri": providerServer.URL + "/keys", - }) - case "/authorize": - redirectURL, err := url.Parse(r.URL.Query().Get("redirect_uri")) - if err != nil { - http.Error(w, "invalid redirect", http.StatusBadRequest) - return - } - query := redirectURL.Query() - query.Set("code", "e2e-code") - query.Set("state", r.URL.Query().Get("state")) - redirectURL.RawQuery = query.Encode() - http.Redirect(w, r, redirectURL.String(), http.StatusFound) - case "/token": - _ = json.NewEncoder(w).Encode(map[string]any{"access_token": "access-token", "token_type": "Bearer", "id_token": idToken}) - case "/keys": - _ = json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]string{{ - "kty": "RSA", "use": "sig", "alg": "RS256", "kid": "e2e-key", - "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()), "e": base64.RawURLEncoding.EncodeToString([]byte{1, 0, 1}), - }}}) - default: - http.NotFound(w, r) - } - })) - claims := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ - "iss": providerServer.URL, "sub": "admin-sub", "aud": clientID, - "exp": time.Now().Add(time.Hour).Unix(), "iat": time.Now().Unix(), - "name": "Admin", "email": "admin@example.com", "email_verified": true, - }) - claims.Header["kid"] = "e2e-key" - idToken, err = claims.SignedString(key) - if err != nil { - providerServer.Close() - t.Fatal(err) - } - t.Cleanup(providerServer.Close) - return fakeOIDCProvider{server: providerServer} -} - -func repositoryRoot(t *testing.T) string { - t.Helper() - _, filename, _, ok := runtime.Caller(0) - if !ok { - t.Fatal("runtime.Caller failed") - } - return filepath.Clean(filepath.Join(filepath.Dir(filename), "..", "..")) -} - -func reserveAddress(t *testing.T) string { - t.Helper() - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - address := listener.Addr().String() - listener.Close() - return address -} - -func waitForURL(t *testing.T, target string, process *exec.Cmd, logs *bytes.Buffer) { - t.Helper() - deadline := time.Now().Add(90 * time.Second) - for { - if process.ProcessState != nil && process.ProcessState.Exited() { - t.Fatalf("%s process exited with %s:\n%s", target, process.ProcessState, logs.String()) - } - response, err := http.Get(target) - if err == nil { - body, _ := io.ReadAll(response.Body) - response.Body.Close() - if response.StatusCode == http.StatusOK { - return - } - _ = body - } - if time.Now().After(deadline) { - t.Fatalf("%s did not become ready: %v\nprocess logs:\n%s", target, err, logs.String()) - } - time.Sleep(25 * time.Millisecond) - } -} - -func mustRequest(t *testing.T, client *http.Client, method, target, body string, headers map[string]string) *http.Response { - t.Helper() - request, err := http.NewRequest(method, target, strings.NewReader(body)) - if err != nil { - t.Fatal(err) - } - for key, value := range headers { - request.Header.Set(key, value) - } - response, err := client.Do(request) - if err != nil { - t.Fatal(err) - } - return response -} - -func readResponseBody(t *testing.T, response *http.Response) string { - t.Helper() - body, err := io.ReadAll(response.Body) - response.Body.Close() - if err != nil { - t.Fatal(err) - } - return string(body) -} - -func formValue(t *testing.T, body, name string) string { - t.Helper() - match := regexp.MustCompile(`name="` + regexp.QuoteMeta(name) + `" value="([^"]+)"`).FindStringSubmatch(body) - if len(match) != 2 { - t.Fatalf("form value %q not found in %s", name, body) - } - return html.UnescapeString(match[1]) -} - -func yamlString(value string) string { return strconv.Quote(value) } - -func containsString(values []string, want string) bool { - for _, value := range values { - if value == want { - return true - } - } - return false -} - -func containsPrefix(values []string, prefix string) bool { - for _, value := range values { - if strings.HasPrefix(value, prefix) { - return true - } - } - return false -} diff --git a/test/integration/webui_csrf_test.go b/test/integration/webui_csrf_test.go deleted file mode 100644 index f756942..0000000 --- a/test/integration/webui_csrf_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package integration_test - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "stick/internal/auth" - domain "stick/internal/core" - "stick/internal/publicurl" - "stick/internal/web/render" - "stick/internal/web/security" -) - -func TestCSRFProtectionUsesLocalHTMLErrorsForBrowserRequests(t *testing.T) { - secret := []byte("secret-32-bytes-minimum-length!!") - sessionCookie := "session-cookie-value" - renderer := newTestRenderer(t) - var token string - protected := security.CSRFProtection(secret, renderer.ErrorPage)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - token = security.CSRFToken(r) - w.WriteHeader(http.StatusNoContent) - })) - get := httptest.NewRequest(http.MethodGet, "/base/", nil) - get.AddCookie(&http.Cookie{Name: security.SessionCookieName(), Value: sessionCookie}) - protected.ServeHTTP(httptest.NewRecorder(), get) - if token == "" { - t.Fatal("CSRF token is empty") - } - - for _, test := range []struct { - name string - body string - status int - text string - }{ - {name: "malformed form", body: "csrf_token=" + token + "&name=%zz", status: http.StatusBadRequest, text: "invalid or too large"}, - {name: "invalid token", body: "csrf_token=wrong", status: http.StatusForbidden, text: "Not allowed"}, - } { - t.Run(test.name, func(t *testing.T) { - request := httptest.NewRequest(http.MethodPost, "/base/sticks/new", strings.NewReader(test.body)) - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - request.AddCookie(&http.Cookie{Name: security.SessionCookieName(), Value: sessionCookie}) - request = request.WithContext(auth.WithIdentity(request.Context(), domain.Identity{Sub: "admin", IsAdmin: true})) - recorder := httptest.NewRecorder() - - protected.ServeHTTP(recorder, request) - - if recorder.Code != test.status || recorder.Header().Get("Content-Type") != "text/html; charset=utf-8" { - t.Fatalf("response = %d Content-Type %q", recorder.Code, recorder.Header().Get("Content-Type")) - } - body := recorder.Body.String() - if !strings.Contains(body, test.text) || !strings.Contains(body, `href="/base/"`) || !strings.Contains(body, `href="/base/assets/styles.css"`) { - t.Errorf("mounted error page missing expected content: %s", body) - } - if strings.Contains(body, "%zz") { - t.Error("error page leaked malformed form details") - } - }) - } -} - -func newTestRenderer(t *testing.T) render.Renderer { - t.Helper() - publicURL, err := publicurl.Parse("http://example.test/base") - if err != nil { - t.Fatal(err) - } - renderer, err := newWebUIRenderer(time.UTC, publicURL, true) - if err != nil { - t.Fatal(err) - } - return renderer -} diff --git a/test/integration/webui_form_test.go b/test/integration/webui_form_test.go deleted file mode 100644 index c16b571..0000000 --- a/test/integration/webui_form_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package integration_test - -import ( - "context" - "html" - "net/http" - "net/http/httptest" - "net/url" - "regexp" - "strconv" - "strings" - "testing" - "time" - - "stick/internal/adapters/persistence/sqlite" - "stick/internal/application" - "stick/internal/auth" - domain "stick/internal/core" - "stick/internal/publicurl" -) - -func TestUIFormsCarryVersionAndRejectStaleSubmission(t *testing.T) { - store, err := sqlite.Open(":memory:") - if err != nil { - t.Fatalf("sqlite.Open: %v", err) - } - t.Cleanup(func() { _ = store.Close() }) - ctx := context.Background() - stick, err := domain.NewStick("aa001", "original") - if err != nil { - t.Fatal(err) - } - if err := store.WithinTransaction(ctx, func(tx application.Transaction) error { - return tx.CreateStick(ctx, stick) - }); err != nil { - t.Fatal(err) - } - publicURL, err := publicurl.Parse("http://example.test/base") - if err != nil { - t.Fatal(err) - } - handler, _, err := newSticksHandler(application.NewService(store), time.UTC, publicURL, true) - if err != nil { - t.Fatal(err) - } - admin := domain.Identity{Sub: "admin", IsAdmin: true} - detail := httptest.NewRequest(http.MethodGet, "/sticks/aa001", nil) - detail.SetPathValue("id", "aa001") - detail = detail.WithContext(auth.WithIdentity(detail.Context(), admin)) - detailRecorder := httptest.NewRecorder() - handler.Detail(detailRecorder, detail) - match := regexp.MustCompile(`name="version" value="([^"]+)"`).FindStringSubmatch(detailRecorder.Body.String()) - if len(match) != 2 { - t.Fatalf("detail form did not carry a version") - } - stale := html.UnescapeString(match[1]) - current, err := store.GetStick(ctx, "aa001") - if err != nil { - t.Fatal(err) - } - if _, err := application.NewService(store).RenameStick(ctx, admin, "aa001", "newer", current.Version); err != nil { - t.Fatal(err) - } - - form := url.Values{"name": {"stale overwrite"}, "version": {stale}} - request := httptest.NewRequest(http.MethodPost, "/sticks/aa001/rename", strings.NewReader(form.Encode())) - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - request.SetPathValue("id", "aa001") - request = request.WithContext(auth.WithIdentity(request.Context(), admin)) - recorder := httptest.NewRecorder() - handler.Rename(recorder, request) - if recorder.Code != http.StatusConflict { - t.Fatalf("stale UI status = %d: %s", recorder.Code, recorder.Body.String()) - } - if location := recorder.Header().Get("Location"); location != "" { - t.Fatalf("stale response redirected to %q", location) - } - body := recorder.Body.String() - if !strings.Contains(body, "changed since") || !strings.Contains(body, "newer") { - t.Fatalf("stale response did not render current state: %s", body) - } - freshVersion := html.EscapeString(stickVersionForFormTest(t, store, "aa001")) - if !strings.Contains(body, `name="version" value="`+freshVersion+`"`) { - t.Fatalf("stale response missing fresh version %q", freshVersion) - } - if strings.Contains(body, "?error=") { - t.Fatal("stale response used query-string error transport") - } - stick, err = store.GetStick(ctx, "aa001") - if err != nil { - t.Fatal(err) - } - if stick.Name != "newer" || stick.Version != 2 { - t.Fatalf("stale UI request changed stick: %+v", stick) - } -} - -func stickVersionForFormTest(t *testing.T, store *sqlite.Store, id string) string { - t.Helper() - stick, err := store.GetStick(context.Background(), id) - if err != nil { - t.Fatal(err) - } - return strconv.FormatInt(stick.Version, 10) -} diff --git a/test/integration/webui_mutations_test.go b/test/integration/webui_mutations_test.go deleted file mode 100644 index 5f7a2f3..0000000 --- a/test/integration/webui_mutations_test.go +++ /dev/null @@ -1,468 +0,0 @@ -package integration_test - -import ( - "context" - "html" - "net/http" - "net/http/httptest" - "net/url" - "strconv" - "strings" - "testing" - "time" - - "stick/internal/adapters/persistence/sqlite" - "stick/internal/application" - "stick/internal/auth" - domain "stick/internal/core" - "stick/internal/web/sticks" -) - -type uiMutationScenario struct { - name string - setup func(*testing.T, *sqlite.Store) - identity domain.Identity - path string - form url.Values - serve func(*sticks.Handler, http.ResponseWriter, *http.Request) -} - -func TestUIMutationsRejectMissingAndStaleFormVersions(t *testing.T) { - scenarios := []uiMutationScenario{ - { - name: "rename", - setup: seedAvailableStick, - identity: domain.Identity{Sub: "admin", IsAdmin: true}, - path: "/sticks/aa001/rename", - form: url.Values{"name": {"renamed"}}, - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Rename(writer, request) - }, - }, - { - name: "archive", - setup: seedAvailableStick, - identity: domain.Identity{Sub: "admin", IsAdmin: true}, - path: "/sticks/aa001/archive", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Archive(writer, request) - }, - }, - { - name: "unarchive", - setup: func(t *testing.T, store *sqlite.Store) { - seedAvailableStick(t, store) - archiveWebUIStick(t, store, "aa001") - }, - identity: domain.Identity{Sub: "admin", IsAdmin: true}, - path: "/sticks/aa001/unarchive", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Unarchive(writer, request) - }, - }, - { - name: "claim", - setup: seedAvailableStick, - identity: domain.Identity{Sub: "u1"}, - path: "/sticks/aa001/claim", - form: url.Values{"reason": {"working"}}, - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Claim(writer, request) - }, - }, - { - name: "release", - setup: func(t *testing.T, store *sqlite.Store) { - seedAvailableStick(t, store) - claimWebUIStick(t, store, "aa001", domain.Identity{Sub: "u1"}, "working") - }, - identity: domain.Identity{Sub: "u1"}, - path: "/sticks/aa001/release", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Release(writer, request) - }, - }, - { - name: "subscribe", - setup: seedAvailableStick, - identity: domain.Identity{Sub: "u1"}, - path: "/sticks/aa001/notify", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Subscribe(writer, request) - }, - }, - { - name: "unsubscribe", - setup: func(t *testing.T, store *sqlite.Store) { - seedAvailableStick(t, store) - subscribeWebUIStick(t, store, "aa001", "u1", "Watcher", "watcher@example.com") - }, - identity: domain.Identity{Sub: "u1"}, - path: "/sticks/aa001/notify/cancel", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Unsubscribe(writer, request) - }, - }, - } - - for _, scenario := range scenarios { - t.Run(scenario.name, func(t *testing.T) { - for _, precondition := range []struct { - name string - version string - wantStatus int - }{ - {name: "missing", wantStatus: http.StatusBadRequest}, - {name: "stale", version: "999", wantStatus: http.StatusConflict}, - } { - t.Run(precondition.name, func(t *testing.T) { - store := newWebUITestDB(t) - scenario.setup(t, store) - before := currentWebUIStick(t, store, "aa001") - handler, _, err := newSticksHandler(application.NewService(store), time.UTC, webuiPublicURL(t, "/base"), true) - if err != nil { - t.Fatal(err) - } - form := cloneValues(scenario.form) - if precondition.version != "" { - form.Set("version", precondition.version) - } - request := newUIFormRequest(scenario.path, form, scenario.identity) - recorder := httptest.NewRecorder() - scenario.serve(handler, recorder, request) - if recorder.Code != precondition.wantStatus { - t.Fatalf("status = %d, want %d: %s", recorder.Code, precondition.wantStatus, recorder.Body.String()) - } - if got := recorder.Header().Get("Location"); got != "" { - t.Fatalf("Location = %q, want no redirect", got) - } - body := recorder.Body.String() - if precondition.wantStatus == http.StatusConflict { - for _, want := range []string{ - "This stick changed since the page was loaded. Review its current state and try again.", - before.Name, - strconv.FormatInt(before.Version, 10), - } { - if !strings.Contains(body, want) { - t.Errorf("conflict page missing %q", want) - } - } - } - if strings.Contains(body, "?error=") { - t.Error("conflict page contains query-string error transport") - } - after := currentWebUIStick(t, store, "aa001") - if after.Version != before.Version || after.Name != before.Name { - t.Fatalf("conflicting request changed stick: before=%+v after=%+v", before, after) - } - }) - } - }) - } -} - -func TestUIMutationRedirectsAndErrors(t *testing.T) { - tests := []struct { - name string - setup func(*testing.T, *sqlite.Store) - identity domain.Identity - path string - form url.Values - serve func(*sticks.Handler, http.ResponseWriter, *http.Request) - wantLocation string - wantStatus int - wantMessage string - }{ - { - name: "rename redirects to the detail page", - setup: seedAvailableStick, - identity: domain.Identity{Sub: "admin", IsAdmin: true}, - path: "/sticks/aa001/rename", - form: url.Values{"name": {"renamed"}}, - wantLocation: "/base/sticks/aa001", - wantStatus: http.StatusSeeOther, - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Rename(writer, request) - }, - }, - { - name: "archive redirects to the dashboard", - setup: seedAvailableStick, - identity: domain.Identity{Sub: "admin", IsAdmin: true}, - path: "/sticks/aa001/archive", - wantLocation: "/base/", - wantStatus: http.StatusSeeOther, - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Archive(writer, request) - }, - }, - { - name: "archive already archived stick explains the conflict", - setup: func(t *testing.T, store *sqlite.Store) { - seedAvailableStick(t, store) - archiveWebUIStick(t, store, "aa001") - }, - identity: domain.Identity{Sub: "admin", IsAdmin: true}, - path: "/sticks/aa001/archive", - wantStatus: http.StatusConflict, - wantMessage: "This stick is already archived.", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Archive(writer, request) - }, - }, - { - name: "unarchive redirects to the dashboard", - setup: func(t *testing.T, store *sqlite.Store) { - seedAvailableStick(t, store) - archiveWebUIStick(t, store, "aa001") - }, - identity: domain.Identity{Sub: "admin", IsAdmin: true}, - path: "/sticks/aa001/unarchive", - wantLocation: "/base/", - wantStatus: http.StatusSeeOther, - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Unarchive(writer, request) - }, - }, - { - name: "unarchive active stick explains the conflict", - setup: seedAvailableStick, - identity: domain.Identity{Sub: "admin", IsAdmin: true}, - path: "/sticks/aa001/unarchive", - wantStatus: http.StatusConflict, - wantMessage: "This stick is not archived.", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Unarchive(writer, request) - }, - }, - { - name: "release redirects back to the stick", - setup: seedHeldBy("u1"), - identity: domain.Identity{Sub: "u1"}, - path: "/sticks/aa001/release", - wantLocation: "/base/sticks/aa001", - wantStatus: http.StatusSeeOther, - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Release(writer, request) - }, - }, - { - name: "archive held stick explains the conflict", - setup: seedHeldBy("holder"), - identity: domain.Identity{Sub: "admin", IsAdmin: true}, - path: "/sticks/aa001/archive", - wantStatus: http.StatusConflict, - wantMessage: "This stick is currently held.", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Archive(writer, request) - }, - }, - { - name: "claim held stick explains the conflict", - setup: seedHeldBy("holder"), - identity: domain.Identity{Sub: "u1"}, - path: "/sticks/aa001/claim", - form: url.Values{"reason": {"again"}}, - wantStatus: http.StatusConflict, - wantMessage: "This stick is already held.", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Claim(writer, request) - }, - }, - { - name: "claim archived stick explains the conflict", - setup: func(t *testing.T, store *sqlite.Store) { - seedAvailableStick(t, store) - archiveWebUIStick(t, store, "aa001") - }, - identity: domain.Identity{Sub: "admin", IsAdmin: true}, - path: "/sticks/aa001/claim", - form: url.Values{"reason": {"working"}}, - wantStatus: http.StatusConflict, - wantMessage: "This stick is archived and cannot be claimed.", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Claim(writer, request) - }, - }, - { - name: "release by non-holder explains the ownership error", - setup: seedHeldBy("holder"), - identity: domain.Identity{Sub: "u1"}, - path: "/sticks/aa001/release", - wantStatus: http.StatusForbidden, - wantMessage: "You can only put down a stick that you currently hold.", - serve: func(handler *sticks.Handler, writer http.ResponseWriter, request *http.Request) { - handler.Release(writer, request) - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - store := newWebUITestDB(t) - test.setup(t, store) - handler, _, err := newSticksHandler(application.NewService(store), time.UTC, webuiPublicURL(t, "/base"), true) - if err != nil { - t.Fatal(err) - } - stick, err := store.GetStick(context.Background(), "aa001") - if err != nil { - t.Fatal(err) - } - form := cloneValues(test.form) - form.Set("version", strconv.FormatInt(stick.Version, 10)) - request := newUIFormRequest(test.path, form, test.identity) - recorder := httptest.NewRecorder() - test.serve(handler, recorder, request) - if recorder.Code != test.wantStatus { - t.Fatalf("status = %d, want %d: %s", recorder.Code, test.wantStatus, recorder.Body.String()) - } - if got := recorder.Header().Get("Location"); got != test.wantLocation { - t.Fatalf("Location = %q, want %q", got, test.wantLocation) - } - if test.wantMessage != "" { - if !strings.Contains(recorder.Body.String(), test.wantMessage) { - t.Errorf("response missing %q", test.wantMessage) - } - if got := recorder.Header().Get("Content-Type"); !strings.HasPrefix(got, "text/html") { - t.Errorf("Content-Type = %q, want HTML", got) - } - if strings.Contains(recorder.Body.String(), "?error=") { - t.Error("response contains query-string error transport") - } - } - }) - } -} - -func TestUIRenameValidationRendersCurrentFormWithSubmittedValue(t *testing.T) { - store := newWebUITestDB(t) - seedAvailableStick(t, store) - handler, _, err := newSticksHandler(application.NewService(store), time.UTC, webuiPublicURL(t, "/base"), true) - if err != nil { - t.Fatal(err) - } - form := url.Values{"name": {"bad/name"}, "version": {webUIStickVersion(t, store, "aa001")}} - request := newUIFormRequest("/sticks/aa001/rename", form, domain.Identity{Sub: "admin", IsAdmin: true}) - recorder := httptest.NewRecorder() - - handler.Rename(recorder, request) - - if recorder.Code != http.StatusUnprocessableEntity || recorder.Header().Get("Location") != "" { - t.Fatalf("response = %d Location %q", recorder.Code, recorder.Header().Get("Location")) - } - for _, want := range []string{ - `value="bad/name"`, - `aria-invalid="true"`, - `aria-describedby="rename-name-error"`, - `id="rename-name-error" role="alert"`, - invalidNameText, - } { - if !strings.Contains(recorder.Body.String(), want) { - t.Errorf("validation response missing %q", want) - } - } - if strings.Contains(recorder.Body.String(), "?error=") { - t.Error("rename validation used query-string error transport") - } - if stick := currentWebUIStick(t, store, "aa001"); stick.Name != "prod" || stick.Version != 1 { - t.Fatalf("invalid rename changed stick: %+v", stick) - } -} - -const invalidNameText = "Name must be non-empty, at most 100 characters, and contain only letters, digits, hyphens, and spaces." - -func TestUITransactionVersionConflictRendersLatestStateAndFreshVersion(t *testing.T) { - store := newWebUITestDB(t) - seedAvailableStick(t, store) - conflictingStore := &versionConflictStore{ - Store: store, - inject: true, - latestName: "newer transaction state", - } - handler, _, err := newSticksHandler(application.NewService(conflictingStore), time.UTC, webuiPublicURL(t, "/base"), true) - if err != nil { - t.Fatal(err) - } - staleVersion := webUIStickVersion(t, store, "aa001") - request := newUIFormRequest("/sticks/aa001/rename", url.Values{ - "name": {"attempted overwrite"}, "version": {staleVersion}, - }, domain.Identity{Sub: "admin", IsAdmin: true}) - recorder := httptest.NewRecorder() - - handler.Rename(recorder, request) - - if recorder.Code != http.StatusConflict || recorder.Header().Get("Location") != "" { - t.Fatalf("response = %d Location %q", recorder.Code, recorder.Header().Get("Location")) - } - latest := currentWebUIStick(t, store, "aa001") - if latest.Name != conflictingStore.latestName || latest.Version != 2 { - t.Fatalf("latest stick = %+v", latest) - } - body := recorder.Body.String() - for _, want := range []string{ - conflictingStore.latestName, - "Review its current state and try again.", - html.EscapeString(strconv.FormatInt(latest.Version, 10)), - } { - if !strings.Contains(body, want) { - t.Errorf("conflict response missing %q", want) - } - } - if strings.Contains(body, "attempted overwrite") || strings.Contains(body, "?error=") { - t.Error("conflict response rendered stale input or query-string error transport") - } -} - -type versionConflictStore struct { - application.Store - inject bool - latestName string -} - -func (s *versionConflictStore) WithinTransaction(ctx context.Context, work func(application.Transaction) error) error { - if !s.inject { - return s.Store.WithinTransaction(ctx, work) - } - s.inject = false - current, err := s.GetStick(ctx, "aa001") - if err != nil { - return err - } - next, err := domain.Rename(current, s.latestName) - if err != nil { - return err - } - if err := s.Store.WithinTransaction(ctx, func(tx application.Transaction) error { - return tx.SaveStick(ctx, next, current.Version) - }); err != nil { - return err - } - return application.ErrVersionConflict -} - -func seedAvailableStick(t *testing.T, store *sqlite.Store) { - createWebUIStick(t, store, "aa001", "prod") -} - -func seedHeldBy(subject string) func(*testing.T, *sqlite.Store) { - return func(t *testing.T, store *sqlite.Store) { - seedAvailableStick(t, store) - claimWebUIStick(t, store, "aa001", domain.Identity{Sub: subject}, "working") - } -} - -func newUIFormRequest(path string, form url.Values, identity domain.Identity) *http.Request { - request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode())) - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - request.SetPathValue("id", "aa001") - return request.WithContext(auth.WithIdentity(request.Context(), identity)) -} - -func cloneValues(values url.Values) url.Values { - clone := make(url.Values, len(values)) - for key, values := range values { - clone[key] = append([]string(nil), values...) - } - return clone -} diff --git a/test/integration/webui_test_helpers_test.go b/test/integration/webui_test_helpers_test.go deleted file mode 100644 index 11f266c..0000000 --- a/test/integration/webui_test_helpers_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package integration_test - -import ( - "context" - "strconv" - "testing" - "time" - - "stick/internal/adapters/persistence/sqlite" - "stick/internal/application" - domain "stick/internal/core" - "stick/internal/publicurl" - "stick/internal/web/content" - "stick/internal/web/render" - "stick/internal/web/sticks" - "stick/internal/web/views" -) - -func newSticksHandler(service *application.Service, loc *time.Location, publicURL publicurl.URL, notificationsEnabled bool) (*sticks.Handler, render.Renderer, error) { - renderer, err := newWebUIRenderer(loc, publicURL, notificationsEnabled) - if err != nil { - return nil, render.Renderer{}, err - } - detailTemplate, err := content.ParsePage(content.Detail) - if err != nil { - return nil, render.Renderer{}, err - } - newStickTemplate, err := content.ParsePage(content.NewStick) - if err != nil { - return nil, render.Renderer{}, err - } - return sticks.New(service, publicURL, renderer, detailTemplate, newStickTemplate, notificationsEnabled), renderer, nil -} - -func newWebUIRenderer(loc *time.Location, publicURL publicurl.URL, notificationsEnabled bool) (render.Renderer, error) { - errorTemplate, err := content.ParsePage(content.Error) - if err != nil { - return render.Renderer{}, err - } - renderer := render.New(views.NewMapper(publicURL, loc, notificationsEnabled), errorTemplate) - return renderer, nil -} - -func webuiPublicURL(t *testing.T, mountPath string) publicurl.URL { - t.Helper() - publicURL, err := publicurl.Parse("http://example.test" + mountPath) - if err != nil { - t.Fatal(err) - } - return publicURL -} - -func newWebUITestDB(t *testing.T) *sqlite.Store { - t.Helper() - store, err := sqlite.Open(":memory:") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = store.Close() }) - return store -} - -func createWebUIStick(t *testing.T, store *sqlite.Store, id, name string) { - t.Helper() - stick, err := domain.NewStick(id, name) - if err != nil { - t.Fatal(err) - } - if err := store.WithinTransaction(context.Background(), func(tx application.Transaction) error { - return tx.CreateStick(context.Background(), stick) - }); err != nil { - t.Fatal(err) - } -} - -func currentWebUIStick(t *testing.T, store *sqlite.Store, id string) domain.Stick { - t.Helper() - stick, err := store.GetStick(context.Background(), id) - if err != nil { - t.Fatal(err) - } - return stick -} - -func claimWebUIStick(t *testing.T, store *sqlite.Store, id string, identity domain.Identity, reason string) { - t.Helper() - stick := currentWebUIStick(t, store, id) - if _, err := application.NewService(store).ClaimStick(context.Background(), identity, id, reason, stick.Version); err != nil { - t.Fatal(err) - } -} - -func archiveWebUIStick(t *testing.T, store *sqlite.Store, id string) { - t.Helper() - stick := currentWebUIStick(t, store, id) - if _, err := application.NewService(store).ArchiveStick(context.Background(), domain.Identity{IsAdmin: true}, id, stick.Version); err != nil { - t.Fatal(err) - } -} - -func subscribeWebUIStick(t *testing.T, store *sqlite.Store, id, subject, name, email string) { - t.Helper() - stick := currentWebUIStick(t, store, id) - if err := application.NewService(store).Subscribe(context.Background(), domain.Identity{ - Sub: subject, - Name: name, - Email: email, - }, id, stick.Version); err != nil { - t.Fatal(err) - } -} - -func webUIStickVersion(t *testing.T, store *sqlite.Store, id string) string { - t.Helper() - return strconv.FormatInt(currentWebUIStick(t, store, id).Version, 10) -} From fdcc093d0ac72c2e169f23aa4b8c7b1c01b346c1 Mon Sep 17 00:00:00 2001 From: alxtr Date: Sun, 30 Aug 2026 18:37:39 +0000 Subject: [PATCH 02/14] Re-organize packages for api --- cmd/stickd/main.go | 17 +- cmd/stickd/main_test.go | 12 +- .../notification/smtp/injection_test.go | 2 +- internal/adapters/notification/smtp/smtp.go | 6 +- .../adapters/notification/smtp/smtp_test.go | 2 +- .../adapters/notification/smtp/wire_test.go | 2 +- .../notification/teams/request_error_test.go | 4 +- internal/adapters/notification/teams/teams.go | 6 +- .../adapters/notification/teams/teams_test.go | 2 +- .../webhook/request_error_test.go | 4 +- .../adapters/notification/webhook/webhook.go | 6 +- .../notification/webhook/webhook_test.go | 2 +- internal/api/conditions.go | 113 ++++ internal/api/handler.go | 524 +----------------- internal/api/handler_test.go | 3 +- .../{web/health/handler.go => api/health.go} | 19 +- .../health/routes.go => api/health_routes.go} | 8 +- internal/{web/health => api}/health_test.go | 7 +- internal/{web/httpx => api}/middleware.go | 4 +- .../{web/httpx => api}/middleware_test.go | 10 +- internal/{web/httpx => api}/request_log.go | 2 +- .../{web/httpx => api}/request_log_test.go | 18 +- internal/api/responses.go | 210 +++++++ internal/{web/httpx => api}/router.go | 2 +- internal/{web/httpx => api}/router_test.go | 14 +- internal/{web => api}/server.go | 26 +- internal/api/sticks.go | 186 +++++++ internal/api/subscriptions.go | 45 ++ internal/{web/httpx => api}/url.go | 2 +- internal/{web/httpx => api}/url_test.go | 10 +- internal/format/duration.go | 19 - .../notification.go | 3 +- .../notification_test.go | 20 +- internal/{format => outbox}/duration_test.go | 6 +- internal/outbox/worker.go | 24 +- test/integration/outbox_worker_test.go | 23 +- 36 files changed, 687 insertions(+), 676 deletions(-) create mode 100644 internal/api/conditions.go rename internal/{web/health/handler.go => api/health.go} (66%) rename internal/{web/health/routes.go => api/health_routes.go} (50%) rename internal/{web/health => api}/health_test.go (94%) rename internal/{web/httpx => api}/middleware.go (77%) rename internal/{web/httpx => api}/middleware_test.go (87%) rename internal/{web/httpx => api}/request_log.go (99%) rename internal/{web/httpx => api}/request_log_test.go (79%) create mode 100644 internal/api/responses.go rename internal/{web/httpx => api}/router.go (99%) rename internal/{web/httpx => api}/router_test.go (95%) rename internal/{web => api}/server.go (81%) create mode 100644 internal/api/sticks.go create mode 100644 internal/api/subscriptions.go rename internal/{web/httpx => api}/url.go (98%) rename internal/{web/httpx => api}/url_test.go (82%) delete mode 100644 internal/format/duration.go rename internal/{application => notification}/notification.go (96%) rename internal/{application => notification}/notification_test.go (59%) rename internal/{format => outbox}/duration_test.go (80%) diff --git a/cmd/stickd/main.go b/cmd/stickd/main.go index 8b4b0f1..47e4353 100644 --- a/cmd/stickd/main.go +++ b/cmd/stickd/main.go @@ -20,11 +20,12 @@ import ( "stick/internal/adapters/persistence/mongodb" "stick/internal/adapters/persistence/postgres" "stick/internal/adapters/persistence/sqlite" + "stick/internal/api" "stick/internal/application" "stick/internal/auth" "stick/internal/config" + "stick/internal/notification" "stick/internal/outbox" - "stick/internal/web" ) const version = "1.0.0" @@ -88,7 +89,7 @@ func mainContext(parent context.Context, args []string) (err error) { }() service := application.NewService(store) - serverRunner, err := web.NewRunner(service, store, web.Options{ + serverRunner, err := api.NewRunner(service, store, api.Options{ PublicURL: cfg.Server.PublicURL, ListenAddr: cfg.Server.ListenAddr, JWT: auth.JWTConfig{Endpoint: cfg.Auth.IDPEndpoint, Audience: cfg.Auth.Audience, Scope: cfg.Auth.Scope}, @@ -171,8 +172,8 @@ func openStore(ctx context.Context, cfg config.DatabaseConfig) (backend, error) } } -func buildNotifier(cfg config.NotificationsConfig) (application.Notifier, error) { - var notifiers []application.Notifier +func buildNotifier(cfg config.NotificationsConfig) (notification.Notifier, error) { + var notifiers []notification.Notifier for i, smtpConfig := range cfg.SMTP { notifier, err := smtp.New(smtp.Config{ Host: smtpConfig.Host, @@ -188,23 +189,23 @@ func buildNotifier(cfg config.NotificationsConfig) (application.Notifier, error) if err != nil { return nil, fmt.Errorf("%s notifier: %w", notificationBackendName("smtp", i), err) } - notifiers = append(notifiers, application.Named(notificationBackendName("smtp", i), notifier)) + notifiers = append(notifiers, notification.Named(notificationBackendName("smtp", i), notifier)) } for i, webhookConfig := range cfg.Webhook { notifier, err := webhook.New(webhook.Config{URL: webhookConfig.URL}) if err != nil { return nil, fmt.Errorf("%s notifier: %w", notificationBackendName("webhook", i), err) } - notifiers = append(notifiers, application.Named(notificationBackendName("webhook", i), notifier)) + notifiers = append(notifiers, notification.Named(notificationBackendName("webhook", i), notifier)) } for i, teamsConfig := range cfg.Teams { notifier, err := teams.New(teams.Config{URL: teamsConfig.URL}) if err != nil { return nil, fmt.Errorf("%s notifier: %w", notificationBackendName("teams", i), err) } - notifiers = append(notifiers, application.Named(notificationBackendName("teams", i), notifier)) + notifiers = append(notifiers, notification.Named(notificationBackendName("teams", i), notifier)) } - return application.Multi(notifiers...), nil + return notification.Multi(notifiers...), nil } func notificationBackendName(kind string, index int) string { diff --git a/cmd/stickd/main_test.go b/cmd/stickd/main_test.go index 7bd6e6d..100bfac 100644 --- a/cmd/stickd/main_test.go +++ b/cmd/stickd/main_test.go @@ -12,8 +12,8 @@ import ( "testing" "time" - "stick/internal/application" "stick/internal/config" + "stick/internal/notification" ) func TestMainContextStopsOnCanceledParent(t *testing.T) { @@ -167,7 +167,7 @@ func TestBuildNotifierComposesWebhook(t *testing.T) { if err != nil { t.Fatalf("buildNotifier: %v", err) } - if err := notifier.Notify(context.Background(), application.Notification{StickID: "aa001"}); err != nil { + if err := notifier.Notify(context.Background(), notification.Notification{StickID: "aa001"}); err != nil { t.Fatalf("Notify: %v", err) } if payload := <-received; !strings.Contains(payload, `"stick_id":"aa001"`) { @@ -193,7 +193,7 @@ func TestBuildNotifierComposesTeams(t *testing.T) { if err != nil { t.Fatalf("buildNotifier: %v", err) } - if err := notifier.Notify(context.Background(), application.Notification{StickName: "aa001"}); err != nil { + if err := notifier.Notify(context.Background(), notification.Notification{StickName: "aa001"}); err != nil { t.Fatalf("Notify: %v", err) } if payload := <-received; !strings.Contains(payload, `"@type":"MessageCard"`) || !strings.Contains(payload, `"title":"aa001 is available"`) { @@ -223,7 +223,7 @@ func TestBuildNotifierComposesMultipleBackends(t *testing.T) { if err != nil { t.Fatalf("buildNotifier: %v", err) } - if err := notifier.Notify(context.Background(), application.Notification{}); err != nil { + if err := notifier.Notify(context.Background(), notification.Notification{}); err != nil { t.Fatalf("Notify: %v", err) } select { @@ -257,7 +257,7 @@ func TestBuildNotifierComposesMultipleInstancesOfOneBackend(t *testing.T) { if err != nil { t.Fatalf("buildNotifier: %v", err) } - if err := notifier.Notify(context.Background(), application.Notification{}); err != nil { + if err := notifier.Notify(context.Background(), notification.Notification{}); err != nil { t.Fatalf("Notify: %v", err) } for i := 0; i < 2; i++ { @@ -305,7 +305,7 @@ func TestBuildNotifierAttributesRuntimeErrors(t *testing.T) { if err != nil { t.Fatalf("buildNotifier: %v", err) } - err = notifier.Notify(context.Background(), application.Notification{}) + err = notifier.Notify(context.Background(), notification.Notification{}) if err == nil || !strings.Contains(err.Error(), "webhook: webhook returned 502") { t.Fatalf("runtime error = %v", err) } diff --git a/internal/adapters/notification/smtp/injection_test.go b/internal/adapters/notification/smtp/injection_test.go index a1fab99..4ebd428 100644 --- a/internal/adapters/notification/smtp/injection_test.go +++ b/internal/adapters/notification/smtp/injection_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - notify "stick/internal/application" + notify "stick/internal/notification" ) func TestSMTPNotifierInjectedSenderRendersMessage(t *testing.T) { diff --git a/internal/adapters/notification/smtp/smtp.go b/internal/adapters/notification/smtp/smtp.go index 9ce3852..7c40c04 100644 --- a/internal/adapters/notification/smtp/smtp.go +++ b/internal/adapters/notification/smtp/smtp.go @@ -13,7 +13,7 @@ import ( "text/template" "time" - "stick/internal/application" + "stick/internal/notification" ) const defaultTimeout = 10 * time.Second @@ -63,7 +63,7 @@ type Notifier struct { send sendContextFunc } -var _ application.Notifier = (*Notifier)(nil) +var _ notification.Notifier = (*Notifier)(nil) // New creates an SMTP notifier, parsing the subject and body as Go text/templates. func New(cfg Config, templates Templates) (*Notifier, error) { @@ -101,7 +101,7 @@ func newNotifier(cfg Config, templates Templates, send sendContextFunc) (*Notifi } // Notify sends one notification through SMTP. -func (n *Notifier) Notify(ctx context.Context, notification application.Notification) error { +func (n *Notifier) Notify(ctx context.Context, notification notification.Notification) error { if err := ctx.Err(); err != nil { return err } diff --git a/internal/adapters/notification/smtp/smtp_test.go b/internal/adapters/notification/smtp/smtp_test.go index 2baef89..8123ca8 100644 --- a/internal/adapters/notification/smtp/smtp_test.go +++ b/internal/adapters/notification/smtp/smtp_test.go @@ -11,7 +11,7 @@ import ( "time" "stick/internal/adapters/notification/smtp" - notify "stick/internal/application" + notify "stick/internal/notification" ) func TestNewSMTPNotifier_ValidatesConfig(t *testing.T) { diff --git a/internal/adapters/notification/smtp/wire_test.go b/internal/adapters/notification/smtp/wire_test.go index a4678fd..f137e54 100644 --- a/internal/adapters/notification/smtp/wire_test.go +++ b/internal/adapters/notification/smtp/wire_test.go @@ -21,7 +21,7 @@ import ( "time" "stick/internal/adapters/notification/smtp" - notify "stick/internal/application" + notify "stick/internal/notification" ) func TestSMTPNotifierDeliversOverSTARTTLS(t *testing.T) { diff --git a/internal/adapters/notification/teams/request_error_test.go b/internal/adapters/notification/teams/request_error_test.go index f6d3552..29e873c 100644 --- a/internal/adapters/notification/teams/request_error_test.go +++ b/internal/adapters/notification/teams/request_error_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "stick/internal/application" + "stick/internal/notification" ) type roundTripperFunc func(*http.Request) (*http.Response, error) @@ -29,7 +29,7 @@ func TestRequestErrorRedactsWebhookURL(t *testing.T) { return nil, fmt.Errorf("transport failed for %s", request.URL.String()) })} - err = notifier.Notify(context.Background(), application.Notification{}) + err = notifier.Notify(context.Background(), notification.Notification{}) if err == nil { t.Fatal("expected request error") } diff --git a/internal/adapters/notification/teams/teams.go b/internal/adapters/notification/teams/teams.go index d1b0594..961c880 100644 --- a/internal/adapters/notification/teams/teams.go +++ b/internal/adapters/notification/teams/teams.go @@ -13,8 +13,8 @@ import ( "strings" "time" - "stick/internal/application" "stick/internal/netutil" + "stick/internal/notification" ) const defaultTimeout = 10 * time.Second @@ -67,7 +67,7 @@ type Notifier struct { client *http.Client } -var _ application.Notifier = (*Notifier)(nil) +var _ notification.Notifier = (*Notifier)(nil) // New creates a Microsoft Teams webhook notifier. func New(cfg Config) (*Notifier, error) { @@ -85,7 +85,7 @@ func New(cfg Config) (*Notifier, error) { } // Notify sends one release notification to Microsoft Teams. -func (n *Notifier) Notify(ctx context.Context, notification application.Notification) error { +func (n *Notifier) Notify(ctx context.Context, notification notification.Notification) error { card := Payload{ Type: "MessageCard", Context: "http://schema.org/extensions", diff --git a/internal/adapters/notification/teams/teams_test.go b/internal/adapters/notification/teams/teams_test.go index e0448c8..a7aed6e 100644 --- a/internal/adapters/notification/teams/teams_test.go +++ b/internal/adapters/notification/teams/teams_test.go @@ -12,7 +12,7 @@ import ( "time" "stick/internal/adapters/notification/teams" - notify "stick/internal/application" + notify "stick/internal/notification" ) func TestTeamsNotifierPostsMessageCard(t *testing.T) { diff --git a/internal/adapters/notification/webhook/request_error_test.go b/internal/adapters/notification/webhook/request_error_test.go index 81253a0..81d4217 100644 --- a/internal/adapters/notification/webhook/request_error_test.go +++ b/internal/adapters/notification/webhook/request_error_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "stick/internal/application" + "stick/internal/notification" ) type roundTripperFunc func(*http.Request) (*http.Response, error) @@ -29,7 +29,7 @@ func TestRequestErrorRedactsWebhookURL(t *testing.T) { return nil, fmt.Errorf("transport failed for %s", request.URL.String()) })} - err = notifier.Notify(context.Background(), application.Notification{}) + err = notifier.Notify(context.Background(), notification.Notification{}) if err == nil { t.Fatal("expected request error") } diff --git a/internal/adapters/notification/webhook/webhook.go b/internal/adapters/notification/webhook/webhook.go index 2063987..01459c2 100644 --- a/internal/adapters/notification/webhook/webhook.go +++ b/internal/adapters/notification/webhook/webhook.go @@ -12,8 +12,8 @@ import ( "strings" "time" - "stick/internal/application" "stick/internal/netutil" + "stick/internal/notification" ) const defaultTimeout = 10 * time.Second @@ -43,7 +43,7 @@ type Notifier struct { client *http.Client } -var _ application.Notifier = (*Notifier)(nil) +var _ notification.Notifier = (*Notifier)(nil) // New creates a webhook notifier. func New(cfg Config) (*Notifier, error) { @@ -61,7 +61,7 @@ func New(cfg Config) (*Notifier, error) { } // Notify sends one notification to the configured webhook. -func (w *Notifier) Notify(ctx context.Context, notification application.Notification) error { +func (w *Notifier) Notify(ctx context.Context, notification notification.Notification) error { payload := Payload{ StickID: notification.StickID, StickName: notification.StickName, diff --git a/internal/adapters/notification/webhook/webhook_test.go b/internal/adapters/notification/webhook/webhook_test.go index af9b35f..4e84f24 100644 --- a/internal/adapters/notification/webhook/webhook_test.go +++ b/internal/adapters/notification/webhook/webhook_test.go @@ -11,7 +11,7 @@ import ( "time" "stick/internal/adapters/notification/webhook" - notify "stick/internal/application" + notify "stick/internal/notification" ) func TestWebhookNotifier_PostsJSON(t *testing.T) { diff --git a/internal/api/conditions.go b/internal/api/conditions.go new file mode 100644 index 0000000..28db183 --- /dev/null +++ b/internal/api/conditions.go @@ -0,0 +1,113 @@ +package api + +import ( + "errors" + "net/http" + "strconv" + "strings" + + "stick/internal/auth" +) + +func (h *Handler) expectedVersion(w http.ResponseWriter, r *http.Request, id string) (int64, bool) { + header := headerValue(r, "If-Match") + if strings.TrimSpace(header) == "" { + writeError(w, http.StatusPreconditionRequired, "If-Match header is required") + return 0, false + } + tags, wildcard, err := parseIfMatch(header) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid If-Match header") + return 0, false + } + if len(tags) == 1 && !wildcard { + return tags[0], true + } + + // A wildcard or a list of tags must be compared to the current + // representation before choosing the version passed to the service. + stick, err := h.service.GetStick(r.Context(), auth.IdentityFromContext(r.Context()), id) + if err != nil { + handleError(w, r, "get stick", err) + return 0, false + } + if !wildcard { + matched := false + for _, tag := range tags { + if tag == stick.Version { + matched = true + break + } + } + if !matched { + writeError(w, http.StatusPreconditionFailed, "precondition failed") + return 0, false + } + } + return stick.Version, true +} + +func historyPagination(w http.ResponseWriter, r *http.Request) (int, int, bool) { + query := r.URL.Query() + limit := defaultHistoryLimit + offset := 0 + var err error + if raw := query.Get("limit"); raw != "" { + limit, err = strconv.Atoi(raw) + if err != nil || limit < 1 || limit > maxHistoryLimit { + writeError(w, http.StatusBadRequest, "invalid history limit") + return 0, 0, false + } + } + if raw := query.Get("offset"); raw != "" { + offset, err = strconv.Atoi(raw) + if err != nil || offset < 0 || offset > maxHistoryOffset { + writeError(w, http.StatusBadRequest, "invalid history offset") + return 0, 0, false + } + } + return limit, offset, true +} + +func parseIfMatch(value string) ([]int64, bool, error) { + value = strings.TrimSpace(value) + if value == "" { + return nil, false, errors.New("missing If-Match") + } + if value == "*" { + return nil, true, nil + } + parts := strings.Split(value, ",") + tags := make([]int64, 0, len(parts)) + for _, part := range parts { + part = strings.TrimSpace(part) + if len(part) < 3 || part[0] != '"' || part[len(part)-1] != '"' || strings.HasPrefix(part, "W/") { + return nil, false, errors.New("invalid entity tag") + } + version, err := strconv.ParseInt(part[1:len(part)-1], 10, 64) + if err != nil || version < 1 || etag(version) != part { + return nil, false, errors.New("invalid entity tag") + } + tags = append(tags, version) + } + if len(tags) == 0 { + return nil, false, errors.New("missing entity tag") + } + return tags, false, nil +} + +func ifNoneMatch(header, current string) bool { + for _, part := range strings.Split(header, ",") { + part = strings.TrimSpace(part) + if part == "*" { + return true + } + if strings.HasPrefix(part, "W/") { + part = strings.TrimSpace(strings.TrimPrefix(part, "W/")) + } + if part == current { + return true + } + } + return false +} diff --git a/internal/api/handler.go b/internal/api/handler.go index 585da5c..ba1bf08 100644 --- a/internal/api/handler.go +++ b/internal/api/handler.go @@ -3,21 +3,13 @@ package api import ( "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "io" "net/http" - "strconv" "strings" - "time" "stick/internal/application" "stick/internal/auth" domain "stick/internal/core" "stick/internal/publicurl" - "stick/internal/web/httpx" ) const ( @@ -61,7 +53,7 @@ func New( // Register adds all API routes to router. Authentication is applied to the // complete API route family; health probes remain unauthenticated. -func Register(router *httpx.Router, handler *Handler) { +func Register(router *Router, handler *Handler) { protected := router.With(handler.authenticate) protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks", handler.listSticks) protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks", handler.createStick) @@ -105,517 +97,3 @@ func (h *Handler) authenticate(next http.Handler) http.Handler { next.ServeHTTP(w, r.WithContext(auth.WithIdentity(r.Context(), identity))) }) } - -func (h *Handler) listSticks(w http.ResponseWriter, r *http.Request) { - sticks, err := h.service.ListSticks(r.Context()) - if err != nil { - internalError(w, r, "list sticks", err) - return - } - writeCollection(w, r, sticksToJSON(sticks)) -} - -func (h *Handler) listArchivedSticks(w http.ResponseWriter, r *http.Request) { - identity := auth.IdentityFromContext(r.Context()) - if !identity.IsAdmin { - writeError(w, http.StatusForbidden, "forbidden") - return - } - sticks, err := h.service.ListArchivedSticks(r.Context(), identity) - if err != nil { - handleError(w, r, "list archived sticks", err) - return - } - writeCollection(w, r, sticksToJSON(sticks)) -} - -func (h *Handler) getStick(w http.ResponseWriter, r *http.Request) { - stick, err := h.service.GetStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id")) - if err != nil { - handleError(w, r, "get stick", err) - return - } - setETag(w, stick.Version) - if ifNoneMatch(headerValue(r, "If-None-Match"), etag(stick.Version)) { - notModified(w) - return - } - writeJSON(w, http.StatusOK, stickToJSON(stick)) -} - -func (h *Handler) createStick(w http.ResponseWriter, r *http.Request) { - if !auth.IdentityFromContext(r.Context()).IsAdmin { - writeError(w, http.StatusForbidden, "forbidden") - return - } - var request struct { - Name string `json:"name"` - } - if !decodeJSON(w, r, &request) { - return - } - stick, err := h.service.CreateStick(r.Context(), auth.IdentityFromContext(r.Context()), request.Name) - if err != nil { - handleError(w, r, "create stick", err) - return - } - setETag(w, stick.Version) - w.Header().Set("Location", httpx.Absolute(h.publicURL, apiPrefix+"/sticks/"+stick.ID)) - writeJSON(w, http.StatusCreated, stickToJSON(stick)) -} - -func (h *Handler) renameStick(w http.ResponseWriter, r *http.Request) { - if !auth.IdentityFromContext(r.Context()).IsAdmin { - writeError(w, http.StatusForbidden, "forbidden") - return - } - var request struct { - Name string `json:"name"` - } - if !decodeJSON(w, r, &request) { - return - } - version, ok := h.expectedVersion(w, r, r.PathValue("id")) - if !ok { - return - } - stick, err := h.service.RenameStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), request.Name, version) - if err != nil { - handleError(w, r, "rename stick", err) - return - } - writeStick(w, stick) -} - -func (h *Handler) archiveStick(w http.ResponseWriter, r *http.Request) { - if !auth.IdentityFromContext(r.Context()).IsAdmin { - writeError(w, http.StatusForbidden, "forbidden") - return - } - version, ok := h.expectedVersion(w, r, r.PathValue("id")) - if !ok { - return - } - stick, err := h.service.ArchiveStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version) - if err != nil { - handleError(w, r, "archive stick", err) - return - } - writeStick(w, stick) -} - -func (h *Handler) unarchiveStick(w http.ResponseWriter, r *http.Request) { - if !auth.IdentityFromContext(r.Context()).IsAdmin { - writeError(w, http.StatusForbidden, "forbidden") - return - } - version, ok := h.expectedVersion(w, r, r.PathValue("id")) - if !ok { - return - } - stick, err := h.service.UnarchiveStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version) - if err != nil { - handleError(w, r, "unarchive stick", err) - return - } - writeStick(w, stick) -} - -func (h *Handler) claimStick(w http.ResponseWriter, r *http.Request) { - var request struct { - Reason string `json:"reason"` - } - if !decodeJSON(w, r, &request) { - return - } - version, ok := h.expectedVersion(w, r, r.PathValue("id")) - if !ok { - return - } - stick, err := h.service.ClaimStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), request.Reason, version) - if err != nil { - handleError(w, r, "claim stick", err) - return - } - writeStick(w, stick) -} - -func (h *Handler) releaseStick(w http.ResponseWriter, r *http.Request) { - version, ok := h.expectedVersion(w, r, r.PathValue("id")) - if !ok { - return - } - stick, err := h.service.ReleaseStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version) - if err != nil { - handleError(w, r, "release stick", err) - return - } - writeStick(w, stick) -} - -func (h *Handler) history(w http.ResponseWriter, r *http.Request) { - identity := auth.IdentityFromContext(r.Context()) - id := r.PathValue("id") - stick, err := h.service.GetStick(r.Context(), identity, id) - if err != nil { - handleError(w, r, "get stick history", err) - return - } - setETag(w, stick.Version) - limit, offset, ok := historyPagination(w, r) - if !ok { - return - } - sessions, total, err := h.service.GetHistory(r.Context(), identity, id, limit, offset) - if err != nil { - handleError(w, r, "get stick history", err) - return - } - response := struct { - Sessions []sessionJSON `json:"sessions"` - Total int `json:"total"` - Limit int `json:"limit"` - Offset int `json:"offset"` - }{ - Sessions: sessionsToJSON(sessions), - Total: total, - Limit: limit, - Offset: offset, - } - writeConditionalJSON(w, r, response) -} - -func (h *Handler) subscribe(w http.ResponseWriter, r *http.Request) { - version, ok := h.expectedVersion(w, r, r.PathValue("id")) - if !ok { - return - } - if err := h.service.Subscribe(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version); err != nil { - handleError(w, r, "subscribe to stick", err) - return - } - setETag(w, version) - w.WriteHeader(http.StatusNoContent) -} - -func (h *Handler) unsubscribe(w http.ResponseWriter, r *http.Request) { - version, ok := h.expectedVersion(w, r, r.PathValue("id")) - if !ok { - return - } - if err := h.service.Unsubscribe(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version); err != nil { - handleError(w, r, "unsubscribe from stick", err) - return - } - setETag(w, version) - w.WriteHeader(http.StatusNoContent) -} - -func (h *Handler) subscriptions(w http.ResponseWriter, r *http.Request) { - ids, err := h.service.SubscribedStickIDs(r.Context(), auth.IdentityFromContext(r.Context())) - if err != nil { - internalError(w, r, "list subscriptions", err) - return - } - if ids == nil { - ids = []string{} - } - writeCollection(w, r, ids) -} - -func (h *Handler) expectedVersion(w http.ResponseWriter, r *http.Request, id string) (int64, bool) { - header := headerValue(r, "If-Match") - if strings.TrimSpace(header) == "" { - writeError(w, http.StatusPreconditionRequired, "If-Match header is required") - return 0, false - } - tags, wildcard, err := parseIfMatch(header) - if err != nil { - writeError(w, http.StatusBadRequest, "invalid If-Match header") - return 0, false - } - if len(tags) == 1 && !wildcard { - return tags[0], true - } - - // A wildcard or a list of tags must be compared to the current - // representation before choosing the version passed to the service. - stick, err := h.service.GetStick(r.Context(), auth.IdentityFromContext(r.Context()), id) - if err != nil { - handleError(w, r, "get stick", err) - return 0, false - } - if !wildcard { - matched := false - for _, tag := range tags { - if tag == stick.Version { - matched = true - break - } - } - if !matched { - writeError(w, http.StatusPreconditionFailed, "precondition failed") - return 0, false - } - } - return stick.Version, true -} - -func historyPagination(w http.ResponseWriter, r *http.Request) (int, int, bool) { - query := r.URL.Query() - limit := defaultHistoryLimit - offset := 0 - var err error - if raw := query.Get("limit"); raw != "" { - limit, err = strconv.Atoi(raw) - if err != nil || limit < 1 || limit > maxHistoryLimit { - writeError(w, http.StatusBadRequest, "invalid history limit") - return 0, 0, false - } - } - if raw := query.Get("offset"); raw != "" { - offset, err = strconv.Atoi(raw) - if err != nil || offset < 0 || offset > maxHistoryOffset { - writeError(w, http.StatusBadRequest, "invalid history offset") - return 0, 0, false - } - } - return limit, offset, true -} - -func parseIfMatch(value string) ([]int64, bool, error) { - value = strings.TrimSpace(value) - if value == "" { - return nil, false, errors.New("missing If-Match") - } - if value == "*" { - return nil, true, nil - } - parts := strings.Split(value, ",") - tags := make([]int64, 0, len(parts)) - for _, part := range parts { - part = strings.TrimSpace(part) - if len(part) < 3 || part[0] != '"' || part[len(part)-1] != '"' || strings.HasPrefix(part, "W/") { - return nil, false, errors.New("invalid entity tag") - } - version, err := strconv.ParseInt(part[1:len(part)-1], 10, 64) - if err != nil || version < 1 || etag(version) != part { - return nil, false, errors.New("invalid entity tag") - } - tags = append(tags, version) - } - if len(tags) == 0 { - return nil, false, errors.New("missing entity tag") - } - return tags, false, nil -} - -func ifNoneMatch(header, current string) bool { - for _, part := range strings.Split(header, ",") { - part = strings.TrimSpace(part) - if part == "*" { - return true - } - if strings.HasPrefix(part, "W/") { - part = strings.TrimSpace(strings.TrimPrefix(part, "W/")) - } - if part == current { - return true - } - } - return false -} - -func writeStick(w http.ResponseWriter, stick domain.Stick) { - setETag(w, stick.Version) - writeJSON(w, http.StatusOK, stickToJSON(stick)) -} - -func writeCollection(w http.ResponseWriter, r *http.Request, value any) { - data, err := json.Marshal(value) - if err != nil { - writeError(w, http.StatusInternalServerError, "internal server error") - return - } - sum := sha256.Sum256(data) - collectionETag := `"` + hex.EncodeToString(sum[:]) + `"` - w.Header().Set("ETag", collectionETag) - if ifNoneMatch(headerValue(r, "If-None-Match"), collectionETag) { - notModified(w) - return - } - writeData(w, http.StatusOK, data) -} - -func writeConditionalJSON(w http.ResponseWriter, r *http.Request, value any) { - data, err := json.Marshal(value) - if err != nil { - writeError(w, http.StatusInternalServerError, "internal server error") - return - } - sum := sha256.Sum256(data) - representationETag := `"` + hex.EncodeToString(sum[:]) + `"` - w.Header().Set("ETag", representationETag) - if ifNoneMatch(headerValue(r, "If-None-Match"), representationETag) { - notModified(w) - return - } - writeData(w, http.StatusOK, data) -} - -func headerValue(r *http.Request, name string) string { - return strings.Join(r.Header.Values(name), ",") -} - -func writeJSON(w http.ResponseWriter, status int, value any) { - data, err := json.Marshal(value) - if err != nil { - writeError(w, http.StatusInternalServerError, "internal server error") - return - } - writeData(w, status, data) -} - -func writeData(w http.ResponseWriter, status int, data []byte) { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(status) - _, _ = w.Write(data) -} - -func notModified(w http.ResponseWriter) { - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(http.StatusNotModified) -} - -func writeError(w http.ResponseWriter, status int, message string) { - writeJSON(w, status, struct { - Error string `json:"error"` - }{Error: message}) -} - -func setETag(w http.ResponseWriter, version int64) { w.Header().Set("ETag", etag(version)) } - -func etag(version int64) string { return `"` + strconv.FormatInt(version, 10) + `"` } - -func decodeJSON(w http.ResponseWriter, r *http.Request, destination any) bool { - r.Body = http.MaxBytesReader(w, r.Body, maxJSONBodyBytes) - decoder := json.NewDecoder(r.Body) - decoder.DisallowUnknownFields() - if err := decoder.Decode(destination); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return false - } - var extra any - if err := decoder.Decode(&extra); err != io.EOF { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return false - } - return true -} - -func unauthorized(w http.ResponseWriter) { - w.Header().Set("WWW-Authenticate", `Bearer`) - writeError(w, http.StatusUnauthorized, "unauthorized") -} - -func internalError(w http.ResponseWriter, r *http.Request, operation string, err error) { - httpx.LogError(r.Context(), "request failed", operation, err) - writeError(w, http.StatusInternalServerError, "internal server error") -} - -func handleError(w http.ResponseWriter, r *http.Request, operation string, err error) { - switch { - case errors.Is(err, application.ErrNotFound): - writeError(w, http.StatusNotFound, "not found") - case errors.Is(err, application.ErrForbidden), errors.Is(err, domain.ErrNotHolder): - writeError(w, http.StatusForbidden, "forbidden") - case errors.Is(err, application.ErrVersionConflict): - writeError(w, http.StatusPreconditionFailed, "precondition failed") - case errors.Is(err, application.ErrAlreadyExists): - writeError(w, http.StatusConflict, "conflict") - case errors.Is(err, domain.ErrInvalidStickName), errors.Is(err, domain.ErrInvalidClaimReason): - writeError(w, http.StatusUnprocessableEntity, "invalid request") - case errors.Is(err, domain.ErrAlreadyHeld), errors.Is(err, domain.ErrAlreadyArchived), - errors.Is(err, domain.ErrNotArchived), errors.Is(err, domain.ErrHeld), - errors.Is(err, domain.ErrVersionExhausted): - writeError(w, http.StatusConflict, "conflict") - default: - internalError(w, r, operation, err) - } -} - -type stickJSON struct { - ID string `json:"id"` - Name string `json:"name"` - Version int64 `json:"version"` - Archived bool `json:"archived"` - Available bool `json:"available"` - ArchivedAt *time.Time `json:"archived_at"` - Holder *holderJSON `json:"holder"` -} - -type holderJSON struct { - Name string `json:"name"` - Email string `json:"email"` - ClaimedAt string `json:"claimed_at"` - Reason string `json:"reason"` -} - -type sessionJSON struct { - ID int64 `json:"id"` - StickID string `json:"stick_id"` - HolderName string `json:"holder_name"` - HolderEmail string `json:"holder_email"` - Reason string `json:"reason"` - ClaimedAt string `json:"claimed_at"` - ReleasedAt *string `json:"released_at"` -} - -func stickToJSON(stick domain.Stick) stickJSON { - response := stickJSON{ - ID: stick.ID, - Name: stick.Name, - Version: stick.Version, - Archived: stick.Archived(), - Available: stick.Available(), - ArchivedAt: stick.ArchivedAt, - } - if stick.Holder != nil { - response.Holder = &holderJSON{ - Name: stick.Holder.Name, - Email: stick.Holder.Email, - ClaimedAt: stick.Holder.ClaimedAt.UTC().Format("2006-01-02T15:04:05.999999999Z07:00"), - Reason: stick.Holder.Reason, - } - } - return response -} - -func sticksToJSON(sticks []domain.Stick) []stickJSON { - result := make([]stickJSON, 0, len(sticks)) - for _, stick := range sticks { - result = append(result, stickToJSON(stick)) - } - return result -} - -func sessionsToJSON(sessions []domain.Session) []sessionJSON { - result := make([]sessionJSON, 0, len(sessions)) - for _, session := range sessions { - item := sessionJSON{ - ID: session.ID, - StickID: session.StickID, - HolderName: session.HolderName, - HolderEmail: session.HolderEmail, - Reason: session.Reason, - ClaimedAt: session.ClaimedAt.UTC().Format("2006-01-02T15:04:05.999999999Z07:00"), - } - if session.ReleasedAt != nil { - releasedAt := session.ReleasedAt.UTC().Format("2006-01-02T15:04:05.999999999Z07:00") - item.ReleasedAt = &releasedAt - } - result = append(result, item) - } - return result -} diff --git a/internal/api/handler_test.go b/internal/api/handler_test.go index 56ca0c3..4de158a 100644 --- a/internal/api/handler_test.go +++ b/internal/api/handler_test.go @@ -15,7 +15,6 @@ import ( "stick/internal/application" domain "stick/internal/core" "stick/internal/publicurl" - "stick/internal/web/httpx" ) type tokenValidator map[string]domain.Identity @@ -44,7 +43,7 @@ func newTestHandler(t *testing.T) http.Handler { "admin-token": admin, "user-token": {Sub: "user", Name: "User", Email: "user@example.com", EmailVerified: true}, }, []string{"admin@example.com"}, publicURL, true) - router := httpx.NewRouter(publicURL) + router := api.NewRouter(publicURL) api.Register(router, handler) router.SetNotFound(http.HandlerFunc(api.NotFound)) return router diff --git a/internal/web/health/handler.go b/internal/api/health.go similarity index 66% rename from internal/web/health/handler.go rename to internal/api/health.go index 7e404ac..2d79f4c 100644 --- a/internal/web/health/handler.go +++ b/internal/api/health.go @@ -1,5 +1,4 @@ -// Package health provides unauthenticated operational HTTP probes. -package health +package api import ( "context" @@ -14,24 +13,24 @@ type ReadinessChecker interface { PingContext(context.Context) error } -// Handler provides unauthenticated process and dependency probes. Responses +// healthHandler provides unauthenticated process and dependency probes. Responses // contain no configuration or database details. -type Handler struct { +type healthHandler struct { readiness ReadinessChecker } -// New returns a health handler backed by readiness. -func New(readiness ReadinessChecker) *Handler { - return &Handler{readiness: readiness} +// NewHealth returns a health handler backed by readiness. +func NewHealth(readiness ReadinessChecker) *healthHandler { + return &healthHandler{readiness: readiness} } // Liveness serves the process liveness probe. -func (h *Handler) Liveness(w http.ResponseWriter, _ *http.Request) { +func (h *healthHandler) Liveness(w http.ResponseWriter, _ *http.Request) { h.writeStatus(w, http.StatusOK, "ok\n") } // Readiness serves the database readiness probe. -func (h *Handler) Readiness(w http.ResponseWriter, r *http.Request) { +func (h *healthHandler) Readiness(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), readinessTimeout) defer cancel() // Readiness deliberately reflects only the required database dependency. @@ -44,7 +43,7 @@ func (h *Handler) Readiness(w http.ResponseWriter, r *http.Request) { h.writeStatus(w, http.StatusOK, "ready\n") } -func (h *Handler) writeStatus(w http.ResponseWriter, status int, body string) { +func (h *healthHandler) writeStatus(w http.ResponseWriter, status int, body string) { w.Header().Set("Cache-Control", "no-store") w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(status) diff --git a/internal/web/health/routes.go b/internal/api/health_routes.go similarity index 50% rename from internal/web/health/routes.go rename to internal/api/health_routes.go index 9c4af28..8797213 100644 --- a/internal/web/health/routes.go +++ b/internal/api/health_routes.go @@ -1,13 +1,11 @@ -package health +package api import ( "net/http" - - "stick/internal/web/httpx" ) -// Register registers the liveness and readiness routes. -func Register(router *httpx.Router, handler *Handler) { +// RegisterHealth registers the liveness and readiness routes. +func RegisterHealth(router *Router, handler *healthHandler) { router.HandleFunc(http.MethodGet, "/healthz", handler.Liveness) router.HandleFunc(http.MethodGet, "/readyz", handler.Readiness) } diff --git a/internal/web/health/health_test.go b/internal/api/health_test.go similarity index 94% rename from internal/web/health/health_test.go rename to internal/api/health_test.go index acbe155..7d64cd1 100644 --- a/internal/web/health/health_test.go +++ b/internal/api/health_test.go @@ -1,4 +1,4 @@ -package health +package api import ( "context" @@ -9,7 +9,6 @@ import ( "time" "stick/internal/publicurl" - "stick/internal/web/httpx" ) type healthDB struct { @@ -40,12 +39,12 @@ func TestHealthRoutes(t *testing.T) { if err != nil { t.Fatal(err) } - router := httpx.NewRouter(publicURL) + router := NewRouter(publicURL) var readiness ReadinessChecker if test.readiness != nil { readiness = test.readiness } - Register(router, New(readiness)) + RegisterHealth(router, NewHealth(readiness)) recorder := httptest.NewRecorder() router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/stick"+test.path, nil)) diff --git a/internal/web/httpx/middleware.go b/internal/api/middleware.go similarity index 77% rename from internal/web/httpx/middleware.go rename to internal/api/middleware.go index d7fa938..e84b038 100644 --- a/internal/web/httpx/middleware.go +++ b/internal/api/middleware.go @@ -1,6 +1,4 @@ -// Package httpx provides the small net/http toolkit shared by the service's -// endpoints and middleware. -package httpx +package api import "net/http" diff --git a/internal/web/httpx/middleware_test.go b/internal/api/middleware_test.go similarity index 87% rename from internal/web/httpx/middleware_test.go rename to internal/api/middleware_test.go index 18f4344..2170982 100644 --- a/internal/web/httpx/middleware_test.go +++ b/internal/api/middleware_test.go @@ -1,4 +1,4 @@ -package httpx_test +package api_test import ( "log/slog" @@ -7,12 +7,12 @@ import ( "strings" "testing" - "stick/internal/web/httpx" + "stick/internal/api" ) func TestChainAppliesMiddlewareInOrder(t *testing.T) { var calls []string - record := func(name string) httpx.Middleware { + record := func(name string) api.Middleware { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { calls = append(calls, name+" before") @@ -25,7 +25,7 @@ func TestChainAppliesMiddlewareInOrder(t *testing.T) { calls = append(calls, "handler") }) - stack := httpx.Chain(record("first"), record("second")) + stack := api.Chain(record("first"), record("second")) stack(final).ServeHTTP( httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil), @@ -42,7 +42,7 @@ func TestRequestLoggerAddsRequestIDAndLogs(t *testing.T) { previous := slog.Default() slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) t.Cleanup(func() { slog.SetDefault(previous) }) - root := httpx.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + root := api.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })) recorder := httptest.NewRecorder() diff --git a/internal/web/httpx/request_log.go b/internal/api/request_log.go similarity index 99% rename from internal/web/httpx/request_log.go rename to internal/api/request_log.go index 1191189..a483e23 100644 --- a/internal/web/httpx/request_log.go +++ b/internal/api/request_log.go @@ -1,4 +1,4 @@ -package httpx +package api import ( "context" diff --git a/internal/web/httpx/request_log_test.go b/internal/api/request_log_test.go similarity index 79% rename from internal/web/httpx/request_log_test.go rename to internal/api/request_log_test.go index 74e7e8a..a9d060c 100644 --- a/internal/web/httpx/request_log_test.go +++ b/internal/api/request_log_test.go @@ -1,4 +1,4 @@ -package httpx_test +package api_test import ( "bytes" @@ -11,12 +11,12 @@ import ( "strings" "testing" - "stick/internal/web/httpx" + "stick/internal/api" ) func TestRequestIDContext(t *testing.T) { - ctx := httpx.WithRequestID(context.Background(), "request-42") - if got := httpx.RequestID(ctx); got != "request-42" { + ctx := api.WithRequestID(context.Background(), "request-42") + if got := api.RequestID(ctx); got != "request-42" { t.Errorf("request ID = %q, want request-42", got) } } @@ -26,8 +26,8 @@ func TestRequestLoggerAssignsAndPropagatesID(t *testing.T) { previous := slog.Default() slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) t.Cleanup(func() { slog.SetDefault(previous) }) - wrapped := httpx.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if httpx.RequestID(r.Context()) == "" { + wrapped := api.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if api.RequestID(r.Context()) == "" { t.Error("request ID missing from context") } w.WriteHeader(http.StatusTeapot) @@ -52,7 +52,7 @@ func TestRequestLoggerAssignsAndPropagatesID(t *testing.T) { } func TestRequestLoggerPropagatesValidIncomingID(t *testing.T) { - wrapped := httpx.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + wrapped := api.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })) request := httptest.NewRequest(http.MethodGet, "/", nil) @@ -69,9 +69,9 @@ func TestLogErrorLogsCorrelatedFailure(t *testing.T) { previous := slog.Default() slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) t.Cleanup(func() { slog.SetDefault(previous) }) - ctx := httpx.WithRequestID(t.Context(), "request-42") + ctx := api.WithRequestID(t.Context(), "request-42") - httpx.LogError(ctx, "request failed", "perform operation", errors.New("failed")) + api.LogError(ctx, "request failed", "perform operation", errors.New("failed")) for _, want := range []string{`"msg":"request failed"`, `"request_id":"request-42"`, `"operation":"perform operation"`, `"error":"failed"`} { if !strings.Contains(logs.String(), want) { diff --git a/internal/api/responses.go b/internal/api/responses.go new file mode 100644 index 0000000..2b912b5 --- /dev/null +++ b/internal/api/responses.go @@ -0,0 +1,210 @@ +package api + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net/http" + "strconv" + "strings" + "time" + + "stick/internal/application" + domain "stick/internal/core" +) + +func writeStick(w http.ResponseWriter, stick domain.Stick) { + setETag(w, stick.Version) + writeJSON(w, http.StatusOK, stickToJSON(stick)) +} + +func writeCollection(w http.ResponseWriter, r *http.Request, value any) { + data, err := json.Marshal(value) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal server error") + return + } + sum := sha256.Sum256(data) + collectionETag := `"` + hex.EncodeToString(sum[:]) + `"` + w.Header().Set("ETag", collectionETag) + if ifNoneMatch(headerValue(r, "If-None-Match"), collectionETag) { + notModified(w) + return + } + writeData(w, http.StatusOK, data) +} + +func writeConditionalJSON(w http.ResponseWriter, r *http.Request, value any) { + data, err := json.Marshal(value) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal server error") + return + } + sum := sha256.Sum256(data) + representationETag := `"` + hex.EncodeToString(sum[:]) + `"` + w.Header().Set("ETag", representationETag) + if ifNoneMatch(headerValue(r, "If-None-Match"), representationETag) { + notModified(w) + return + } + writeData(w, http.StatusOK, data) +} + +func headerValue(r *http.Request, name string) string { + return strings.Join(r.Header.Values(name), ",") +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + data, err := json.Marshal(value) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal server error") + return + } + writeData(w, status, data) +} + +func writeData(w http.ResponseWriter, status int, data []byte) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(status) + _, _ = w.Write(data) +} + +func notModified(w http.ResponseWriter) { + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusNotModified) +} + +func writeError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, struct { + Error string `json:"error"` + }{Error: message}) +} + +func setETag(w http.ResponseWriter, version int64) { w.Header().Set("ETag", etag(version)) } + +func etag(version int64) string { return `"` + strconv.FormatInt(version, 10) + `"` } + +func decodeJSON(w http.ResponseWriter, r *http.Request, destination any) bool { + r.Body = http.MaxBytesReader(w, r.Body, maxJSONBodyBytes) + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(destination); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return false + } + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return false + } + return true +} + +func unauthorized(w http.ResponseWriter) { + w.Header().Set("WWW-Authenticate", `Bearer`) + writeError(w, http.StatusUnauthorized, "unauthorized") +} + +func internalError(w http.ResponseWriter, r *http.Request, operation string, err error) { + LogError(r.Context(), "request failed", operation, err) + writeError(w, http.StatusInternalServerError, "internal server error") +} + +func handleError(w http.ResponseWriter, r *http.Request, operation string, err error) { + switch { + case errors.Is(err, application.ErrNotFound): + writeError(w, http.StatusNotFound, "not found") + case errors.Is(err, application.ErrForbidden), errors.Is(err, domain.ErrNotHolder): + writeError(w, http.StatusForbidden, "forbidden") + case errors.Is(err, application.ErrVersionConflict): + writeError(w, http.StatusPreconditionFailed, "precondition failed") + case errors.Is(err, application.ErrAlreadyExists): + writeError(w, http.StatusConflict, "conflict") + case errors.Is(err, domain.ErrInvalidStickName), errors.Is(err, domain.ErrInvalidClaimReason): + writeError(w, http.StatusUnprocessableEntity, "invalid request") + case errors.Is(err, domain.ErrAlreadyHeld), errors.Is(err, domain.ErrAlreadyArchived), + errors.Is(err, domain.ErrNotArchived), errors.Is(err, domain.ErrHeld), + errors.Is(err, domain.ErrVersionExhausted): + writeError(w, http.StatusConflict, "conflict") + default: + internalError(w, r, operation, err) + } +} + +type stickJSON struct { + ID string `json:"id"` + Name string `json:"name"` + Version int64 `json:"version"` + Archived bool `json:"archived"` + Available bool `json:"available"` + ArchivedAt *time.Time `json:"archived_at"` + Holder *holderJSON `json:"holder"` +} + +type holderJSON struct { + Name string `json:"name"` + Email string `json:"email"` + ClaimedAt string `json:"claimed_at"` + Reason string `json:"reason"` +} + +type sessionJSON struct { + ID int64 `json:"id"` + StickID string `json:"stick_id"` + HolderName string `json:"holder_name"` + HolderEmail string `json:"holder_email"` + Reason string `json:"reason"` + ClaimedAt string `json:"claimed_at"` + ReleasedAt *string `json:"released_at"` +} + +func stickToJSON(stick domain.Stick) stickJSON { + response := stickJSON{ + ID: stick.ID, + Name: stick.Name, + Version: stick.Version, + Archived: stick.Archived(), + Available: stick.Available(), + ArchivedAt: stick.ArchivedAt, + } + if stick.Holder != nil { + response.Holder = &holderJSON{ + Name: stick.Holder.Name, + Email: stick.Holder.Email, + ClaimedAt: stick.Holder.ClaimedAt.UTC().Format("2006-01-02T15:04:05.999999999Z07:00"), + Reason: stick.Holder.Reason, + } + } + return response +} + +func sticksToJSON(sticks []domain.Stick) []stickJSON { + result := make([]stickJSON, 0, len(sticks)) + for _, stick := range sticks { + result = append(result, stickToJSON(stick)) + } + return result +} + +func sessionsToJSON(sessions []domain.Session) []sessionJSON { + result := make([]sessionJSON, 0, len(sessions)) + for _, session := range sessions { + item := sessionJSON{ + ID: session.ID, + StickID: session.StickID, + HolderName: session.HolderName, + HolderEmail: session.HolderEmail, + Reason: session.Reason, + ClaimedAt: session.ClaimedAt.UTC().Format("2006-01-02T15:04:05.999999999Z07:00"), + } + if session.ReleasedAt != nil { + releasedAt := session.ReleasedAt.UTC().Format("2006-01-02T15:04:05.999999999Z07:00") + item.ReleasedAt = &releasedAt + } + result = append(result, item) + } + return result +} diff --git a/internal/web/httpx/router.go b/internal/api/router.go similarity index 99% rename from internal/web/httpx/router.go rename to internal/api/router.go index e05f5e9..0200b2a 100644 --- a/internal/web/httpx/router.go +++ b/internal/api/router.go @@ -1,4 +1,4 @@ -package httpx +package api import ( "net/http" diff --git a/internal/web/httpx/router_test.go b/internal/api/router_test.go similarity index 95% rename from internal/web/httpx/router_test.go rename to internal/api/router_test.go index 1498b24..c11f2da 100644 --- a/internal/web/httpx/router_test.go +++ b/internal/api/router_test.go @@ -1,12 +1,12 @@ -package httpx_test +package api_test import ( "net/http" "net/http/httptest" "testing" + "stick/internal/api" "stick/internal/publicurl" - "stick/internal/web/httpx" ) func testPublicURL(t *testing.T, mountPath string) publicurl.URL { @@ -20,13 +20,13 @@ func testPublicURL(t *testing.T, mountPath string) publicurl.URL { func TestRouterWithScopesMiddleware(t *testing.T) { publicURL := testPublicURL(t, "") - routes := httpx.NewRouter(publicURL) + routes := api.NewRouter(publicURL) reject := func(http.Handler) http.Handler { return http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) { response.WriteHeader(http.StatusUnauthorized) }) } - protected := routes.With(httpx.Chain(reject)) + protected := routes.With(api.Chain(reject)) routes.Handle(http.MethodGet, "/public", http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) { response.WriteHeader(http.StatusNoContent) })) @@ -49,7 +49,7 @@ func TestRouterWithScopesMiddleware(t *testing.T) { func TestRouterPreservesNestedMountAndPathValues(t *testing.T) { publicURL := testPublicURL(t, "/ops/stick") - routes := httpx.NewRouter(publicURL) + routes := api.NewRouter(publicURL) routes.HandleFunc(http.MethodGet, "/sticks/{id}", func(w http.ResponseWriter, r *http.Request) { if got := r.URL.Path; got != "/ops/stick/sticks/aa001" { t.Errorf("handler path = %q", got) @@ -72,7 +72,7 @@ func TestRouterPreservesNestedMountAndPathValues(t *testing.T) { } func TestRouterUsesCustomNotFoundOnlyInsideMount(t *testing.T) { - routes := httpx.NewRouter(testPublicURL(t, "/stick")) + routes := api.NewRouter(testPublicURL(t, "/stick")) routes.SetNotFound(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/html") w.WriteHeader(http.StatusNotFound) @@ -93,7 +93,7 @@ func TestRouterUsesCustomNotFoundOnlyInsideMount(t *testing.T) { } func TestRouterCustomNotFoundAndRedirectSemantics(t *testing.T) { - routes := httpx.NewRouter(testPublicURL(t, "/stick")) + routes := api.NewRouter(testPublicURL(t, "/stick")) routes.SetNotFound(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/html") w.WriteHeader(http.StatusNotFound) diff --git a/internal/web/server.go b/internal/api/server.go similarity index 81% rename from internal/web/server.go rename to internal/api/server.go index 8e1104f..510ac30 100644 --- a/internal/web/server.go +++ b/internal/api/server.go @@ -1,5 +1,4 @@ -// Package web owns the HTTP server lifecycle. -package web +package api import ( "context" @@ -10,12 +9,9 @@ import ( "net/http" "time" - "stick/internal/api" "stick/internal/application" "stick/internal/auth" "stick/internal/publicurl" - "stick/internal/web/health" - "stick/internal/web/httpx" ) // Options contains the settings required to build the HTTP server. @@ -37,7 +33,7 @@ type Runner struct { // NewRunner builds the HTTP application and its dependency graph. // Listening is intentionally deferred to Run so startup failures are reported // through the runner lifecycle rather than escaping during HTTP composition. -func NewRunner(service *application.Service, readiness health.ReadinessChecker, options Options) (*Runner, error) { +func NewRunner(service *application.Service, readiness ReadinessChecker, options Options) (*Runner, error) { handler, err := newHandler(service, readiness, options) if err != nil { return nil, fmt.Errorf("HTTP server: %w", err) @@ -49,20 +45,20 @@ func NewRunner(service *application.Service, readiness health.ReadinessChecker, } // newHandler builds the complete HTTP graph. -func newHandler(service *application.Service, readiness health.ReadinessChecker, options Options) (http.Handler, error) { +func newHandler(service *application.Service, readiness ReadinessChecker, options Options) (http.Handler, error) { if err := options.PublicURL.Validate(); err != nil { return nil, fmt.Errorf("public URL: %w", err) } - router := httpx.NewRouter(options.PublicURL) - health.Register(router, health.New(readiness)) - apiHandler := api.New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, options.PublicURL, options.NotificationsEnabled) - api.Register(router, apiHandler) - router.SetNotFound(http.HandlerFunc(api.NotFound)) + router := NewRouter(options.PublicURL) + RegisterHealth(router, NewHealth(readiness)) + apiHandler := New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, options.PublicURL, options.NotificationsEnabled) + Register(router, apiHandler) + router.SetNotFound(http.HandlerFunc(NotFound)) - middlewares := httpx.Chain( - httpx.RequestLogger, - api.Headers) + middlewares := Chain( + RequestLogger, + Headers) return middlewares(router), nil } diff --git a/internal/api/sticks.go b/internal/api/sticks.go new file mode 100644 index 0000000..a1fa74d --- /dev/null +++ b/internal/api/sticks.go @@ -0,0 +1,186 @@ +package api + +import ( + "net/http" + + "stick/internal/auth" +) + +func (h *Handler) listSticks(w http.ResponseWriter, r *http.Request) { + sticks, err := h.service.ListSticks(r.Context()) + if err != nil { + internalError(w, r, "list sticks", err) + return + } + writeCollection(w, r, sticksToJSON(sticks)) +} + +func (h *Handler) listArchivedSticks(w http.ResponseWriter, r *http.Request) { + identity := auth.IdentityFromContext(r.Context()) + if !identity.IsAdmin { + writeError(w, http.StatusForbidden, "forbidden") + return + } + sticks, err := h.service.ListArchivedSticks(r.Context(), identity) + if err != nil { + handleError(w, r, "list archived sticks", err) + return + } + writeCollection(w, r, sticksToJSON(sticks)) +} + +func (h *Handler) getStick(w http.ResponseWriter, r *http.Request) { + stick, err := h.service.GetStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id")) + if err != nil { + handleError(w, r, "get stick", err) + return + } + setETag(w, stick.Version) + if ifNoneMatch(headerValue(r, "If-None-Match"), etag(stick.Version)) { + notModified(w) + return + } + writeJSON(w, http.StatusOK, stickToJSON(stick)) +} + +func (h *Handler) createStick(w http.ResponseWriter, r *http.Request) { + if !auth.IdentityFromContext(r.Context()).IsAdmin { + writeError(w, http.StatusForbidden, "forbidden") + return + } + var request struct { + Name string `json:"name"` + } + if !decodeJSON(w, r, &request) { + return + } + stick, err := h.service.CreateStick(r.Context(), auth.IdentityFromContext(r.Context()), request.Name) + if err != nil { + handleError(w, r, "create stick", err) + return + } + setETag(w, stick.Version) + w.Header().Set("Location", Absolute(h.publicURL, apiPrefix+"/sticks/"+stick.ID)) + writeJSON(w, http.StatusCreated, stickToJSON(stick)) +} + +func (h *Handler) renameStick(w http.ResponseWriter, r *http.Request) { + if !auth.IdentityFromContext(r.Context()).IsAdmin { + writeError(w, http.StatusForbidden, "forbidden") + return + } + var request struct { + Name string `json:"name"` + } + if !decodeJSON(w, r, &request) { + return + } + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + stick, err := h.service.RenameStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), request.Name, version) + if err != nil { + handleError(w, r, "rename stick", err) + return + } + writeStick(w, stick) +} + +func (h *Handler) archiveStick(w http.ResponseWriter, r *http.Request) { + if !auth.IdentityFromContext(r.Context()).IsAdmin { + writeError(w, http.StatusForbidden, "forbidden") + return + } + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + stick, err := h.service.ArchiveStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version) + if err != nil { + handleError(w, r, "archive stick", err) + return + } + writeStick(w, stick) +} + +func (h *Handler) unarchiveStick(w http.ResponseWriter, r *http.Request) { + if !auth.IdentityFromContext(r.Context()).IsAdmin { + writeError(w, http.StatusForbidden, "forbidden") + return + } + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + stick, err := h.service.UnarchiveStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version) + if err != nil { + handleError(w, r, "unarchive stick", err) + return + } + writeStick(w, stick) +} + +func (h *Handler) claimStick(w http.ResponseWriter, r *http.Request) { + var request struct { + Reason string `json:"reason"` + } + if !decodeJSON(w, r, &request) { + return + } + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + stick, err := h.service.ClaimStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), request.Reason, version) + if err != nil { + handleError(w, r, "claim stick", err) + return + } + writeStick(w, stick) +} + +func (h *Handler) releaseStick(w http.ResponseWriter, r *http.Request) { + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + stick, err := h.service.ReleaseStick(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version) + if err != nil { + handleError(w, r, "release stick", err) + return + } + writeStick(w, stick) +} + +func (h *Handler) history(w http.ResponseWriter, r *http.Request) { + identity := auth.IdentityFromContext(r.Context()) + id := r.PathValue("id") + stick, err := h.service.GetStick(r.Context(), identity, id) + if err != nil { + handleError(w, r, "get stick history", err) + return + } + setETag(w, stick.Version) + limit, offset, ok := historyPagination(w, r) + if !ok { + return + } + sessions, total, err := h.service.GetHistory(r.Context(), identity, id, limit, offset) + if err != nil { + handleError(w, r, "get stick history", err) + return + } + response := struct { + Sessions []sessionJSON `json:"sessions"` + Total int `json:"total"` + Limit int `json:"limit"` + Offset int `json:"offset"` + }{ + Sessions: sessionsToJSON(sessions), + Total: total, + Limit: limit, + Offset: offset, + } + writeConditionalJSON(w, r, response) +} diff --git a/internal/api/subscriptions.go b/internal/api/subscriptions.go new file mode 100644 index 0000000..e333417 --- /dev/null +++ b/internal/api/subscriptions.go @@ -0,0 +1,45 @@ +package api + +import ( + "net/http" + + "stick/internal/auth" +) + +func (h *Handler) subscribe(w http.ResponseWriter, r *http.Request) { + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + if err := h.service.Subscribe(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version); err != nil { + handleError(w, r, "subscribe to stick", err) + return + } + setETag(w, version) + w.WriteHeader(http.StatusNoContent) +} + +func (h *Handler) unsubscribe(w http.ResponseWriter, r *http.Request) { + version, ok := h.expectedVersion(w, r, r.PathValue("id")) + if !ok { + return + } + if err := h.service.Unsubscribe(r.Context(), auth.IdentityFromContext(r.Context()), r.PathValue("id"), version); err != nil { + handleError(w, r, "unsubscribe from stick", err) + return + } + setETag(w, version) + w.WriteHeader(http.StatusNoContent) +} + +func (h *Handler) subscriptions(w http.ResponseWriter, r *http.Request) { + ids, err := h.service.SubscribedStickIDs(r.Context(), auth.IdentityFromContext(r.Context())) + if err != nil { + internalError(w, r, "list subscriptions", err) + return + } + if ids == nil { + ids = []string{} + } + writeCollection(w, r, ids) +} diff --git a/internal/web/httpx/url.go b/internal/api/url.go similarity index 98% rename from internal/web/httpx/url.go rename to internal/api/url.go index dfddce4..2008dbc 100644 --- a/internal/web/httpx/url.go +++ b/internal/api/url.go @@ -1,4 +1,4 @@ -package httpx +package api import ( "fmt" diff --git a/internal/web/httpx/url_test.go b/internal/api/url_test.go similarity index 82% rename from internal/web/httpx/url_test.go rename to internal/api/url_test.go index 337d8a4..00ebd50 100644 --- a/internal/web/httpx/url_test.go +++ b/internal/api/url_test.go @@ -1,10 +1,10 @@ -package httpx_test +package api_test import ( "testing" + "stick/internal/api" "stick/internal/publicurl" - "stick/internal/web/httpx" ) func TestPathComposition(t *testing.T) { @@ -20,10 +20,10 @@ func TestPathComposition(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { publicURL := mustParse(t, "https://example.test", tt.basePath) - if got := httpx.Path(publicURL, tt.reference); got != tt.want { + if got := api.Path(publicURL, tt.reference); got != tt.want { t.Errorf("Path() = %q, want %q", got, tt.want) } - if got := httpx.Absolute(publicURL, tt.reference); got != publicURL.String()+tt.reference { + if got := api.Absolute(publicURL, tt.reference); got != publicURL.String()+tt.reference { t.Errorf("Absolute() = %q", got) } }) @@ -39,7 +39,7 @@ func TestPathRejectsUntrustedReferences(t *testing.T) { t.Fatalf("Path(%q) did not panic", reference) } }() - _ = httpx.Path(publicURL, reference) + _ = api.Path(publicURL, reference) }) } } diff --git a/internal/format/duration.go b/internal/format/duration.go deleted file mode 100644 index de7f0f8..0000000 --- a/internal/format/duration.go +++ /dev/null @@ -1,19 +0,0 @@ -// Package format formats domain values for display in the UI and outbound -// notifications. -package format - -import ( - "fmt" - "time" -) - -// Duration formats a duration using the compact representation used by the -// application. Callers should round to their desired precision first. -func Duration(value time.Duration) string { - hours := int(value.Hours()) - minutes := int(value.Minutes()) % 60 - if hours > 0 { - return fmt.Sprintf("%dh %02dmin", hours, minutes) - } - return fmt.Sprintf("%d min", minutes) -} diff --git a/internal/application/notification.go b/internal/notification/notification.go similarity index 96% rename from internal/application/notification.go rename to internal/notification/notification.go index 2dcd995..ffc8f2b 100644 --- a/internal/application/notification.go +++ b/internal/notification/notification.go @@ -1,4 +1,5 @@ -package application +// Package notification defines transport-neutral notification delivery contracts. +package notification import ( "context" diff --git a/internal/application/notification_test.go b/internal/notification/notification_test.go similarity index 59% rename from internal/application/notification_test.go rename to internal/notification/notification_test.go index e2acafa..5a97625 100644 --- a/internal/application/notification_test.go +++ b/internal/notification/notification_test.go @@ -1,4 +1,4 @@ -package application_test +package notification_test import ( "context" @@ -6,23 +6,23 @@ import ( "strings" "testing" - app "stick/internal/application" + notification "stick/internal/notification" ) func TestNoopNotifier(t *testing.T) { - notifier := app.Noop() - if err := notifier.Notify(context.Background(), app.Notification{}); err != nil { + notifier := notification.Noop() + if err := notifier.Notify(context.Background(), notification.Notification{}); err != nil { t.Errorf("Noop should never error, got %v", err) } } func TestNamedNotifierAttributesErrorAndPreservesCause(t *testing.T) { failure := errors.New("connection refused") - notifier := app.Named("smtp", app.NotifierFunc(func(context.Context, app.Notification) error { + notifier := notification.Named("smtp", notification.NotifierFunc(func(context.Context, notification.Notification) error { return failure })) - err := notifier.Notify(context.Background(), app.Notification{}) + err := notifier.Notify(context.Background(), notification.Notification{}) if !errors.Is(err, failure) { t.Fatalf("Named should preserve the cause, got %v", err) } @@ -35,18 +35,18 @@ func TestFanoutNotifierAttemptsEveryBackendAndJoinsErrors(t *testing.T) { firstFailure := errors.New("first failure") secondFailure := errors.New("second failure") var calls []string - notifier := app.Fanout( - app.Named("first", app.NotifierFunc(func(context.Context, app.Notification) error { + notifier := notification.Fanout( + notification.Named("first", notification.NotifierFunc(func(context.Context, notification.Notification) error { calls = append(calls, "first") return firstFailure })), - app.Named("second", app.NotifierFunc(func(context.Context, app.Notification) error { + notification.Named("second", notification.NotifierFunc(func(context.Context, notification.Notification) error { calls = append(calls, "second") return secondFailure })), ) - err := notifier.Notify(context.Background(), app.Notification{}) + err := notifier.Notify(context.Background(), notification.Notification{}) if !errors.Is(err, firstFailure) || !errors.Is(err, secondFailure) { t.Fatalf("Fanout error = %v, want both causes", err) } diff --git a/internal/format/duration_test.go b/internal/outbox/duration_test.go similarity index 80% rename from internal/format/duration_test.go rename to internal/outbox/duration_test.go index 5530359..fc34480 100644 --- a/internal/format/duration_test.go +++ b/internal/outbox/duration_test.go @@ -1,10 +1,8 @@ -package format_test +package outbox import ( "testing" "time" - - "stick/internal/format" ) func TestDuration(t *testing.T) { @@ -19,7 +17,7 @@ func TestDuration(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - if got := format.Duration(test.value); got != test.want { + if got := formatDuration(test.value); got != test.want { t.Fatalf("Duration(%v) = %q, want %q", test.value, got, test.want) } }) diff --git a/internal/outbox/worker.go b/internal/outbox/worker.go index 03dc0f0..27c752b 100644 --- a/internal/outbox/worker.go +++ b/internal/outbox/worker.go @@ -9,8 +9,7 @@ import ( "time" "uuid" - "stick/internal/application" - "stick/internal/format" + "stick/internal/notification" ) const ( @@ -39,14 +38,14 @@ type WorkerOptions struct { // Worker claims and delivers persisted notification records. type Worker struct { store Store - notifier application.Notifier + notifier notification.Notifier options WorkerOptions } // NewWorker returns a notification worker with normalized options. -func NewWorker(store Store, notifier application.Notifier, options WorkerOptions) *Worker { +func NewWorker(store Store, notifier notification.Notifier, options WorkerOptions) *Worker { if notifier == nil { - notifier = application.Noop() + notifier = notification.Noop() } if options.Location == nil { options.Location = time.UTC @@ -138,14 +137,14 @@ func (w *Worker) processOne(ctx context.Context) (bool, error) { return true, fmt.Errorf("deliver notification %d attempt %d: %w", delivery.ID, delivery.Attempts, err) } -func (w *Worker) notification(delivery Delivery) application.Notification { +func (w *Worker) notification(delivery Delivery) notification.Notification { duration := delivery.ReleasedAt.Sub(delivery.HeldSince).Round(time.Minute) - return application.Notification{ + return notification.Notification{ StickID: delivery.StickID, StickName: delivery.StickName, HolderName: delivery.HolderName, HolderEmail: delivery.HolderEmail, - Duration: format.Duration(duration), + Duration: formatDuration(duration), ReleasedAt: delivery.ReleasedAt.In(w.options.Location).Format("Jan 2 · 15:04"), BaseURL: w.options.BaseURL, RecipientName: delivery.RecipientName, @@ -153,6 +152,15 @@ func (w *Worker) notification(delivery Delivery) application.Notification { } } +func formatDuration(value time.Duration) string { + hours := int(value.Hours()) + minutes := int(value.Minutes()) % 60 + if hours > 0 { + return fmt.Sprintf("%dh %02dmin", hours, minutes) + } + return fmt.Sprintf("%d min", minutes) +} + func (w *Worker) backoff(attempt int) time.Duration { delay := w.options.InitialBackoff for i := 1; i < attempt && delay < w.options.MaxBackoff; i++ { diff --git a/test/integration/outbox_worker_test.go b/test/integration/outbox_worker_test.go index 9e0951e..efefd25 100644 --- a/test/integration/outbox_worker_test.go +++ b/test/integration/outbox_worker_test.go @@ -18,13 +18,14 @@ import ( "stick/internal/adapters/persistence/sqlite" "stick/internal/application" core "stick/internal/core" + "stick/internal/notification" "stick/internal/outbox" ) func TestWorkerSuccessfulDeliveryRecordsOutcomeAndCleansSubscription(t *testing.T) { store, conn := preparedDelivery(t) - delivered := make(chan application.Notification, 1) - worker := testWorker(store, application.NotifierFunc(func(_ context.Context, notification application.Notification) error { + delivered := make(chan notification.Notification, 1) + worker := testWorker(store, notification.NotifierFunc(func(_ context.Context, notification notification.Notification) error { delivered <- notification return nil })) @@ -105,7 +106,7 @@ func TestWorkerDeliversTeamsNotificationAndRecordsOutcome(t *testing.T) { func TestWorkerDeliversToMultipleInstancesOfOneBackend(t *testing.T) { store, conn := preparedDelivery(t) received := make(chan string, 2) - newWebhook := func(name string) application.Notifier { + newWebhook := func(name string) notification.Notifier { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { received <- name w.WriteHeader(http.StatusNoContent) @@ -118,7 +119,7 @@ func TestWorkerDeliversToMultipleInstancesOfOneBackend(t *testing.T) { return notifier } - worker := testWorker(store, application.Multi( + worker := testWorker(store, notification.Multi( newWebhook("first webhook"), newWebhook("second webhook"), )) @@ -143,7 +144,7 @@ func TestWorkerDeliversToMultipleInstancesOfOneBackend(t *testing.T) { func TestWorkerRetriesFailureThenSucceeds(t *testing.T) { store, conn := preparedDelivery(t) var calls atomic.Int32 - worker := testWorker(store, application.NotifierFunc(func(context.Context, application.Notification) error { + worker := testWorker(store, notification.NotifierFunc(func(context.Context, notification.Notification) error { if calls.Add(1) == 1 { return errors.New("temporary SMTP failure") } @@ -180,7 +181,7 @@ func TestWorkerRecoversStaleClaimAfterRestart(t *testing.T) { } var calls atomic.Int32 - worker := testWorker(store, application.NotifierFunc(func(context.Context, application.Notification) error { + worker := testWorker(store, notification.NotifierFunc(func(context.Context, notification.Notification) error { calls.Add(1) return nil })) @@ -195,7 +196,7 @@ func TestWorkerRecoversStaleClaimAfterRestart(t *testing.T) { func TestWorkerRunCancellationStopsCooperativeInFlightNotifier(t *testing.T) { store, conn := preparedDelivery(t) started := make(chan struct{}) - worker := testWorker(store, application.NotifierFunc(func(ctx context.Context, _ application.Notification) error { + worker := testWorker(store, notification.NotifierFunc(func(ctx context.Context, _ notification.Notification) error { close(started) <-ctx.Done() return ctx.Err() @@ -217,7 +218,7 @@ func TestWorkerRunCancellationStopsCooperativeInFlightNotifier(t *testing.T) { func TestWorkerBoundsEachDeliveryAttempt(t *testing.T) { store, conn := preparedDelivery(t) timedOut := make(chan struct{}) - worker := outbox.NewWorker(store, application.NotifierFunc(func(ctx context.Context, _ application.Notification) error { + worker := outbox.NewWorker(store, notification.NotifierFunc(func(ctx context.Context, _ notification.Notification) error { <-ctx.Done() close(timedOut) return ctx.Err() @@ -266,7 +267,7 @@ func TestWorkerDoesNotDeleteNewerResubscription(t *testing.T) { t.Fatal("resubscription reused the captured generation token") } - worker := testWorker(store, application.Noop()) + worker := testWorker(store, notification.Noop()) cancel, done := startWorker(worker) t.Cleanup(func() { stopWorker(t, cancel, done) }) waitForOutbox(t, conn, "succeeded", 1) @@ -288,7 +289,7 @@ func TestWorkerDoesNotDeleteNewerResubscription(t *testing.T) { func TestWorkerUsesInjectedClockForDeliveryOutcome(t *testing.T) { store, conn := preparedDelivery(t) fixed := time.Date(2040, time.January, 2, 3, 4, 5, 0, time.UTC) - worker := outbox.NewWorker(store, application.Noop(), outbox.WorkerOptions{ + worker := outbox.NewWorker(store, notification.Noop(), outbox.WorkerOptions{ PollInterval: time.Millisecond, AttemptTimeout: 100 * time.Millisecond, InitialBackoff: time.Millisecond, @@ -375,7 +376,7 @@ func releaseStick(t *testing.T, store *sqlite.Store, id string, identity core.Id } } -func testWorker(store *sqlite.Store, notifier application.Notifier) *outbox.Worker { +func testWorker(store *sqlite.Store, notifier notification.Notifier) *outbox.Worker { return outbox.NewWorker(store, notifier, outbox.WorkerOptions{ BaseURL: "https://example.com/stick", Location: time.UTC, From 4f969e217766faf07678c6ac1c7720c1107b5498 Mon Sep 17 00:00:00 2001 From: alxtr Date: Sun, 30 Aug 2026 19:34:02 +0000 Subject: [PATCH 03/14] Trying to factor out publicurl --- cmd/stickd/main.go | 2 +- internal/api/handler.go | 5 +- internal/api/handler_test.go | 11 ++--- internal/api/health_test.go | 8 +--- internal/api/router.go | 24 ++++++---- internal/api/router_test.go | 33 +++++++------ internal/api/server.go | 15 ++++-- internal/api/sticks.go | 2 +- internal/api/url.go | 26 ----------- internal/api/url_test.go | 54 --------------------- internal/config/config.go | 8 +--- internal/config/config_test.go | 4 +- internal/config/normalize.go | 36 ++++++++++++++ internal/publicurl/url.go | 85 +++++++--------------------------- internal/publicurl/url_test.go | 56 +++++----------------- 15 files changed, 124 insertions(+), 245 deletions(-) delete mode 100644 internal/api/url.go delete mode 100644 internal/api/url_test.go diff --git a/cmd/stickd/main.go b/cmd/stickd/main.go index 47e4353..f697f6b 100644 --- a/cmd/stickd/main.go +++ b/cmd/stickd/main.go @@ -103,7 +103,7 @@ func mainContext(parent context.Context, args []string) (err error) { components := []application.Component{serverRunner} if notifier != nil { components = append(components, outbox.NewWorker(store, notifier, outbox.WorkerOptions{ - BaseURL: cfg.Server.PublicURL.String(), + BaseURL: cfg.Server.PublicURL, Location: cfg.Timezone, })) } diff --git a/internal/api/handler.go b/internal/api/handler.go index ba1bf08..9c62e9f 100644 --- a/internal/api/handler.go +++ b/internal/api/handler.go @@ -9,7 +9,6 @@ import ( "stick/internal/application" "stick/internal/auth" domain "stick/internal/core" - "stick/internal/publicurl" ) const ( @@ -25,7 +24,7 @@ type Handler struct { service *application.Service validator TokenValidator admins map[string]struct{} - publicURL publicurl.URL + publicURL string notificationsEnabled bool } @@ -39,7 +38,7 @@ func New( service *application.Service, validator TokenValidator, adminEmails []string, - publicURL publicurl.URL, + publicURL string, notificationsEnabled bool, ) *Handler { return &Handler{ diff --git a/internal/api/handler_test.go b/internal/api/handler_test.go index 4de158a..e6dce4e 100644 --- a/internal/api/handler_test.go +++ b/internal/api/handler_test.go @@ -14,7 +14,6 @@ import ( "stick/internal/api" "stick/internal/application" domain "stick/internal/core" - "stick/internal/publicurl" ) type tokenValidator map[string]domain.Identity @@ -34,16 +33,13 @@ func newTestHandler(t *testing.T) http.Handler { t.Fatal(err) } t.Cleanup(func() { _ = store.Close() }) - publicURL, err := publicurl.Parse("http://localhost:8080") - if err != nil { - t.Fatal(err) - } + publicURL := "http://localhost:8080" admin := domain.Identity{Sub: "admin", Name: "Admin", Email: "admin@example.com", EmailVerified: true} handler := api.New(application.NewService(store), tokenValidator{ "admin-token": admin, "user-token": {Sub: "user", Name: "User", Email: "user@example.com", EmailVerified: true}, }, []string{"admin@example.com"}, publicURL, true) - router := api.NewRouter(publicURL) + router := api.NewRouter("") api.Register(router, handler) router.SetNotFound(http.HandlerFunc(api.NotFound)) return router @@ -92,6 +88,9 @@ func TestStickETagAndOptimisticConcurrency(t *testing.T) { if stick.ID == "" || stick.Version != 1 { t.Fatalf("created stick = %+v", stick) } + if got := created.Header().Get("Location"); got != "http://localhost:8080/api/v1/sticks/"+stick.ID { + t.Errorf("Location = %q", got) + } path := "/api/v1/sticks/" + stick.ID current := request(handler, http.MethodGet, path, "user-token", "", nil) diff --git a/internal/api/health_test.go b/internal/api/health_test.go index 7d64cd1..0cbb74a 100644 --- a/internal/api/health_test.go +++ b/internal/api/health_test.go @@ -7,8 +7,6 @@ import ( "net/http/httptest" "testing" "time" - - "stick/internal/publicurl" ) type healthDB struct { @@ -35,11 +33,7 @@ func TestHealthRoutes(t *testing.T) { {name: "missing dependency", path: "/readyz", wantStatus: http.StatusServiceUnavailable, wantBody: "not ready\n"}, } { t.Run(test.name, func(t *testing.T) { - publicURL, err := publicurl.Parse("http://example.test/stick") - if err != nil { - t.Fatal(err) - } - router := NewRouter(publicURL) + router := NewRouter("/stick") var readiness ReadinessChecker if test.readiness != nil { readiness = test.readiness diff --git a/internal/api/router.go b/internal/api/router.go index 0200b2a..f1de736 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -1,24 +1,25 @@ package api import ( + "fmt" "net/http" "slices" "strings" - - "stick/internal/publicurl" ) // Router registers mount-aware net/http routes with optional scoped middleware. type Router struct { mux *http.ServeMux - publicURL publicurl.URL + mountPath string middlewares []Middleware notFound http.Handler } -// NewRouter returns a mount-aware router for publicURL. -func NewRouter(publicURL publicurl.URL) *Router { - return &Router{mux: http.NewServeMux(), publicURL: publicURL} +// NewRouter returns a mount-aware router. mountPath is the optional path from +// an already parsed and validated public URL; the router has no reason to know +// the URL's origin. +func NewRouter(mountPath string) *Router { + return &Router{mux: http.NewServeMux(), mountPath: mountPath} } func (r *Router) ServeHTTP(response http.ResponseWriter, request *http.Request) { @@ -50,7 +51,7 @@ func (r *Router) With(stack ...Middleware) *Router { // Handle registers a route with the router and optional middleware. func (r *Router) Handle(method, reference string, handler http.Handler, middlewares ...Middleware) { combined := append(slices.Clone(r.middlewares), middlewares...) - r.mux.Handle(method+" "+Path(r.publicURL, reference), Chain(combined...)(handler)) + r.mux.Handle(method+" "+r.path(reference), Chain(combined...)(handler)) } // HandleFunc registers a route backed by an http.HandlerFunc. @@ -59,6 +60,13 @@ func (r *Router) HandleFunc(method, reference string, handler http.HandlerFunc, } func (r *Router) containsRequestPath(path string) bool { - mount := r.publicURL.MountPath() + mount := r.mountPath return mount == "" || path == mount || strings.HasPrefix(path, mount+"/") } + +func (r *Router) path(reference string) string { + if reference == "" || reference[0] != '/' || strings.HasPrefix(reference, "//") || strings.ContainsAny(reference, `\#`) { + panic(fmt.Sprintf("invalid application-relative reference %q", reference)) + } + return r.mountPath + reference +} diff --git a/internal/api/router_test.go b/internal/api/router_test.go index c11f2da..db5ab76 100644 --- a/internal/api/router_test.go +++ b/internal/api/router_test.go @@ -6,21 +6,15 @@ import ( "testing" "stick/internal/api" - "stick/internal/publicurl" ) -func testPublicURL(t *testing.T, mountPath string) publicurl.URL { +func testMountPath(t *testing.T, mountPath string) string { t.Helper() - publicURL, err := publicurl.Parse("http://example.test" + mountPath) - if err != nil { - t.Fatal(err) - } - return publicURL + return mountPath } func TestRouterWithScopesMiddleware(t *testing.T) { - publicURL := testPublicURL(t, "") - routes := api.NewRouter(publicURL) + routes := api.NewRouter(testMountPath(t, "")) reject := func(http.Handler) http.Handler { return http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) { response.WriteHeader(http.StatusUnauthorized) @@ -48,8 +42,7 @@ func TestRouterWithScopesMiddleware(t *testing.T) { } func TestRouterPreservesNestedMountAndPathValues(t *testing.T) { - publicURL := testPublicURL(t, "/ops/stick") - routes := api.NewRouter(publicURL) + routes := api.NewRouter(testMountPath(t, "/ops/stick")) routes.HandleFunc(http.MethodGet, "/sticks/{id}", func(w http.ResponseWriter, r *http.Request) { if got := r.URL.Path; got != "/ops/stick/sticks/aa001" { t.Errorf("handler path = %q", got) @@ -72,7 +65,7 @@ func TestRouterPreservesNestedMountAndPathValues(t *testing.T) { } func TestRouterUsesCustomNotFoundOnlyInsideMount(t *testing.T) { - routes := api.NewRouter(testPublicURL(t, "/stick")) + routes := api.NewRouter(testMountPath(t, "/stick")) routes.SetNotFound(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/html") w.WriteHeader(http.StatusNotFound) @@ -93,7 +86,7 @@ func TestRouterUsesCustomNotFoundOnlyInsideMount(t *testing.T) { } func TestRouterCustomNotFoundAndRedirectSemantics(t *testing.T) { - routes := api.NewRouter(testPublicURL(t, "/stick")) + routes := api.NewRouter(testMountPath(t, "/stick")) routes.SetNotFound(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/html") w.WriteHeader(http.StatusNotFound) @@ -141,3 +134,17 @@ func TestRouterCustomNotFoundAndRedirectSemantics(t *testing.T) { }) } } + +func TestRouterRejectsUntrustedReferences(t *testing.T) { + routes := api.NewRouter("/stick") + for _, reference := range []string{"", "api/v1/sticks", "//evil.example", `/stick\\one`, "/stick#fragment"} { + t.Run(reference, func(t *testing.T) { + defer func() { + if recover() == nil { + t.Fatalf("Handle(%q) did not panic", reference) + } + }() + routes.Handle(http.MethodGet, reference, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + }) + } +} diff --git a/internal/api/server.go b/internal/api/server.go index 510ac30..5756d67 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -7,6 +7,7 @@ import ( "log/slog" "net" "net/http" + "net/url" "time" "stick/internal/application" @@ -16,7 +17,7 @@ import ( // Options contains the settings required to build the HTTP server. type Options struct { - PublicURL publicurl.URL + PublicURL string ListenAddr string JWT auth.JWTConfig AdminEmails []string @@ -46,13 +47,19 @@ func NewRunner(service *application.Service, readiness ReadinessChecker, options // newHandler builds the complete HTTP graph. func newHandler(service *application.Service, readiness ReadinessChecker, options Options) (http.Handler, error) { - if err := options.PublicURL.Validate(); err != nil { + publicURL, err := publicurl.Parse(options.PublicURL) + if err != nil { return nil, fmt.Errorf("public URL: %w", err) } + parsedPublicURL, err := url.Parse(publicURL) + if err != nil { + return nil, fmt.Errorf("public URL: %w", err) + } + + router := NewRouter(parsedPublicURL.Path) + apiHandler := New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, publicURL, options.NotificationsEnabled) - router := NewRouter(options.PublicURL) RegisterHealth(router, NewHealth(readiness)) - apiHandler := New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, options.PublicURL, options.NotificationsEnabled) Register(router, apiHandler) router.SetNotFound(http.HandlerFunc(NotFound)) diff --git a/internal/api/sticks.go b/internal/api/sticks.go index a1fa74d..e29a3ac 100644 --- a/internal/api/sticks.go +++ b/internal/api/sticks.go @@ -60,7 +60,7 @@ func (h *Handler) createStick(w http.ResponseWriter, r *http.Request) { return } setETag(w, stick.Version) - w.Header().Set("Location", Absolute(h.publicURL, apiPrefix+"/sticks/"+stick.ID)) + w.Header().Set("Location", h.publicURL+apiPrefix+"/sticks/"+stick.ID) writeJSON(w, http.StatusCreated, stickToJSON(stick)) } diff --git a/internal/api/url.go b/internal/api/url.go deleted file mode 100644 index 2008dbc..0000000 --- a/internal/api/url.go +++ /dev/null @@ -1,26 +0,0 @@ -package api - -import ( - "fmt" - "strings" - - "stick/internal/publicurl" -) - -// Path prefixes a trusted application-relative path, query string, or -// ServeMux pattern with the configured mount path. -func Path(publicURL publicurl.URL, reference string) string { - if reference == "" || reference[0] != '/' || strings.HasPrefix(reference, "//") || strings.ContainsAny(reference, `\#`) { - panic(fmt.Sprintf("invalid application-relative reference %q", reference)) - } - if publicURL.MountPath() == "" { - return reference - } - return publicURL.MountPath() + reference -} - -// Absolute returns an absolute URL for a trusted application-relative -// reference. -func Absolute(publicURL publicurl.URL, reference string) string { - return publicURL.Origin() + Path(publicURL, reference) -} diff --git a/internal/api/url_test.go b/internal/api/url_test.go deleted file mode 100644 index 00ebd50..0000000 --- a/internal/api/url_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package api_test - -import ( - "testing" - - "stick/internal/api" - "stick/internal/publicurl" -) - -func TestPathComposition(t *testing.T) { - tests := []struct { - name string - basePath string - reference string - want string - }{ - {name: "root", reference: "/api/v1/sticks", want: "/api/v1/sticks"}, - {name: "mounted", basePath: "/ops/stick", reference: "/api/v1/sticks", want: "/ops/stick/api/v1/sticks"}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - publicURL := mustParse(t, "https://example.test", tt.basePath) - if got := api.Path(publicURL, tt.reference); got != tt.want { - t.Errorf("Path() = %q, want %q", got, tt.want) - } - if got := api.Absolute(publicURL, tt.reference); got != publicURL.String()+tt.reference { - t.Errorf("Absolute() = %q", got) - } - }) - } -} - -func TestPathRejectsUntrustedReferences(t *testing.T) { - publicURL := mustParse(t, "https://example.test", "/stick") - for _, reference := range []string{"", "api/v1/sticks", "//evil.example", `/stick\\one`, "/stick#fragment"} { - t.Run(reference, func(t *testing.T) { - defer func() { - if recover() == nil { - t.Fatalf("Path(%q) did not panic", reference) - } - }() - _ = api.Path(publicURL, reference) - }) - } -} - -func mustParse(t *testing.T, baseURL, basePath string) publicurl.URL { - t.Helper() - publicURL, err := publicurl.Parse(baseURL + basePath) - if err != nil { - t.Fatal(err) - } - return publicURL -} diff --git a/internal/config/config.go b/internal/config/config.go index 944b22b..9626fd3 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,11 +1,7 @@ // Package config loads and validates application configuration. package config -import ( - "time" - - "stick/internal/publicurl" -) +import "time" // Database driver names identify the configured persistence backend. const ( @@ -16,7 +12,7 @@ const ( // ServerConfig contains the HTTP server's deployment settings. type ServerConfig struct { - PublicURL publicurl.URL + PublicURL string ListenAddr string } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 4c4d903..5228d2a 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -82,7 +82,7 @@ func TestLoadDefaultsPublicURL(t *testing.T) { setRequiredEnv(t) t.Setenv("STICK_SERVER_PUBLIC_URL", "") cfg := loadFromEnv(t) - if got := cfg.Server.PublicURL.String(); got != "http://localhost" { + if got := cfg.Server.PublicURL; got != "http://localhost" { t.Fatalf("PublicURL = %q, want http://localhost", got) } } @@ -114,7 +114,7 @@ timezone: America/New_York if cfg.Auth.Audience != "env-api" || cfg.Auth.IDPEndpoint != "https://yaml.example.com" || cfg.Auth.Scope != "stick:read" { t.Fatalf("auth = %+v", cfg.Auth) } - if got := cfg.Server.PublicURL.String(); got != "https://env.example.com/stick" { + if got := cfg.Server.PublicURL; got != "https://env.example.com/stick" { t.Errorf("PublicURL = %q", got) } want, _ := time.LoadLocation("America/New_York") diff --git a/internal/config/normalize.go b/internal/config/normalize.go index d361e15..f3fbc91 100644 --- a/internal/config/normalize.go +++ b/internal/config/normalize.go @@ -16,9 +16,45 @@ func normalize(config Config) (Config, error) { if config.Server.ListenAddr == "" { config.Server.ListenAddr = ":8080" } +<<<<<<< HEAD if err := config.Server.PublicURL.Validate(); err != nil { if err := setPublicURL(&config, "http://localhost"); err != nil { return Config{}, err +======= + database, err := normalizeDatabase(raw.Database) + if err != nil { + return Config{}, err + } + publicURLValue := strings.TrimSpace(raw.Server.PublicURL) + if publicURLValue == "" { + publicURLValue = "http://localhost" + } + publicURL, err := publicurl.Parse(publicURLValue) + if err != nil { + return Config{}, err + } + parsedPublicURL, err := url.Parse(publicURL) + if err != nil { + // publicurl.Parse already parsed and validated this value. Keep this + // guard local to the configuration boundary if that implementation + // changes in the future. + return Config{}, fmt.Errorf("invalid PUBLIC_URL %q: %w", publicURLValue, err) + } + if parsedPublicURL.Scheme != "https" && !netutil.IsLoopbackHost(parsedPublicURL.Hostname()) { + return Config{}, fmt.Errorf("invalid PUBLIC_URL %q: HTTPS is required for non-local addresses", publicURLValue) + } + + listenAddr := strings.TrimSpace(raw.Server.ListenAddr) + if listenAddr == "" { + listenAddr = ":8080" + } + + location := time.UTC + if raw.Timezone != "" { + location, err = time.LoadLocation(raw.Timezone) + if err != nil { + return Config{}, fmt.Errorf("invalid timezone %q: %w", raw.Timezone, err) +>>>>>>> 39d6435 (Trying to factor out publicurl) } } if config.Timezone == nil { diff --git a/internal/publicurl/url.go b/internal/publicurl/url.go index a6a3c47..83c6056 100644 --- a/internal/publicurl/url.go +++ b/internal/publicurl/url.go @@ -8,62 +8,56 @@ import ( "net/url" "strconv" "strings" - - "stick/internal/netutil" ) -// URL is an immutable, validated public application URL. It contains an -// origin and an optional application mount path. Its zero value is -// intentionally invalid; values must be constructed with Parse. -type URL struct { - origin string - mountPath string -} - // Parse validates and normalizes the complete public application URL. A lone // trailing slash is accepted. Mount segments are deliberately limited to a // conservative set of ASCII URL characters so they are safe in URLs, ServeMux // patterns, and cookie paths without context-specific escaping. -func Parse(publicURL string) (URL, error) { +// +// The normalized URL is returned as a string. Consumers that need the mount +// path should derive it at the routing boundary; other consumers can keep the +// complete public URL unchanged. +func Parse(publicURL string) (string, error) { if publicURL == "" { - return URL{}, invalidPublicURL(publicURL, "must not be empty") + return "", invalidPublicURL(publicURL, "must not be empty") } for _, r := range publicURL { if r > 0x7f || r <= 0x20 || r == 0x7f { - return URL{}, invalidPublicURL(publicURL, "must contain only visible ASCII characters") + return "", invalidPublicURL(publicURL, "must contain only visible ASCII characters") } } if strings.ContainsAny(publicURL, `\%`) { - return URL{}, invalidPublicURL(publicURL, "backslashes and percent escapes are not supported") + return "", invalidPublicURL(publicURL, "backslashes and percent escapes are not supported") } parsed, err := url.Parse(publicURL) if err != nil { - return URL{}, fmt.Errorf("invalid PUBLIC_URL %q: %w", publicURL, err) + return "", fmt.Errorf("invalid PUBLIC_URL %q: %w", publicURL, err) } if parsed.Scheme != "http" && parsed.Scheme != "https" { - return URL{}, invalidPublicURL(publicURL, "scheme must be http or https") + return "", invalidPublicURL(publicURL, "scheme must be http or https") } if !parsed.IsAbs() || parsed.Host == "" || parsed.Hostname() == "" || parsed.Opaque != "" { - return URL{}, invalidPublicURL(publicURL, "must be an absolute URL with a hostname") + return "", invalidPublicURL(publicURL, "must be an absolute URL with a hostname") } if parsed.User != nil { - return URL{}, invalidPublicURL(publicURL, "user information is not supported") + return "", invalidPublicURL(publicURL, "user information is not supported") } if parsed.RawQuery != "" || parsed.ForceQuery || parsed.Fragment != "" || strings.Contains(publicURL, "#") { - return URL{}, invalidPublicURL(publicURL, "must not include a query or fragment") + return "", invalidPublicURL(publicURL, "must not include a query or fragment") } if err := validateAuthority(parsed); err != nil { - return URL{}, invalidPublicURL(publicURL, err.Error()) + return "", invalidPublicURL(publicURL, err.Error()) } mountPath, err := normalizeMountPath(parsed.Path) if err != nil { - return URL{}, invalidPublicURL(publicURL, err.Error()) + return "", invalidPublicURL(publicURL, err.Error()) } origin := parsed.Scheme + "://" + parsed.Host - return URL{origin: origin, mountPath: mountPath}, nil + return origin + mountPath, nil } func normalizeMountPath(path string) (string, error) { @@ -138,50 +132,3 @@ func isAlphaNumeric(c byte) bool { func invalidPublicURL(raw, reason string) error { return fmt.Errorf("invalid PUBLIC_URL %q: %s", raw, reason) } - -// Validate reports whether u was constructed by Parse. Because URL's fields -// are private, a non-zero value is always valid outside this package. -func (u URL) Validate() error { - if u.origin == "" { - return errors.New("publicurl.URL is invalid: construct it with publicurl.Parse") - } - return nil -} - -func (u URL) assertValid() { - if err := u.Validate(); err != nil { - panic(err.Error()) - } -} - -func (u URL) String() string { - u.assertValid() - return u.origin + u.mountPath -} - -// Origin returns the normalized scheme and authority without the application -// mount path. -func (u URL) Origin() string { - u.assertValid() - return u.origin -} - -// MountPath returns the normalized mount path, or an empty string for a root -// deployment. -func (u URL) MountPath() string { - u.assertValid() - return u.mountPath -} - -// IsHTTPS reports whether the public origin uses HTTPS. -func (u URL) IsHTTPS() bool { - u.assertValid() - return strings.HasPrefix(u.origin, "https://") -} - -// IsLoopback reports whether the public URL points at the local machine. -func (u URL) IsLoopback() bool { - u.assertValid() - parsed, err := url.Parse(u.origin) - return err == nil && netutil.IsLoopbackHost(parsed.Hostname()) -} diff --git a/internal/publicurl/url_test.go b/internal/publicurl/url_test.go index a97cdac..c0dd38f 100644 --- a/internal/publicurl/url_test.go +++ b/internal/publicurl/url_test.go @@ -9,19 +9,16 @@ import ( func TestParseAndCompose(t *testing.T) { tests := []struct { - name string - value string - wantString string - wantOrigin string - wantMount string - wantHTTPS bool + name string + value string + want string }{ - {name: "root", value: "http://localhost:8080", wantString: "http://localhost:8080", wantOrigin: "http://localhost:8080"}, - {name: "root slash", value: "https://example.com/", wantString: "https://example.com", wantOrigin: "https://example.com", wantHTTPS: true}, - {name: "mounted", value: "https://example.com/stick/", wantString: "https://example.com/stick", wantOrigin: "https://example.com", wantMount: "/stick", wantHTTPS: true}, - {name: "nested", value: "http://127.0.0.1:8080/ops/stick", wantString: "http://127.0.0.1:8080/ops/stick", wantOrigin: "http://127.0.0.1:8080", wantMount: "/ops/stick"}, - {name: "period in segment", value: "https://example.com/apps/stick.v2", wantString: "https://example.com/apps/stick.v2", wantOrigin: "https://example.com", wantMount: "/apps/stick.v2", wantHTTPS: true}, - {name: "IPv6 authority", value: "http://[::1]:8080", wantString: "http://[::1]:8080", wantOrigin: "http://[::1]:8080"}, + {name: "root", value: "http://localhost:8080", want: "http://localhost:8080"}, + {name: "root slash", value: "https://example.com/", want: "https://example.com"}, + {name: "mounted", value: "https://example.com/stick/", want: "https://example.com/stick"}, + {name: "nested", value: "http://127.0.0.1:8080/ops/stick", want: "http://127.0.0.1:8080/ops/stick"}, + {name: "period in segment", value: "https://example.com/apps/stick.v2", want: "https://example.com/apps/stick.v2"}, + {name: "IPv6 authority", value: "http://[::1]:8080", want: "http://[::1]:8080"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -29,17 +26,8 @@ func TestParseAndCompose(t *testing.T) { if err != nil { t.Fatalf("Parse: %v", err) } - if got := value.String(); got != tt.wantString { - t.Errorf("String() = %q, want %q", got, tt.wantString) - } - if got := value.Origin(); got != tt.wantOrigin { - t.Errorf("Origin() = %q, want %q", got, tt.wantOrigin) - } - if got := value.MountPath(); got != tt.wantMount { - t.Errorf("MountPath() = %q, want %q", got, tt.wantMount) - } - if got := value.IsHTTPS(); got != tt.wantHTTPS { - t.Errorf("IsHTTPS() = %v, want %v", got, tt.wantHTTPS) + if value != tt.want { + t.Errorf("Parse() = %q, want %q", value, tt.want) } }) } @@ -65,25 +53,3 @@ func TestParseRejectsInvalidURLs(t *testing.T) { }) } } - -func TestZeroValueFailsClearly(t *testing.T) { - assertPanics := func(name string, f func()) { - t.Helper() - t.Run(name, func(t *testing.T) { - defer func() { - if recover() == nil { - t.Fatal("zero-value URL did not panic") - } - }() - f() - }) - } - var zero publicurl.URL - if err := zero.Validate(); err == nil { - t.Fatal("zero-value URL passed validation") - } - assertPanics("String", func() { _ = zero.String() }) - assertPanics("MountPath", func() { zero.MountPath() }) - assertPanics("IsHTTPS", func() { zero.IsHTTPS() }) - assertPanics("Origin", func() { zero.Origin() }) -} From 0841d4c37d44600cfad1447b49359f39893833bb Mon Sep 17 00:00:00 2001 From: alxtr Date: Sun, 30 Aug 2026 19:42:28 +0000 Subject: [PATCH 04/14] merge health files --- internal/api/health.go | 6 ++++++ internal/api/health_routes.go | 11 ----------- internal/api/server.go | 3 ++- 3 files changed, 8 insertions(+), 12 deletions(-) delete mode 100644 internal/api/health_routes.go diff --git a/internal/api/health.go b/internal/api/health.go index 2d79f4c..f67e815 100644 --- a/internal/api/health.go +++ b/internal/api/health.go @@ -24,6 +24,12 @@ func NewHealth(readiness ReadinessChecker) *healthHandler { return &healthHandler{readiness: readiness} } +// RegisterHealth registers the liveness and readiness routes. +func RegisterHealth(router *Router, handler *healthHandler) { + router.HandleFunc(http.MethodGet, "/healthz", handler.Liveness) + router.HandleFunc(http.MethodGet, "/readyz", handler.Readiness) +} + // Liveness serves the process liveness probe. func (h *healthHandler) Liveness(w http.ResponseWriter, _ *http.Request) { h.writeStatus(w, http.StatusOK, "ok\n") diff --git a/internal/api/health_routes.go b/internal/api/health_routes.go deleted file mode 100644 index 8797213..0000000 --- a/internal/api/health_routes.go +++ /dev/null @@ -1,11 +0,0 @@ -package api - -import ( - "net/http" -) - -// RegisterHealth registers the liveness and readiness routes. -func RegisterHealth(router *Router, handler *healthHandler) { - router.HandleFunc(http.MethodGet, "/healthz", handler.Liveness) - router.HandleFunc(http.MethodGet, "/readyz", handler.Readiness) -} diff --git a/internal/api/server.go b/internal/api/server.go index 5756d67..70058f5 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -58,8 +58,9 @@ func newHandler(service *application.Service, readiness ReadinessChecker, option router := NewRouter(parsedPublicURL.Path) apiHandler := New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, publicURL, options.NotificationsEnabled) + healthHandler := NewHealth(readiness) - RegisterHealth(router, NewHealth(readiness)) + RegisterHealth(router, healthHandler) Register(router, apiHandler) router.SetNotFound(http.HandlerFunc(NotFound)) From 6df23810eb183af52a4e1c9a4bd7955c80529c0c Mon Sep 17 00:00:00 2001 From: alxtr Date: Sun, 30 Aug 2026 19:55:42 +0000 Subject: [PATCH 05/14] handler methods --- internal/api/handler.go | 32 ++++++++++++++++---------------- internal/api/handler_test.go | 2 +- internal/api/health.go | 8 ++++---- internal/api/health_test.go | 2 +- internal/api/server.go | 6 +++--- 5 files changed, 25 insertions(+), 25 deletions(-) diff --git a/internal/api/handler.go b/internal/api/handler.go index 9c62e9f..93a9aad 100644 --- a/internal/api/handler.go +++ b/internal/api/handler.go @@ -52,22 +52,22 @@ func New( // Register adds all API routes to router. Authentication is applied to the // complete API route family; health probes remain unauthenticated. -func Register(router *Router, handler *Handler) { - protected := router.With(handler.authenticate) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks", handler.listSticks) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks", handler.createStick) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/archived", handler.listArchivedSticks) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}", handler.getStick) - protected.HandleFunc(http.MethodPatch, apiPrefix+"/sticks/{id}", handler.renameStick) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}/history", handler.history) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/claim", handler.claimStick) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/release", handler.releaseStick) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/archive", handler.archiveStick) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/unarchive", handler.unarchiveStick) - if handler.notificationsEnabled { - protected.HandleFunc(http.MethodPut, apiPrefix+"/sticks/{id}/subscription", handler.subscribe) - protected.HandleFunc(http.MethodDelete, apiPrefix+"/sticks/{id}/subscription", handler.unsubscribe) - protected.HandleFunc(http.MethodGet, apiPrefix+"/subscriptions", handler.subscriptions) +func (h *Handler) Register(router *Router) { + protected := router.With(h.authenticate) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks", h.listSticks) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks", h.createStick) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/archived", h.listArchivedSticks) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}", h.getStick) + protected.HandleFunc(http.MethodPatch, apiPrefix+"/sticks/{id}", h.renameStick) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}/history", h.history) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/claim", h.claimStick) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/release", h.releaseStick) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/archive", h.archiveStick) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/unarchive", h.unarchiveStick) + if h.notificationsEnabled { + protected.HandleFunc(http.MethodPut, apiPrefix+"/sticks/{id}/subscription", h.subscribe) + protected.HandleFunc(http.MethodDelete, apiPrefix+"/sticks/{id}/subscription", h.unsubscribe) + protected.HandleFunc(http.MethodGet, apiPrefix+"/subscriptions", h.subscriptions) } } diff --git a/internal/api/handler_test.go b/internal/api/handler_test.go index e6dce4e..875e3c7 100644 --- a/internal/api/handler_test.go +++ b/internal/api/handler_test.go @@ -40,7 +40,7 @@ func newTestHandler(t *testing.T) http.Handler { "user-token": {Sub: "user", Name: "User", Email: "user@example.com", EmailVerified: true}, }, []string{"admin@example.com"}, publicURL, true) router := api.NewRouter("") - api.Register(router, handler) + handler.Register(router) router.SetNotFound(http.HandlerFunc(api.NotFound)) return router } diff --git a/internal/api/health.go b/internal/api/health.go index f67e815..55afc02 100644 --- a/internal/api/health.go +++ b/internal/api/health.go @@ -24,10 +24,10 @@ func NewHealth(readiness ReadinessChecker) *healthHandler { return &healthHandler{readiness: readiness} } -// RegisterHealth registers the liveness and readiness routes. -func RegisterHealth(router *Router, handler *healthHandler) { - router.HandleFunc(http.MethodGet, "/healthz", handler.Liveness) - router.HandleFunc(http.MethodGet, "/readyz", handler.Readiness) +// Register adds the liveness and readiness routes to router. +func (h *healthHandler) Register(router *Router) { + router.HandleFunc(http.MethodGet, "/healthz", h.Liveness) + router.HandleFunc(http.MethodGet, "/readyz", h.Readiness) } // Liveness serves the process liveness probe. diff --git a/internal/api/health_test.go b/internal/api/health_test.go index 0cbb74a..149723d 100644 --- a/internal/api/health_test.go +++ b/internal/api/health_test.go @@ -38,7 +38,7 @@ func TestHealthRoutes(t *testing.T) { if test.readiness != nil { readiness = test.readiness } - RegisterHealth(router, NewHealth(readiness)) + NewHealth(readiness).Register(router) recorder := httptest.NewRecorder() router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/stick"+test.path, nil)) diff --git a/internal/api/server.go b/internal/api/server.go index 70058f5..69e3c0f 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -57,11 +57,11 @@ func newHandler(service *application.Service, readiness ReadinessChecker, option } router := NewRouter(parsedPublicURL.Path) - apiHandler := New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, publicURL, options.NotificationsEnabled) healthHandler := NewHealth(readiness) + apiHandler := New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, publicURL, options.NotificationsEnabled) - RegisterHealth(router, healthHandler) - Register(router, apiHandler) + healthHandler.Register(router) + apiHandler.Register(router) router.SetNotFound(http.HandlerFunc(NotFound)) middlewares := Chain( From c25e3eed5896f3dc162656af1716812cef756898 Mon Sep 17 00:00:00 2001 From: alxtr Date: Mon, 31 Aug 2026 23:30:35 +0000 Subject: [PATCH 06/14] route groups packages --- internal/api/handler.go | 93 +++------------- internal/api/health.go | 58 ++-------- internal/api/health/handler.go | 69 ++++++++++++ internal/api/request_log.go | 85 +------------- internal/api/requestlog/requestlog.go | 105 ++++++++++++++++++ internal/api/server.go | 12 +- internal/api/{ => sticks}/conditions.go | 2 +- .../api/{sticks.go => sticks/endpoints.go} | 2 +- internal/api/sticks/handler.go | 103 +++++++++++++++++ internal/api/{ => sticks}/responses.go | 5 +- internal/api/{ => sticks}/subscriptions.go | 2 +- 11 files changed, 324 insertions(+), 212 deletions(-) create mode 100644 internal/api/health/handler.go create mode 100644 internal/api/requestlog/requestlog.go rename internal/api/{ => sticks}/conditions.go (99%) rename internal/api/{sticks.go => sticks/endpoints.go} (99%) create mode 100644 internal/api/sticks/handler.go rename internal/api/{ => sticks}/responses.go (98%) rename internal/api/{ => sticks}/subscriptions.go (98%) diff --git a/internal/api/handler.go b/internal/api/handler.go index 93a9aad..77bc972 100644 --- a/internal/api/handler.go +++ b/internal/api/handler.go @@ -1,39 +1,22 @@ -// Package api provides the JSON REST API for Stick. +// Package api provides the HTTP server and routing infrastructure for Stick. package api import ( - "context" + "encoding/json" "net/http" - "strings" + "stick/internal/api/sticks" "stick/internal/application" - "stick/internal/auth" - domain "stick/internal/core" ) -const ( - apiPrefix = "/api/v1" - maxJSONBodyBytes = 1 << 20 - defaultHistoryLimit = 20 - maxHistoryLimit = 100 - maxHistoryOffset = 100_000 -) - -// Handler serves the Stick REST API. -type Handler struct { - service *application.Service - validator TokenValidator - admins map[string]struct{} - publicURL string - notificationsEnabled bool -} +// Handler is kept as an alias for compatibility with callers that used the +// original root API package. New code should use api/sticks directly. +type Handler = sticks.Handler -// TokenValidator authenticates one external bearer token. -type TokenValidator interface { - Validate(context.Context, string) (domain.Identity, error) -} +// TokenValidator is the validator used by the Stick route group. +type TokenValidator = sticks.TokenValidator -// New returns an API handler. +// New returns a Stick API handler. New code should use sticks.New directly. func New( service *application.Service, validator TokenValidator, @@ -41,58 +24,16 @@ func New( publicURL string, notificationsEnabled bool, ) *Handler { - return &Handler{ - service: service, - validator: validator, - admins: auth.AdminSet(adminEmails), - publicURL: publicURL, - notificationsEnabled: notificationsEnabled, - } -} - -// Register adds all API routes to router. Authentication is applied to the -// complete API route family; health probes remain unauthenticated. -func (h *Handler) Register(router *Router) { - protected := router.With(h.authenticate) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks", h.listSticks) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks", h.createStick) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/archived", h.listArchivedSticks) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}", h.getStick) - protected.HandleFunc(http.MethodPatch, apiPrefix+"/sticks/{id}", h.renameStick) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}/history", h.history) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/claim", h.claimStick) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/release", h.releaseStick) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/archive", h.archiveStick) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/unarchive", h.unarchiveStick) - if h.notificationsEnabled { - protected.HandleFunc(http.MethodPut, apiPrefix+"/sticks/{id}/subscription", h.subscribe) - protected.HandleFunc(http.MethodDelete, apiPrefix+"/sticks/{id}/subscription", h.unsubscribe) - protected.HandleFunc(http.MethodGet, apiPrefix+"/subscriptions", h.subscriptions) - } + return sticks.New(service, validator, adminEmails, publicURL, notificationsEnabled) } // NotFound writes the JSON response used for unknown API routes. func NotFound(w http.ResponseWriter, _ *http.Request) { - writeError(w, http.StatusNotFound, "not found") -} - -func (h *Handler) authenticate(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - parts := strings.Fields(r.Header.Get("Authorization")) - if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { - unauthorized(w) - return - } - if h.validator == nil { - writeError(w, http.StatusInternalServerError, "internal server error") - return - } - identity, err := h.validator.Validate(r.Context(), parts[1]) - if err != nil { - unauthorized(w) - return - } - identity = auth.WithAdminStatus(identity, h.admins) - next.ServeHTTP(w, r.WithContext(auth.WithIdentity(r.Context(), identity))) - }) + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusNotFound) + data, _ := json.Marshal(struct { + Error string `json:"error"` + }{Error: "not found"}) + _, _ = w.Write(data) } diff --git a/internal/api/health.go b/internal/api/health.go index 55afc02..8654c23 100644 --- a/internal/api/health.go +++ b/internal/api/health.go @@ -1,57 +1,21 @@ package api import ( - "context" - "net/http" - "time" + "stick/internal/api/health" ) -const readinessTimeout = 2 * time.Second - // ReadinessChecker is the dependency used by the readiness probe. -type ReadinessChecker interface { - PingContext(context.Context) error -} - -// healthHandler provides unauthenticated process and dependency probes. Responses -// contain no configuration or database details. -type healthHandler struct { - readiness ReadinessChecker -} - -// NewHealth returns a health handler backed by readiness. -func NewHealth(readiness ReadinessChecker) *healthHandler { - return &healthHandler{readiness: readiness} -} - -// Register adds the liveness and readiness routes to router. -func (h *healthHandler) Register(router *Router) { - router.HandleFunc(http.MethodGet, "/healthz", h.Liveness) - router.HandleFunc(http.MethodGet, "/readyz", h.Readiness) -} +type ReadinessChecker = health.ReadinessChecker -// Liveness serves the process liveness probe. -func (h *healthHandler) Liveness(w http.ResponseWriter, _ *http.Request) { - h.writeStatus(w, http.StatusOK, "ok\n") -} +// healthHandler is kept as an alias for compatibility with the original root +// API package. New code should use health.Handler directly. +type healthHandler = health.Handler -// Readiness serves the database readiness probe. -func (h *healthHandler) Readiness(w http.ResponseWriter, r *http.Request) { - ctx, cancel := context.WithTimeout(r.Context(), readinessTimeout) - defer cancel() - // Readiness deliberately reflects only the required database dependency. - // Identity-provider discovery is lazy, so an identity-provider outage does - // not remove otherwise healthy instances from service. - if h.readiness == nil || h.readiness.PingContext(ctx) != nil { - h.writeStatus(w, http.StatusServiceUnavailable, "not ready\n") - return - } - h.writeStatus(w, http.StatusOK, "ready\n") -} +// readinessTimeout preserves the original package-local test seam. +const readinessTimeout = health.ReadinessTimeout -func (h *healthHandler) writeStatus(w http.ResponseWriter, status int, body string) { - w.Header().Set("Cache-Control", "no-store") - w.Header().Set("Content-Type", "text/plain; charset=utf-8") - w.WriteHeader(status) - _, _ = w.Write([]byte(body)) +// NewHealth returns a health handler backed by readiness. New code should use +// health.New directly. +func NewHealth(readiness ReadinessChecker) *healthHandler { + return health.New(readiness) } diff --git a/internal/api/health/handler.go b/internal/api/health/handler.go new file mode 100644 index 0000000..cbb8062 --- /dev/null +++ b/internal/api/health/handler.go @@ -0,0 +1,69 @@ +// Package health provides the process and dependency health endpoints. +package health + +import ( + "context" + "net/http" + "time" +) + +const ( + // ReadinessTimeout is the maximum time spent checking the readiness + // dependency. + ReadinessTimeout = 2 * time.Second +) + +// RouteRegistrar is the part of the API router needed to register routes. +// Keeping the interface here avoids coupling route groups to the server's +// router implementation. +type RouteRegistrar interface { + HandleFunc(method, reference string, handler http.HandlerFunc, middlewares ...func(http.Handler) http.Handler) +} + +// ReadinessChecker is the dependency used by the readiness probe. +type ReadinessChecker interface { + PingContext(context.Context) error +} + +// Handler provides unauthenticated process and dependency probes. Responses +// contain no configuration or database details. +type Handler struct { + readiness ReadinessChecker +} + +// New returns a health handler backed by readiness. +func New(readiness ReadinessChecker) *Handler { + return &Handler{readiness: readiness} +} + +// Register adds the liveness and readiness routes to router. +func (h *Handler) Register(router RouteRegistrar) { + router.HandleFunc(http.MethodGet, "/healthz", h.Liveness) + router.HandleFunc(http.MethodGet, "/readyz", h.Readiness) +} + +// Liveness serves the process liveness probe. +func (h *Handler) Liveness(w http.ResponseWriter, _ *http.Request) { + h.writeStatus(w, http.StatusOK, "ok\n") +} + +// Readiness serves the database readiness probe. +func (h *Handler) Readiness(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), ReadinessTimeout) + defer cancel() + // Readiness deliberately reflects only the required database dependency. + // Identity-provider discovery is lazy, so an identity-provider outage does + // not remove otherwise healthy instances from service. + if h.readiness == nil || h.readiness.PingContext(ctx) != nil { + h.writeStatus(w, http.StatusServiceUnavailable, "not ready\n") + return + } + h.writeStatus(w, http.StatusOK, "ready\n") +} + +func (h *Handler) writeStatus(w http.ResponseWriter, status int, body string) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) +} diff --git a/internal/api/request_log.go b/internal/api/request_log.go index a483e23..42b250d 100644 --- a/internal/api/request_log.go +++ b/internal/api/request_log.go @@ -2,103 +2,30 @@ package api import ( "context" - "crypto/rand" - "encoding/hex" - "fmt" - "io" - "log/slog" "net/http" - "strings" - "time" -) - -type contextKey string -const requestIDKey contextKey = "request-id" + "stick/internal/api/requestlog" +) // RequestLogger assigns or propagates a safe request ID, exposes it in the // response, and logs only method/path/status/duration/request ID. Query // strings and headers are intentionally excluded because they may contain // credentials or other user data. func RequestLogger(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestID := validRequestID(r.Header.Get("X-Request-ID")) - if requestID == "" { - requestID = newRequestID() - } - w.Header().Set("X-Request-ID", requestID) - start := time.Now() - sw := &statusWriter{ResponseWriter: w} - r = r.WithContext(WithRequestID(r.Context(), requestID)) - next.ServeHTTP(sw, r) - status := sw.status - if status == 0 { - status = http.StatusOK - } - duration := time.Since(start) - slog.InfoContext(r.Context(), "http request", "method", r.Method, "path", r.URL.Path, "status", status, - "duration_ms", duration.Seconds()*1000, "request_id", requestID) - }) + return requestlog.RequestLogger(next) } // WithRequestID returns a context containing the request ID. func WithRequestID(ctx context.Context, requestID string) context.Context { - return context.WithValue(ctx, requestIDKey, requestID) + return requestlog.WithRequestID(ctx, requestID) } // RequestID returns the request ID assigned by the request logger, if any. func RequestID(ctx context.Context) string { - id, _ := ctx.Value(requestIDKey).(string) - return id + return requestlog.RequestID(ctx) } // LogError logs a request failure with its correlated request ID. func LogError(ctx context.Context, message, operation string, err error) { - slog.ErrorContext(ctx, message, "request_id", RequestID(ctx), "operation", operation, "error", err) -} - -type statusWriter struct { - http.ResponseWriter - status int - wroteHeader bool -} - -func (w *statusWriter) WriteHeader(status int) { - if w.wroteHeader { - return - } - w.status = status - w.wroteHeader = true - w.ResponseWriter.WriteHeader(status) -} - -func (w *statusWriter) Write(p []byte) (int, error) { - if !w.wroteHeader { - w.WriteHeader(http.StatusOK) - } - return w.ResponseWriter.Write(p) -} - -func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } - -func validRequestID(value string) string { - if len(value) == 0 || len(value) > 128 { - return "" - } - for _, r := range value { - if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && !strings.ContainsRune("._-", r) { - return "" - } - } - return value -} - -func newRequestID() string { - var b [16]byte - if _, err := io.ReadFull(rand.Reader, b[:]); err == nil { - return hex.EncodeToString(b[:]) - } - // crypto/rand failures should be exceptionally rare; a timestamp keeps - // request logging useful without exposing request data. - return fmt.Sprintf("fallback-%x", time.Now().UnixNano()) + requestlog.LogError(ctx, message, operation, err) } diff --git a/internal/api/requestlog/requestlog.go b/internal/api/requestlog/requestlog.go new file mode 100644 index 0000000..017173f --- /dev/null +++ b/internal/api/requestlog/requestlog.go @@ -0,0 +1,105 @@ +// Package requestlog provides request logging and request-ID context helpers. +package requestlog + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "io" + "log/slog" + "net/http" + "strings" + "time" +) + +type contextKey string + +const requestIDKey contextKey = "request-id" + +// RequestLogger assigns or propagates a safe request ID, exposes it in the +// response, and logs only method/path/status/duration/request ID. Query +// strings and headers are intentionally excluded because they may contain +// credentials or other user data. +func RequestLogger(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestID := validRequestID(r.Header.Get("X-Request-ID")) + if requestID == "" { + requestID = newRequestID() + } + w.Header().Set("X-Request-ID", requestID) + start := time.Now() + sw := &statusWriter{ResponseWriter: w} + r = r.WithContext(WithRequestID(r.Context(), requestID)) + next.ServeHTTP(sw, r) + status := sw.status + if status == 0 { + status = http.StatusOK + } + duration := time.Since(start) + slog.InfoContext(r.Context(), "http request", "method", r.Method, "path", r.URL.Path, "status", status, + "duration_ms", duration.Seconds()*1000, "request_id", requestID) + }) +} + +// WithRequestID returns a context containing the request ID. +func WithRequestID(ctx context.Context, requestID string) context.Context { + return context.WithValue(ctx, requestIDKey, requestID) +} + +// RequestID returns the request ID assigned by the request logger, if any. +func RequestID(ctx context.Context) string { + id, _ := ctx.Value(requestIDKey).(string) + return id +} + +// LogError logs a request failure with its correlated request ID. +func LogError(ctx context.Context, message, operation string, err error) { + slog.ErrorContext(ctx, message, "request_id", RequestID(ctx), "operation", operation, "error", err) +} + +type statusWriter struct { + http.ResponseWriter + status int + wroteHeader bool +} + +func (w *statusWriter) WriteHeader(status int) { + if w.wroteHeader { + return + } + w.status = status + w.wroteHeader = true + w.ResponseWriter.WriteHeader(status) +} + +func (w *statusWriter) Write(p []byte) (int, error) { + if !w.wroteHeader { + w.WriteHeader(http.StatusOK) + } + return w.ResponseWriter.Write(p) +} + +func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +func validRequestID(value string) string { + if len(value) == 0 || len(value) > 128 { + return "" + } + for _, r := range value { + if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && !strings.ContainsRune("._-", r) { + return "" + } + } + return value +} + +func newRequestID() string { + var b [16]byte + if _, err := io.ReadFull(rand.Reader, b[:]); err == nil { + return hex.EncodeToString(b[:]) + } + // crypto/rand failures should be exceptionally rare; a timestamp keeps + // request logging useful without exposing request data. + return fmt.Sprintf("fallback-%x", time.Now().UnixNano()) +} diff --git a/internal/api/server.go b/internal/api/server.go index 69e3c0f..64b7ed5 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -10,6 +10,8 @@ import ( "net/url" "time" + "stick/internal/api/health" + "stick/internal/api/sticks" "stick/internal/application" "stick/internal/auth" "stick/internal/publicurl" @@ -34,7 +36,7 @@ type Runner struct { // NewRunner builds the HTTP application and its dependency graph. // Listening is intentionally deferred to Run so startup failures are reported // through the runner lifecycle rather than escaping during HTTP composition. -func NewRunner(service *application.Service, readiness ReadinessChecker, options Options) (*Runner, error) { +func NewRunner(service *application.Service, readiness health.ReadinessChecker, options Options) (*Runner, error) { handler, err := newHandler(service, readiness, options) if err != nil { return nil, fmt.Errorf("HTTP server: %w", err) @@ -46,7 +48,7 @@ func NewRunner(service *application.Service, readiness ReadinessChecker, options } // newHandler builds the complete HTTP graph. -func newHandler(service *application.Service, readiness ReadinessChecker, options Options) (http.Handler, error) { +func newHandler(service *application.Service, readiness health.ReadinessChecker, options Options) (http.Handler, error) { publicURL, err := publicurl.Parse(options.PublicURL) if err != nil { return nil, fmt.Errorf("public URL: %w", err) @@ -57,11 +59,11 @@ func newHandler(service *application.Service, readiness ReadinessChecker, option } router := NewRouter(parsedPublicURL.Path) - healthHandler := NewHealth(readiness) - apiHandler := New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, publicURL, options.NotificationsEnabled) + healthHandler := health.New(readiness) + sticksHandler := sticks.New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, publicURL, options.NotificationsEnabled) healthHandler.Register(router) - apiHandler.Register(router) + sticksHandler.Register(router) router.SetNotFound(http.HandlerFunc(NotFound)) middlewares := Chain( diff --git a/internal/api/conditions.go b/internal/api/sticks/conditions.go similarity index 99% rename from internal/api/conditions.go rename to internal/api/sticks/conditions.go index 28db183..ed8ea82 100644 --- a/internal/api/conditions.go +++ b/internal/api/sticks/conditions.go @@ -1,4 +1,4 @@ -package api +package sticks import ( "errors" diff --git a/internal/api/sticks.go b/internal/api/sticks/endpoints.go similarity index 99% rename from internal/api/sticks.go rename to internal/api/sticks/endpoints.go index e29a3ac..522252a 100644 --- a/internal/api/sticks.go +++ b/internal/api/sticks/endpoints.go @@ -1,4 +1,4 @@ -package api +package sticks import ( "net/http" diff --git a/internal/api/sticks/handler.go b/internal/api/sticks/handler.go new file mode 100644 index 0000000..748c3c0 --- /dev/null +++ b/internal/api/sticks/handler.go @@ -0,0 +1,103 @@ +// Package sticks provides the authenticated Stick REST API route group. +package sticks + +import ( + "context" + "net/http" + "strings" + + "stick/internal/application" + "stick/internal/auth" + domain "stick/internal/core" +) + +const ( + apiPrefix = "/api/v1" + maxJSONBodyBytes = 1 << 20 + defaultHistoryLimit = 20 + maxHistoryLimit = 100 + maxHistoryOffset = 100_000 +) + +// RouteRegistrar is the part of the API router needed to register routes. +// Keeping the interface here avoids coupling route groups to the server's +// router implementation. +type RouteRegistrar interface { + HandleFunc(method, reference string, handler http.HandlerFunc, middlewares ...func(http.Handler) http.Handler) +} + +// Handler serves the authenticated Stick REST API. +type Handler struct { + service *application.Service + validator TokenValidator + admins map[string]struct{} + publicURL string + notificationsEnabled bool +} + +// TokenValidator authenticates one external bearer token. +type TokenValidator interface { + Validate(context.Context, string) (domain.Identity, error) +} + +// New returns a Stick API handler. +func New( + service *application.Service, + validator TokenValidator, + adminEmails []string, + publicURL string, + notificationsEnabled bool, +) *Handler { + return &Handler{ + service: service, + validator: validator, + admins: auth.AdminSet(adminEmails), + publicURL: publicURL, + notificationsEnabled: notificationsEnabled, + } +} + +// Register adds all Stick API routes to router. Authentication is applied to +// every route in this group. +func (h *Handler) Register(router RouteRegistrar) { + h.register(router, http.MethodGet, apiPrefix+"/sticks", h.listSticks) + h.register(router, http.MethodPost, apiPrefix+"/sticks", h.createStick) + h.register(router, http.MethodGet, apiPrefix+"/sticks/archived", h.listArchivedSticks) + h.register(router, http.MethodGet, apiPrefix+"/sticks/{id}", h.getStick) + h.register(router, http.MethodPatch, apiPrefix+"/sticks/{id}", h.renameStick) + h.register(router, http.MethodGet, apiPrefix+"/sticks/{id}/history", h.history) + h.register(router, http.MethodPost, apiPrefix+"/sticks/{id}/claim", h.claimStick) + h.register(router, http.MethodPost, apiPrefix+"/sticks/{id}/release", h.releaseStick) + h.register(router, http.MethodPost, apiPrefix+"/sticks/{id}/archive", h.archiveStick) + h.register(router, http.MethodPost, apiPrefix+"/sticks/{id}/unarchive", h.unarchiveStick) + if h.notificationsEnabled { + h.register(router, http.MethodPut, apiPrefix+"/sticks/{id}/subscription", h.subscribe) + h.register(router, http.MethodDelete, apiPrefix+"/sticks/{id}/subscription", h.unsubscribe) + h.register(router, http.MethodGet, apiPrefix+"/subscriptions", h.subscriptions) + } +} + +func (h *Handler) register(router RouteRegistrar, method, reference string, handler http.HandlerFunc) { + router.HandleFunc(method, reference, handler, h.authenticate) +} + +func (h *Handler) authenticate(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + parts := strings.Fields(r.Header.Get("Authorization")) + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { + unauthorized(w) + return + } + if h.validator == nil { + writeError(w, http.StatusInternalServerError, "internal server error") + return + } + identity, err := h.validator.Validate(r.Context(), parts[1]) + if err != nil { + unauthorized(w) + return + } + identity = auth.WithAdminStatus(identity, h.admins) + next.ServeHTTP(w, r.WithContext(auth.WithIdentity(r.Context(), identity))) + }) +} diff --git a/internal/api/responses.go b/internal/api/sticks/responses.go similarity index 98% rename from internal/api/responses.go rename to internal/api/sticks/responses.go index 2b912b5..00a6785 100644 --- a/internal/api/responses.go +++ b/internal/api/sticks/responses.go @@ -1,4 +1,4 @@ -package api +package sticks import ( "crypto/sha256" @@ -11,6 +11,7 @@ import ( "strings" "time" + "stick/internal/api/requestlog" "stick/internal/application" domain "stick/internal/core" ) @@ -109,7 +110,7 @@ func unauthorized(w http.ResponseWriter) { } func internalError(w http.ResponseWriter, r *http.Request, operation string, err error) { - LogError(r.Context(), "request failed", operation, err) + requestlog.LogError(r.Context(), "request failed", operation, err) writeError(w, http.StatusInternalServerError, "internal server error") } diff --git a/internal/api/subscriptions.go b/internal/api/sticks/subscriptions.go similarity index 98% rename from internal/api/subscriptions.go rename to internal/api/sticks/subscriptions.go index e333417..ee2d668 100644 --- a/internal/api/subscriptions.go +++ b/internal/api/sticks/subscriptions.go @@ -1,4 +1,4 @@ -package api +package sticks import ( "net/http" From b79ac86a54f317cb634b4980577742ed8131ed70 Mon Sep 17 00:00:00 2001 From: alxtr Date: Tue, 1 Sep 2026 00:53:51 +0000 Subject: [PATCH 07/14] good first pass --- cmd/stickd/main.go | 4 +- internal/api/handler.go | 39 ----- internal/api/health.go | 21 --- internal/api/health/handler.go | 11 +- .../handler_test.go} | 15 +- internal/api/request_log.go | 31 ---- internal/api/{ => server}/server.go | 14 +- internal/api/sticks/conditions.go | 31 +--- internal/api/sticks/endpoints.go | 39 ++--- internal/api/sticks/handler.go | 48 +++--- internal/api/{ => sticks}/handler_test.go | 13 +- internal/api/sticks/responses.go | 119 ++------------- internal/api/sticks/subscriptions.go | 9 +- internal/{api => web/httpx}/headers.go | 4 +- internal/{api => web/httpx}/middleware.go | 2 +- .../{api => web/httpx}/middleware_test.go | 10 +- internal/web/httpx/not_found.go | 8 + .../httpx/request_log.go} | 3 +- .../{api => web/httpx}/request_log_test.go | 18 +-- internal/web/httpx/responses.go | 139 ++++++++++++++++++ internal/{api => web/httpx}/router.go | 4 +- internal/{api => web/httpx}/router_test.go | 16 +- 22 files changed, 267 insertions(+), 331 deletions(-) delete mode 100644 internal/api/handler.go delete mode 100644 internal/api/health.go rename internal/api/{health_test.go => health/handler_test.go} (86%) delete mode 100644 internal/api/request_log.go rename internal/api/{ => server}/server.go (93%) rename internal/api/{ => sticks}/handler_test.go (95%) rename internal/{api => web/httpx}/headers.go (75%) rename internal/{api => web/httpx}/middleware.go (96%) rename internal/{api => web/httpx}/middleware_test.go (87%) create mode 100644 internal/web/httpx/not_found.go rename internal/{api/requestlog/requestlog.go => web/httpx/request_log.go} (96%) rename internal/{api => web/httpx}/request_log_test.go (79%) create mode 100644 internal/web/httpx/responses.go rename internal/{api => web/httpx}/router.go (96%) rename internal/{api => web/httpx}/router_test.go (94%) diff --git a/cmd/stickd/main.go b/cmd/stickd/main.go index f697f6b..d089842 100644 --- a/cmd/stickd/main.go +++ b/cmd/stickd/main.go @@ -20,7 +20,7 @@ import ( "stick/internal/adapters/persistence/mongodb" "stick/internal/adapters/persistence/postgres" "stick/internal/adapters/persistence/sqlite" - "stick/internal/api" + "stick/internal/api/server" "stick/internal/application" "stick/internal/auth" "stick/internal/config" @@ -89,7 +89,7 @@ func mainContext(parent context.Context, args []string) (err error) { }() service := application.NewService(store) - serverRunner, err := api.NewRunner(service, store, api.Options{ + serverRunner, err := server.NewRunner(service, store, server.Options{ PublicURL: cfg.Server.PublicURL, ListenAddr: cfg.Server.ListenAddr, JWT: auth.JWTConfig{Endpoint: cfg.Auth.IDPEndpoint, Audience: cfg.Auth.Audience, Scope: cfg.Auth.Scope}, diff --git a/internal/api/handler.go b/internal/api/handler.go deleted file mode 100644 index 77bc972..0000000 --- a/internal/api/handler.go +++ /dev/null @@ -1,39 +0,0 @@ -// Package api provides the HTTP server and routing infrastructure for Stick. -package api - -import ( - "encoding/json" - "net/http" - - "stick/internal/api/sticks" - "stick/internal/application" -) - -// Handler is kept as an alias for compatibility with callers that used the -// original root API package. New code should use api/sticks directly. -type Handler = sticks.Handler - -// TokenValidator is the validator used by the Stick route group. -type TokenValidator = sticks.TokenValidator - -// New returns a Stick API handler. New code should use sticks.New directly. -func New( - service *application.Service, - validator TokenValidator, - adminEmails []string, - publicURL string, - notificationsEnabled bool, -) *Handler { - return sticks.New(service, validator, adminEmails, publicURL, notificationsEnabled) -} - -// NotFound writes the JSON response used for unknown API routes. -func NotFound(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(http.StatusNotFound) - data, _ := json.Marshal(struct { - Error string `json:"error"` - }{Error: "not found"}) - _, _ = w.Write(data) -} diff --git a/internal/api/health.go b/internal/api/health.go deleted file mode 100644 index 8654c23..0000000 --- a/internal/api/health.go +++ /dev/null @@ -1,21 +0,0 @@ -package api - -import ( - "stick/internal/api/health" -) - -// ReadinessChecker is the dependency used by the readiness probe. -type ReadinessChecker = health.ReadinessChecker - -// healthHandler is kept as an alias for compatibility with the original root -// API package. New code should use health.Handler directly. -type healthHandler = health.Handler - -// readinessTimeout preserves the original package-local test seam. -const readinessTimeout = health.ReadinessTimeout - -// NewHealth returns a health handler backed by readiness. New code should use -// health.New directly. -func NewHealth(readiness ReadinessChecker) *healthHandler { - return health.New(readiness) -} diff --git a/internal/api/health/handler.go b/internal/api/health/handler.go index cbb8062..c19565a 100644 --- a/internal/api/health/handler.go +++ b/internal/api/health/handler.go @@ -5,6 +5,8 @@ import ( "context" "net/http" "time" + + "stick/internal/web/httpx" ) const ( @@ -13,13 +15,6 @@ const ( ReadinessTimeout = 2 * time.Second ) -// RouteRegistrar is the part of the API router needed to register routes. -// Keeping the interface here avoids coupling route groups to the server's -// router implementation. -type RouteRegistrar interface { - HandleFunc(method, reference string, handler http.HandlerFunc, middlewares ...func(http.Handler) http.Handler) -} - // ReadinessChecker is the dependency used by the readiness probe. type ReadinessChecker interface { PingContext(context.Context) error @@ -37,7 +32,7 @@ func New(readiness ReadinessChecker) *Handler { } // Register adds the liveness and readiness routes to router. -func (h *Handler) Register(router RouteRegistrar) { +func (h *Handler) Register(router *httpx.Router) { router.HandleFunc(http.MethodGet, "/healthz", h.Liveness) router.HandleFunc(http.MethodGet, "/readyz", h.Readiness) } diff --git a/internal/api/health_test.go b/internal/api/health/handler_test.go similarity index 86% rename from internal/api/health_test.go rename to internal/api/health/handler_test.go index 149723d..ff94ce8 100644 --- a/internal/api/health_test.go +++ b/internal/api/health/handler_test.go @@ -1,4 +1,4 @@ -package api +package health_test import ( "context" @@ -7,6 +7,9 @@ import ( "net/http/httptest" "testing" "time" + + "stick/internal/api/health" + "stick/internal/web/httpx" ) type healthDB struct { @@ -33,12 +36,12 @@ func TestHealthRoutes(t *testing.T) { {name: "missing dependency", path: "/readyz", wantStatus: http.StatusServiceUnavailable, wantBody: "not ready\n"}, } { t.Run(test.name, func(t *testing.T) { - router := NewRouter("/stick") - var readiness ReadinessChecker + router := httpx.NewRouter("/stick") + var readiness health.ReadinessChecker if test.readiness != nil { readiness = test.readiness } - NewHealth(readiness).Register(router) + health.New(readiness).Register(router) recorder := httptest.NewRecorder() router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/stick"+test.path, nil)) @@ -53,8 +56,8 @@ func TestHealthRoutes(t *testing.T) { } if test.path == "/readyz" && test.readiness != nil { remaining := time.Until(test.readiness.deadline) - if remaining <= 0 || remaining > readinessTimeout { - t.Errorf("readiness deadline remaining = %s, want (0, %s]", remaining, readinessTimeout) + if remaining <= 0 || remaining > health.ReadinessTimeout { + t.Errorf("readiness deadline remaining = %s, want (0, %s]", remaining, health.ReadinessTimeout) } } }) diff --git a/internal/api/request_log.go b/internal/api/request_log.go deleted file mode 100644 index 42b250d..0000000 --- a/internal/api/request_log.go +++ /dev/null @@ -1,31 +0,0 @@ -package api - -import ( - "context" - "net/http" - - "stick/internal/api/requestlog" -) - -// RequestLogger assigns or propagates a safe request ID, exposes it in the -// response, and logs only method/path/status/duration/request ID. Query -// strings and headers are intentionally excluded because they may contain -// credentials or other user data. -func RequestLogger(next http.Handler) http.Handler { - return requestlog.RequestLogger(next) -} - -// WithRequestID returns a context containing the request ID. -func WithRequestID(ctx context.Context, requestID string) context.Context { - return requestlog.WithRequestID(ctx, requestID) -} - -// RequestID returns the request ID assigned by the request logger, if any. -func RequestID(ctx context.Context) string { - return requestlog.RequestID(ctx) -} - -// LogError logs a request failure with its correlated request ID. -func LogError(ctx context.Context, message, operation string, err error) { - requestlog.LogError(ctx, message, operation, err) -} diff --git a/internal/api/server.go b/internal/api/server/server.go similarity index 93% rename from internal/api/server.go rename to internal/api/server/server.go index 64b7ed5..ef74b2c 100644 --- a/internal/api/server.go +++ b/internal/api/server/server.go @@ -1,4 +1,5 @@ -package api +// Package server composes the HTTP application and owns its lifecycle. +package server import ( "context" @@ -15,6 +16,7 @@ import ( "stick/internal/application" "stick/internal/auth" "stick/internal/publicurl" + "stick/internal/web/httpx" ) // Options contains the settings required to build the HTTP server. @@ -58,17 +60,17 @@ func newHandler(service *application.Service, readiness health.ReadinessChecker, return nil, fmt.Errorf("public URL: %w", err) } - router := NewRouter(parsedPublicURL.Path) + router := httpx.NewRouter(parsedPublicURL.Path) healthHandler := health.New(readiness) sticksHandler := sticks.New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, publicURL, options.NotificationsEnabled) healthHandler.Register(router) sticksHandler.Register(router) - router.SetNotFound(http.HandlerFunc(NotFound)) + router.SetNotFound(http.HandlerFunc(httpx.NotFound)) - middlewares := Chain( - RequestLogger, - Headers) + middlewares := httpx.Chain( + httpx.RequestLogger, + httpx.Headers) return middlewares(router), nil } diff --git a/internal/api/sticks/conditions.go b/internal/api/sticks/conditions.go index ed8ea82..9331185 100644 --- a/internal/api/sticks/conditions.go +++ b/internal/api/sticks/conditions.go @@ -7,17 +7,18 @@ import ( "strings" "stick/internal/auth" + "stick/internal/web/httpx" ) func (h *Handler) expectedVersion(w http.ResponseWriter, r *http.Request, id string) (int64, bool) { - header := headerValue(r, "If-Match") + header := httpx.HeaderValue(r, "If-Match") if strings.TrimSpace(header) == "" { - writeError(w, http.StatusPreconditionRequired, "If-Match header is required") + httpx.WriteError(w, http.StatusPreconditionRequired, "If-Match header is required") return 0, false } tags, wildcard, err := parseIfMatch(header) if err != nil { - writeError(w, http.StatusBadRequest, "invalid If-Match header") + httpx.WriteError(w, http.StatusBadRequest, "invalid If-Match header") return 0, false } if len(tags) == 1 && !wildcard { @@ -40,7 +41,7 @@ func (h *Handler) expectedVersion(w http.ResponseWriter, r *http.Request, id str } } if !matched { - writeError(w, http.StatusPreconditionFailed, "precondition failed") + httpx.WriteError(w, http.StatusPreconditionFailed, "precondition failed") return 0, false } } @@ -55,14 +56,14 @@ func historyPagination(w http.ResponseWriter, r *http.Request) (int, int, bool) if raw := query.Get("limit"); raw != "" { limit, err = strconv.Atoi(raw) if err != nil || limit < 1 || limit > maxHistoryLimit { - writeError(w, http.StatusBadRequest, "invalid history limit") + httpx.WriteError(w, http.StatusBadRequest, "invalid history limit") return 0, 0, false } } if raw := query.Get("offset"); raw != "" { offset, err = strconv.Atoi(raw) if err != nil || offset < 0 || offset > maxHistoryOffset { - writeError(w, http.StatusBadRequest, "invalid history offset") + httpx.WriteError(w, http.StatusBadRequest, "invalid history offset") return 0, 0, false } } @@ -85,7 +86,7 @@ func parseIfMatch(value string) ([]int64, bool, error) { return nil, false, errors.New("invalid entity tag") } version, err := strconv.ParseInt(part[1:len(part)-1], 10, 64) - if err != nil || version < 1 || etag(version) != part { + if err != nil || version < 1 || httpx.ETag(version) != part { return nil, false, errors.New("invalid entity tag") } tags = append(tags, version) @@ -95,19 +96,3 @@ func parseIfMatch(value string) ([]int64, bool, error) { } return tags, false, nil } - -func ifNoneMatch(header, current string) bool { - for _, part := range strings.Split(header, ",") { - part = strings.TrimSpace(part) - if part == "*" { - return true - } - if strings.HasPrefix(part, "W/") { - part = strings.TrimSpace(strings.TrimPrefix(part, "W/")) - } - if part == current { - return true - } - } - return false -} diff --git a/internal/api/sticks/endpoints.go b/internal/api/sticks/endpoints.go index 522252a..f2364bf 100644 --- a/internal/api/sticks/endpoints.go +++ b/internal/api/sticks/endpoints.go @@ -4,21 +4,22 @@ import ( "net/http" "stick/internal/auth" + "stick/internal/web/httpx" ) func (h *Handler) listSticks(w http.ResponseWriter, r *http.Request) { sticks, err := h.service.ListSticks(r.Context()) if err != nil { - internalError(w, r, "list sticks", err) + httpx.InternalError(w, r, "list sticks", err) return } - writeCollection(w, r, sticksToJSON(sticks)) + httpx.WriteCollection(w, r, sticksToJSON(sticks)) } func (h *Handler) listArchivedSticks(w http.ResponseWriter, r *http.Request) { identity := auth.IdentityFromContext(r.Context()) if !identity.IsAdmin { - writeError(w, http.StatusForbidden, "forbidden") + httpx.WriteError(w, http.StatusForbidden, "forbidden") return } sticks, err := h.service.ListArchivedSticks(r.Context(), identity) @@ -26,7 +27,7 @@ func (h *Handler) listArchivedSticks(w http.ResponseWriter, r *http.Request) { handleError(w, r, "list archived sticks", err) return } - writeCollection(w, r, sticksToJSON(sticks)) + httpx.WriteCollection(w, r, sticksToJSON(sticks)) } func (h *Handler) getStick(w http.ResponseWriter, r *http.Request) { @@ -35,23 +36,23 @@ func (h *Handler) getStick(w http.ResponseWriter, r *http.Request) { handleError(w, r, "get stick", err) return } - setETag(w, stick.Version) - if ifNoneMatch(headerValue(r, "If-None-Match"), etag(stick.Version)) { - notModified(w) + httpx.SetETag(w, stick.Version) + if httpx.IfNoneMatch(httpx.HeaderValue(r, "If-None-Match"), httpx.ETag(stick.Version)) { + httpx.NotModified(w) return } - writeJSON(w, http.StatusOK, stickToJSON(stick)) + httpx.WriteJSON(w, http.StatusOK, stickToJSON(stick)) } func (h *Handler) createStick(w http.ResponseWriter, r *http.Request) { if !auth.IdentityFromContext(r.Context()).IsAdmin { - writeError(w, http.StatusForbidden, "forbidden") + httpx.WriteError(w, http.StatusForbidden, "forbidden") return } var request struct { Name string `json:"name"` } - if !decodeJSON(w, r, &request) { + if !httpx.DecodeJSON(w, r, &request) { return } stick, err := h.service.CreateStick(r.Context(), auth.IdentityFromContext(r.Context()), request.Name) @@ -59,20 +60,20 @@ func (h *Handler) createStick(w http.ResponseWriter, r *http.Request) { handleError(w, r, "create stick", err) return } - setETag(w, stick.Version) + httpx.SetETag(w, stick.Version) w.Header().Set("Location", h.publicURL+apiPrefix+"/sticks/"+stick.ID) - writeJSON(w, http.StatusCreated, stickToJSON(stick)) + httpx.WriteJSON(w, http.StatusCreated, stickToJSON(stick)) } func (h *Handler) renameStick(w http.ResponseWriter, r *http.Request) { if !auth.IdentityFromContext(r.Context()).IsAdmin { - writeError(w, http.StatusForbidden, "forbidden") + httpx.WriteError(w, http.StatusForbidden, "forbidden") return } var request struct { Name string `json:"name"` } - if !decodeJSON(w, r, &request) { + if !httpx.DecodeJSON(w, r, &request) { return } version, ok := h.expectedVersion(w, r, r.PathValue("id")) @@ -89,7 +90,7 @@ func (h *Handler) renameStick(w http.ResponseWriter, r *http.Request) { func (h *Handler) archiveStick(w http.ResponseWriter, r *http.Request) { if !auth.IdentityFromContext(r.Context()).IsAdmin { - writeError(w, http.StatusForbidden, "forbidden") + httpx.WriteError(w, http.StatusForbidden, "forbidden") return } version, ok := h.expectedVersion(w, r, r.PathValue("id")) @@ -106,7 +107,7 @@ func (h *Handler) archiveStick(w http.ResponseWriter, r *http.Request) { func (h *Handler) unarchiveStick(w http.ResponseWriter, r *http.Request) { if !auth.IdentityFromContext(r.Context()).IsAdmin { - writeError(w, http.StatusForbidden, "forbidden") + httpx.WriteError(w, http.StatusForbidden, "forbidden") return } version, ok := h.expectedVersion(w, r, r.PathValue("id")) @@ -125,7 +126,7 @@ func (h *Handler) claimStick(w http.ResponseWriter, r *http.Request) { var request struct { Reason string `json:"reason"` } - if !decodeJSON(w, r, &request) { + if !httpx.DecodeJSON(w, r, &request) { return } version, ok := h.expectedVersion(w, r, r.PathValue("id")) @@ -161,7 +162,7 @@ func (h *Handler) history(w http.ResponseWriter, r *http.Request) { handleError(w, r, "get stick history", err) return } - setETag(w, stick.Version) + httpx.SetETag(w, stick.Version) limit, offset, ok := historyPagination(w, r) if !ok { return @@ -182,5 +183,5 @@ func (h *Handler) history(w http.ResponseWriter, r *http.Request) { Limit: limit, Offset: offset, } - writeConditionalJSON(w, r, response) + httpx.WriteConditionalJSON(w, r, response) } diff --git a/internal/api/sticks/handler.go b/internal/api/sticks/handler.go index 748c3c0..5008d4d 100644 --- a/internal/api/sticks/handler.go +++ b/internal/api/sticks/handler.go @@ -9,23 +9,16 @@ import ( "stick/internal/application" "stick/internal/auth" domain "stick/internal/core" + "stick/internal/web/httpx" ) const ( apiPrefix = "/api/v1" - maxJSONBodyBytes = 1 << 20 defaultHistoryLimit = 20 maxHistoryLimit = 100 maxHistoryOffset = 100_000 ) -// RouteRegistrar is the part of the API router needed to register routes. -// Keeping the interface here avoids coupling route groups to the server's -// router implementation. -type RouteRegistrar interface { - HandleFunc(method, reference string, handler http.HandlerFunc, middlewares ...func(http.Handler) http.Handler) -} - // Handler serves the authenticated Stick REST API. type Handler struct { service *application.Service @@ -59,42 +52,39 @@ func New( // Register adds all Stick API routes to router. Authentication is applied to // every route in this group. -func (h *Handler) Register(router RouteRegistrar) { - h.register(router, http.MethodGet, apiPrefix+"/sticks", h.listSticks) - h.register(router, http.MethodPost, apiPrefix+"/sticks", h.createStick) - h.register(router, http.MethodGet, apiPrefix+"/sticks/archived", h.listArchivedSticks) - h.register(router, http.MethodGet, apiPrefix+"/sticks/{id}", h.getStick) - h.register(router, http.MethodPatch, apiPrefix+"/sticks/{id}", h.renameStick) - h.register(router, http.MethodGet, apiPrefix+"/sticks/{id}/history", h.history) - h.register(router, http.MethodPost, apiPrefix+"/sticks/{id}/claim", h.claimStick) - h.register(router, http.MethodPost, apiPrefix+"/sticks/{id}/release", h.releaseStick) - h.register(router, http.MethodPost, apiPrefix+"/sticks/{id}/archive", h.archiveStick) - h.register(router, http.MethodPost, apiPrefix+"/sticks/{id}/unarchive", h.unarchiveStick) +func (h *Handler) Register(router *httpx.Router) { + protected := router.With(h.authenticate) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks", h.listSticks) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks", h.createStick) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/archived", h.listArchivedSticks) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}", h.getStick) + protected.HandleFunc(http.MethodPatch, apiPrefix+"/sticks/{id}", h.renameStick) + protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}/history", h.history) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/claim", h.claimStick) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/release", h.releaseStick) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/archive", h.archiveStick) + protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/unarchive", h.unarchiveStick) if h.notificationsEnabled { - h.register(router, http.MethodPut, apiPrefix+"/sticks/{id}/subscription", h.subscribe) - h.register(router, http.MethodDelete, apiPrefix+"/sticks/{id}/subscription", h.unsubscribe) - h.register(router, http.MethodGet, apiPrefix+"/subscriptions", h.subscriptions) + protected.HandleFunc(http.MethodPut, apiPrefix+"/sticks/{id}/subscription", h.subscribe) + protected.HandleFunc(http.MethodDelete, apiPrefix+"/sticks/{id}/subscription", h.unsubscribe) + protected.HandleFunc(http.MethodGet, apiPrefix+"/subscriptions", h.subscriptions) } } -func (h *Handler) register(router RouteRegistrar, method, reference string, handler http.HandlerFunc) { - router.HandleFunc(method, reference, handler, h.authenticate) -} - func (h *Handler) authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { parts := strings.Fields(r.Header.Get("Authorization")) if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { - unauthorized(w) + httpx.Unauthorized(w) return } if h.validator == nil { - writeError(w, http.StatusInternalServerError, "internal server error") + httpx.WriteError(w, http.StatusInternalServerError, "internal server error") return } identity, err := h.validator.Validate(r.Context(), parts[1]) if err != nil { - unauthorized(w) + httpx.Unauthorized(w) return } identity = auth.WithAdminStatus(identity, h.admins) diff --git a/internal/api/handler_test.go b/internal/api/sticks/handler_test.go similarity index 95% rename from internal/api/handler_test.go rename to internal/api/sticks/handler_test.go index 875e3c7..c6855a9 100644 --- a/internal/api/handler_test.go +++ b/internal/api/sticks/handler_test.go @@ -1,4 +1,4 @@ -package api_test +package sticks_test import ( "context" @@ -11,9 +11,10 @@ import ( "testing" "stick/internal/adapters/persistence/sqlite" - "stick/internal/api" + "stick/internal/api/sticks" "stick/internal/application" domain "stick/internal/core" + "stick/internal/web/httpx" ) type tokenValidator map[string]domain.Identity @@ -35,13 +36,13 @@ func newTestHandler(t *testing.T) http.Handler { t.Cleanup(func() { _ = store.Close() }) publicURL := "http://localhost:8080" admin := domain.Identity{Sub: "admin", Name: "Admin", Email: "admin@example.com", EmailVerified: true} - handler := api.New(application.NewService(store), tokenValidator{ + handler := sticks.New(application.NewService(store), tokenValidator{ "admin-token": admin, "user-token": {Sub: "user", Name: "User", Email: "user@example.com", EmailVerified: true}, }, []string{"admin@example.com"}, publicURL, true) - router := api.NewRouter("") + router := httpx.NewRouter("") handler.Register(router) - router.SetNotFound(http.HandlerFunc(api.NotFound)) + router.SetNotFound(http.HandlerFunc(httpx.NotFound)) return router } @@ -147,4 +148,4 @@ func TestAPIMapsAuthorizationAndValidationErrors(t *testing.T) { } } -var _ api.TokenValidator = tokenValidator{} +var _ sticks.TokenValidator = tokenValidator{} diff --git a/internal/api/sticks/responses.go b/internal/api/sticks/responses.go index 00a6785..2074ba6 100644 --- a/internal/api/sticks/responses.go +++ b/internal/api/sticks/responses.go @@ -1,137 +1,38 @@ package sticks import ( - "crypto/sha256" - "encoding/hex" - "encoding/json" "errors" - "io" "net/http" - "strconv" - "strings" "time" - "stick/internal/api/requestlog" "stick/internal/application" domain "stick/internal/core" + "stick/internal/web/httpx" ) func writeStick(w http.ResponseWriter, stick domain.Stick) { - setETag(w, stick.Version) - writeJSON(w, http.StatusOK, stickToJSON(stick)) -} - -func writeCollection(w http.ResponseWriter, r *http.Request, value any) { - data, err := json.Marshal(value) - if err != nil { - writeError(w, http.StatusInternalServerError, "internal server error") - return - } - sum := sha256.Sum256(data) - collectionETag := `"` + hex.EncodeToString(sum[:]) + `"` - w.Header().Set("ETag", collectionETag) - if ifNoneMatch(headerValue(r, "If-None-Match"), collectionETag) { - notModified(w) - return - } - writeData(w, http.StatusOK, data) -} - -func writeConditionalJSON(w http.ResponseWriter, r *http.Request, value any) { - data, err := json.Marshal(value) - if err != nil { - writeError(w, http.StatusInternalServerError, "internal server error") - return - } - sum := sha256.Sum256(data) - representationETag := `"` + hex.EncodeToString(sum[:]) + `"` - w.Header().Set("ETag", representationETag) - if ifNoneMatch(headerValue(r, "If-None-Match"), representationETag) { - notModified(w) - return - } - writeData(w, http.StatusOK, data) -} - -func headerValue(r *http.Request, name string) string { - return strings.Join(r.Header.Values(name), ",") -} - -func writeJSON(w http.ResponseWriter, status int, value any) { - data, err := json.Marshal(value) - if err != nil { - writeError(w, http.StatusInternalServerError, "internal server error") - return - } - writeData(w, status, data) -} - -func writeData(w http.ResponseWriter, status int, data []byte) { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(status) - _, _ = w.Write(data) -} - -func notModified(w http.ResponseWriter) { - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(http.StatusNotModified) -} - -func writeError(w http.ResponseWriter, status int, message string) { - writeJSON(w, status, struct { - Error string `json:"error"` - }{Error: message}) -} - -func setETag(w http.ResponseWriter, version int64) { w.Header().Set("ETag", etag(version)) } - -func etag(version int64) string { return `"` + strconv.FormatInt(version, 10) + `"` } - -func decodeJSON(w http.ResponseWriter, r *http.Request, destination any) bool { - r.Body = http.MaxBytesReader(w, r.Body, maxJSONBodyBytes) - decoder := json.NewDecoder(r.Body) - decoder.DisallowUnknownFields() - if err := decoder.Decode(destination); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return false - } - var extra any - if err := decoder.Decode(&extra); err != io.EOF { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return false - } - return true -} - -func unauthorized(w http.ResponseWriter) { - w.Header().Set("WWW-Authenticate", `Bearer`) - writeError(w, http.StatusUnauthorized, "unauthorized") -} - -func internalError(w http.ResponseWriter, r *http.Request, operation string, err error) { - requestlog.LogError(r.Context(), "request failed", operation, err) - writeError(w, http.StatusInternalServerError, "internal server error") + httpx.SetETag(w, stick.Version) + httpx.WriteJSON(w, http.StatusOK, stickToJSON(stick)) } func handleError(w http.ResponseWriter, r *http.Request, operation string, err error) { switch { case errors.Is(err, application.ErrNotFound): - writeError(w, http.StatusNotFound, "not found") + httpx.WriteError(w, http.StatusNotFound, "not found") case errors.Is(err, application.ErrForbidden), errors.Is(err, domain.ErrNotHolder): - writeError(w, http.StatusForbidden, "forbidden") + httpx.WriteError(w, http.StatusForbidden, "forbidden") case errors.Is(err, application.ErrVersionConflict): - writeError(w, http.StatusPreconditionFailed, "precondition failed") + httpx.WriteError(w, http.StatusPreconditionFailed, "precondition failed") case errors.Is(err, application.ErrAlreadyExists): - writeError(w, http.StatusConflict, "conflict") + httpx.WriteError(w, http.StatusConflict, "conflict") case errors.Is(err, domain.ErrInvalidStickName), errors.Is(err, domain.ErrInvalidClaimReason): - writeError(w, http.StatusUnprocessableEntity, "invalid request") + httpx.WriteError(w, http.StatusUnprocessableEntity, "invalid request") case errors.Is(err, domain.ErrAlreadyHeld), errors.Is(err, domain.ErrAlreadyArchived), errors.Is(err, domain.ErrNotArchived), errors.Is(err, domain.ErrHeld), errors.Is(err, domain.ErrVersionExhausted): - writeError(w, http.StatusConflict, "conflict") + httpx.WriteError(w, http.StatusConflict, "conflict") default: - internalError(w, r, operation, err) + httpx.InternalError(w, r, operation, err) } } diff --git a/internal/api/sticks/subscriptions.go b/internal/api/sticks/subscriptions.go index ee2d668..7ea792f 100644 --- a/internal/api/sticks/subscriptions.go +++ b/internal/api/sticks/subscriptions.go @@ -4,6 +4,7 @@ import ( "net/http" "stick/internal/auth" + "stick/internal/web/httpx" ) func (h *Handler) subscribe(w http.ResponseWriter, r *http.Request) { @@ -15,7 +16,7 @@ func (h *Handler) subscribe(w http.ResponseWriter, r *http.Request) { handleError(w, r, "subscribe to stick", err) return } - setETag(w, version) + httpx.SetETag(w, version) w.WriteHeader(http.StatusNoContent) } @@ -28,18 +29,18 @@ func (h *Handler) unsubscribe(w http.ResponseWriter, r *http.Request) { handleError(w, r, "unsubscribe from stick", err) return } - setETag(w, version) + httpx.SetETag(w, version) w.WriteHeader(http.StatusNoContent) } func (h *Handler) subscriptions(w http.ResponseWriter, r *http.Request) { ids, err := h.service.SubscribedStickIDs(r.Context(), auth.IdentityFromContext(r.Context())) if err != nil { - internalError(w, r, "list subscriptions", err) + httpx.InternalError(w, r, "list subscriptions", err) return } if ids == nil { ids = []string{} } - writeCollection(w, r, ids) + httpx.WriteCollection(w, r, ids) } diff --git a/internal/api/headers.go b/internal/web/httpx/headers.go similarity index 75% rename from internal/api/headers.go rename to internal/web/httpx/headers.go index a9300c6..5b84e3d 100644 --- a/internal/api/headers.go +++ b/internal/web/httpx/headers.go @@ -1,8 +1,8 @@ -package api +package httpx import "net/http" -// Headers adds response headers useful for a JSON API. +// Headers adds response headers useful for an HTTP API. func Headers(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") diff --git a/internal/api/middleware.go b/internal/web/httpx/middleware.go similarity index 96% rename from internal/api/middleware.go rename to internal/web/httpx/middleware.go index e84b038..8436753 100644 --- a/internal/api/middleware.go +++ b/internal/web/httpx/middleware.go @@ -1,4 +1,4 @@ -package api +package httpx import "net/http" diff --git a/internal/api/middleware_test.go b/internal/web/httpx/middleware_test.go similarity index 87% rename from internal/api/middleware_test.go rename to internal/web/httpx/middleware_test.go index 2170982..18f4344 100644 --- a/internal/api/middleware_test.go +++ b/internal/web/httpx/middleware_test.go @@ -1,4 +1,4 @@ -package api_test +package httpx_test import ( "log/slog" @@ -7,12 +7,12 @@ import ( "strings" "testing" - "stick/internal/api" + "stick/internal/web/httpx" ) func TestChainAppliesMiddlewareInOrder(t *testing.T) { var calls []string - record := func(name string) api.Middleware { + record := func(name string) httpx.Middleware { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { calls = append(calls, name+" before") @@ -25,7 +25,7 @@ func TestChainAppliesMiddlewareInOrder(t *testing.T) { calls = append(calls, "handler") }) - stack := api.Chain(record("first"), record("second")) + stack := httpx.Chain(record("first"), record("second")) stack(final).ServeHTTP( httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil), @@ -42,7 +42,7 @@ func TestRequestLoggerAddsRequestIDAndLogs(t *testing.T) { previous := slog.Default() slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) t.Cleanup(func() { slog.SetDefault(previous) }) - root := api.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + root := httpx.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })) recorder := httptest.NewRecorder() diff --git a/internal/web/httpx/not_found.go b/internal/web/httpx/not_found.go new file mode 100644 index 0000000..c9b17b3 --- /dev/null +++ b/internal/web/httpx/not_found.go @@ -0,0 +1,8 @@ +package httpx + +import "net/http" + +// NotFound writes the standard JSON response used for unknown routes. +func NotFound(w http.ResponseWriter, _ *http.Request) { + WriteError(w, http.StatusNotFound, "not found") +} diff --git a/internal/api/requestlog/requestlog.go b/internal/web/httpx/request_log.go similarity index 96% rename from internal/api/requestlog/requestlog.go rename to internal/web/httpx/request_log.go index 017173f..1191189 100644 --- a/internal/api/requestlog/requestlog.go +++ b/internal/web/httpx/request_log.go @@ -1,5 +1,4 @@ -// Package requestlog provides request logging and request-ID context helpers. -package requestlog +package httpx import ( "context" diff --git a/internal/api/request_log_test.go b/internal/web/httpx/request_log_test.go similarity index 79% rename from internal/api/request_log_test.go rename to internal/web/httpx/request_log_test.go index a9d060c..74e7e8a 100644 --- a/internal/api/request_log_test.go +++ b/internal/web/httpx/request_log_test.go @@ -1,4 +1,4 @@ -package api_test +package httpx_test import ( "bytes" @@ -11,12 +11,12 @@ import ( "strings" "testing" - "stick/internal/api" + "stick/internal/web/httpx" ) func TestRequestIDContext(t *testing.T) { - ctx := api.WithRequestID(context.Background(), "request-42") - if got := api.RequestID(ctx); got != "request-42" { + ctx := httpx.WithRequestID(context.Background(), "request-42") + if got := httpx.RequestID(ctx); got != "request-42" { t.Errorf("request ID = %q, want request-42", got) } } @@ -26,8 +26,8 @@ func TestRequestLoggerAssignsAndPropagatesID(t *testing.T) { previous := slog.Default() slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) t.Cleanup(func() { slog.SetDefault(previous) }) - wrapped := api.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if api.RequestID(r.Context()) == "" { + wrapped := httpx.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if httpx.RequestID(r.Context()) == "" { t.Error("request ID missing from context") } w.WriteHeader(http.StatusTeapot) @@ -52,7 +52,7 @@ func TestRequestLoggerAssignsAndPropagatesID(t *testing.T) { } func TestRequestLoggerPropagatesValidIncomingID(t *testing.T) { - wrapped := api.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + wrapped := httpx.RequestLogger(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })) request := httptest.NewRequest(http.MethodGet, "/", nil) @@ -69,9 +69,9 @@ func TestLogErrorLogsCorrelatedFailure(t *testing.T) { previous := slog.Default() slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) t.Cleanup(func() { slog.SetDefault(previous) }) - ctx := api.WithRequestID(t.Context(), "request-42") + ctx := httpx.WithRequestID(t.Context(), "request-42") - api.LogError(ctx, "request failed", "perform operation", errors.New("failed")) + httpx.LogError(ctx, "request failed", "perform operation", errors.New("failed")) for _, want := range []string{`"msg":"request failed"`, `"request_id":"request-42"`, `"operation":"perform operation"`, `"error":"failed"`} { if !strings.Contains(logs.String(), want) { diff --git a/internal/web/httpx/responses.go b/internal/web/httpx/responses.go new file mode 100644 index 0000000..63c21a0 --- /dev/null +++ b/internal/web/httpx/responses.go @@ -0,0 +1,139 @@ +package httpx + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "strconv" + "strings" +) + +const maxJSONBodyBytes = 1 << 20 + +// WriteCollection writes a JSON collection with a content-derived ETag and +// supports conditional requests. +func WriteCollection(w http.ResponseWriter, r *http.Request, value any) { + data, err := json.Marshal(value) + if err != nil { + WriteError(w, http.StatusInternalServerError, "internal server error") + return + } + sum := sha256.Sum256(data) + collectionETag := `"` + hex.EncodeToString(sum[:]) + `"` + w.Header().Set("ETag", collectionETag) + if IfNoneMatch(HeaderValue(r, "If-None-Match"), collectionETag) { + NotModified(w) + return + } + WriteData(w, http.StatusOK, data) +} + +// WriteConditionalJSON writes a JSON response with a content-derived ETag +// and supports conditional requests. +func WriteConditionalJSON(w http.ResponseWriter, r *http.Request, value any) { + data, err := json.Marshal(value) + if err != nil { + WriteError(w, http.StatusInternalServerError, "internal server error") + return + } + sum := sha256.Sum256(data) + representationETag := `"` + hex.EncodeToString(sum[:]) + `"` + w.Header().Set("ETag", representationETag) + if IfNoneMatch(HeaderValue(r, "If-None-Match"), representationETag) { + NotModified(w) + return + } + WriteData(w, http.StatusOK, data) +} + +// HeaderValue joins repeated request header values using the standard +// comma-separated representation. +func HeaderValue(r *http.Request, name string) string { + return strings.Join(r.Header.Values(name), ",") +} + +// WriteJSON marshals value and writes it as a JSON response. +func WriteJSON(w http.ResponseWriter, status int, value any) { + data, err := json.Marshal(value) + if err != nil { + WriteError(w, http.StatusInternalServerError, "internal server error") + return + } + WriteData(w, status, data) +} + +// WriteData writes already-marshaled JSON response data. +func WriteData(w http.ResponseWriter, status int, data []byte) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(status) + _, _ = w.Write(data) +} + +// NotModified writes a response for a satisfied conditional request. +func NotModified(w http.ResponseWriter) { + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusNotModified) +} + +// WriteError writes the standard JSON error response. +func WriteError(w http.ResponseWriter, status int, message string) { + WriteJSON(w, status, struct { + Error string `json:"error"` + }{Error: message}) +} + +// SetETag sets an entity tag for a numeric resource version. +func SetETag(w http.ResponseWriter, version int64) { w.Header().Set("ETag", ETag(version)) } + +// ETag returns the entity tag for a numeric resource version. +func ETag(version int64) string { return `"` + strconv.FormatInt(version, 10) + `"` } + +// IfNoneMatch reports whether one of the supplied entity tags matches the +// current representation. +func IfNoneMatch(header, current string) bool { + for _, part := range strings.Split(header, ",") { + part = strings.TrimSpace(part) + if part == "*" { + return true + } + if strings.HasPrefix(part, "W/") { + part = strings.TrimSpace(strings.TrimPrefix(part, "W/")) + } + if part == current { + return true + } + } + return false +} + +// DecodeJSON decodes one strict JSON request body into destination. +func DecodeJSON(w http.ResponseWriter, r *http.Request, destination any) bool { + r.Body = http.MaxBytesReader(w, r.Body, maxJSONBodyBytes) + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(destination); err != nil { + WriteError(w, http.StatusBadRequest, "invalid JSON body") + return false + } + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + WriteError(w, http.StatusBadRequest, "invalid JSON body") + return false + } + return true +} + +// Unauthorized writes the standard bearer authentication error response. +func Unauthorized(w http.ResponseWriter) { + w.Header().Set("WWW-Authenticate", `Bearer`) + WriteError(w, http.StatusUnauthorized, "unauthorized") +} + +// InternalError logs a request failure and writes a generic server error. +func InternalError(w http.ResponseWriter, r *http.Request, operation string, err error) { + LogError(r.Context(), "request failed", operation, err) + WriteError(w, http.StatusInternalServerError, "internal server error") +} diff --git a/internal/api/router.go b/internal/web/httpx/router.go similarity index 96% rename from internal/api/router.go rename to internal/web/httpx/router.go index f1de736..25db8cd 100644 --- a/internal/api/router.go +++ b/internal/web/httpx/router.go @@ -1,4 +1,6 @@ -package api +// Package httpx provides reusable net/http routing and middleware +// infrastructure. +package httpx import ( "fmt" diff --git a/internal/api/router_test.go b/internal/web/httpx/router_test.go similarity index 94% rename from internal/api/router_test.go rename to internal/web/httpx/router_test.go index db5ab76..dfd4da1 100644 --- a/internal/api/router_test.go +++ b/internal/web/httpx/router_test.go @@ -1,11 +1,11 @@ -package api_test +package httpx_test import ( "net/http" "net/http/httptest" "testing" - "stick/internal/api" + "stick/internal/web/httpx" ) func testMountPath(t *testing.T, mountPath string) string { @@ -14,13 +14,13 @@ func testMountPath(t *testing.T, mountPath string) string { } func TestRouterWithScopesMiddleware(t *testing.T) { - routes := api.NewRouter(testMountPath(t, "")) + routes := httpx.NewRouter(testMountPath(t, "")) reject := func(http.Handler) http.Handler { return http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) { response.WriteHeader(http.StatusUnauthorized) }) } - protected := routes.With(api.Chain(reject)) + protected := routes.With(httpx.Chain(reject)) routes.Handle(http.MethodGet, "/public", http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) { response.WriteHeader(http.StatusNoContent) })) @@ -42,7 +42,7 @@ func TestRouterWithScopesMiddleware(t *testing.T) { } func TestRouterPreservesNestedMountAndPathValues(t *testing.T) { - routes := api.NewRouter(testMountPath(t, "/ops/stick")) + routes := httpx.NewRouter(testMountPath(t, "/ops/stick")) routes.HandleFunc(http.MethodGet, "/sticks/{id}", func(w http.ResponseWriter, r *http.Request) { if got := r.URL.Path; got != "/ops/stick/sticks/aa001" { t.Errorf("handler path = %q", got) @@ -65,7 +65,7 @@ func TestRouterPreservesNestedMountAndPathValues(t *testing.T) { } func TestRouterUsesCustomNotFoundOnlyInsideMount(t *testing.T) { - routes := api.NewRouter(testMountPath(t, "/stick")) + routes := httpx.NewRouter(testMountPath(t, "/stick")) routes.SetNotFound(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/html") w.WriteHeader(http.StatusNotFound) @@ -86,7 +86,7 @@ func TestRouterUsesCustomNotFoundOnlyInsideMount(t *testing.T) { } func TestRouterCustomNotFoundAndRedirectSemantics(t *testing.T) { - routes := api.NewRouter(testMountPath(t, "/stick")) + routes := httpx.NewRouter(testMountPath(t, "/stick")) routes.SetNotFound(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/html") w.WriteHeader(http.StatusNotFound) @@ -136,7 +136,7 @@ func TestRouterCustomNotFoundAndRedirectSemantics(t *testing.T) { } func TestRouterRejectsUntrustedReferences(t *testing.T) { - routes := api.NewRouter("/stick") + routes := httpx.NewRouter("/stick") for _, reference := range []string{"", "api/v1/sticks", "//evil.example", `/stick\\one`, "/stick#fragment"} { t.Run(reference, func(t *testing.T) { defer func() { From e6aa994779ff6581e39a527e3feb9155cbbea71a Mon Sep 17 00:00:00 2001 From: alxtr Date: Tue, 1 Sep 2026 01:25:41 +0000 Subject: [PATCH 08/14] cleanup remaining things --- internal/api/sticks/conditions.go | 98 ---------------------------- internal/api/sticks/endpoints.go | 19 ++++-- internal/api/sticks/subscriptions.go | 4 +- internal/web/httpx/conditions.go | 40 ++++++++++++ internal/web/httpx/pagination.go | 45 +++++++++++++ 5 files changed, 99 insertions(+), 107 deletions(-) delete mode 100644 internal/api/sticks/conditions.go create mode 100644 internal/web/httpx/conditions.go create mode 100644 internal/web/httpx/pagination.go diff --git a/internal/api/sticks/conditions.go b/internal/api/sticks/conditions.go deleted file mode 100644 index 9331185..0000000 --- a/internal/api/sticks/conditions.go +++ /dev/null @@ -1,98 +0,0 @@ -package sticks - -import ( - "errors" - "net/http" - "strconv" - "strings" - - "stick/internal/auth" - "stick/internal/web/httpx" -) - -func (h *Handler) expectedVersion(w http.ResponseWriter, r *http.Request, id string) (int64, bool) { - header := httpx.HeaderValue(r, "If-Match") - if strings.TrimSpace(header) == "" { - httpx.WriteError(w, http.StatusPreconditionRequired, "If-Match header is required") - return 0, false - } - tags, wildcard, err := parseIfMatch(header) - if err != nil { - httpx.WriteError(w, http.StatusBadRequest, "invalid If-Match header") - return 0, false - } - if len(tags) == 1 && !wildcard { - return tags[0], true - } - - // A wildcard or a list of tags must be compared to the current - // representation before choosing the version passed to the service. - stick, err := h.service.GetStick(r.Context(), auth.IdentityFromContext(r.Context()), id) - if err != nil { - handleError(w, r, "get stick", err) - return 0, false - } - if !wildcard { - matched := false - for _, tag := range tags { - if tag == stick.Version { - matched = true - break - } - } - if !matched { - httpx.WriteError(w, http.StatusPreconditionFailed, "precondition failed") - return 0, false - } - } - return stick.Version, true -} - -func historyPagination(w http.ResponseWriter, r *http.Request) (int, int, bool) { - query := r.URL.Query() - limit := defaultHistoryLimit - offset := 0 - var err error - if raw := query.Get("limit"); raw != "" { - limit, err = strconv.Atoi(raw) - if err != nil || limit < 1 || limit > maxHistoryLimit { - httpx.WriteError(w, http.StatusBadRequest, "invalid history limit") - return 0, 0, false - } - } - if raw := query.Get("offset"); raw != "" { - offset, err = strconv.Atoi(raw) - if err != nil || offset < 0 || offset > maxHistoryOffset { - httpx.WriteError(w, http.StatusBadRequest, "invalid history offset") - return 0, 0, false - } - } - return limit, offset, true -} - -func parseIfMatch(value string) ([]int64, bool, error) { - value = strings.TrimSpace(value) - if value == "" { - return nil, false, errors.New("missing If-Match") - } - if value == "*" { - return nil, true, nil - } - parts := strings.Split(value, ",") - tags := make([]int64, 0, len(parts)) - for _, part := range parts { - part = strings.TrimSpace(part) - if len(part) < 3 || part[0] != '"' || part[len(part)-1] != '"' || strings.HasPrefix(part, "W/") { - return nil, false, errors.New("invalid entity tag") - } - version, err := strconv.ParseInt(part[1:len(part)-1], 10, 64) - if err != nil || version < 1 || httpx.ETag(version) != part { - return nil, false, errors.New("invalid entity tag") - } - tags = append(tags, version) - } - if len(tags) == 0 { - return nil, false, errors.New("missing entity tag") - } - return tags, false, nil -} diff --git a/internal/api/sticks/endpoints.go b/internal/api/sticks/endpoints.go index f2364bf..6b4caac 100644 --- a/internal/api/sticks/endpoints.go +++ b/internal/api/sticks/endpoints.go @@ -76,7 +76,7 @@ func (h *Handler) renameStick(w http.ResponseWriter, r *http.Request) { if !httpx.DecodeJSON(w, r, &request) { return } - version, ok := h.expectedVersion(w, r, r.PathValue("id")) + version, ok := httpx.IfMatchVersion(w, r) if !ok { return } @@ -93,7 +93,7 @@ func (h *Handler) archiveStick(w http.ResponseWriter, r *http.Request) { httpx.WriteError(w, http.StatusForbidden, "forbidden") return } - version, ok := h.expectedVersion(w, r, r.PathValue("id")) + version, ok := httpx.IfMatchVersion(w, r) if !ok { return } @@ -110,7 +110,7 @@ func (h *Handler) unarchiveStick(w http.ResponseWriter, r *http.Request) { httpx.WriteError(w, http.StatusForbidden, "forbidden") return } - version, ok := h.expectedVersion(w, r, r.PathValue("id")) + version, ok := httpx.IfMatchVersion(w, r) if !ok { return } @@ -129,7 +129,7 @@ func (h *Handler) claimStick(w http.ResponseWriter, r *http.Request) { if !httpx.DecodeJSON(w, r, &request) { return } - version, ok := h.expectedVersion(w, r, r.PathValue("id")) + version, ok := httpx.IfMatchVersion(w, r) if !ok { return } @@ -142,7 +142,7 @@ func (h *Handler) claimStick(w http.ResponseWriter, r *http.Request) { } func (h *Handler) releaseStick(w http.ResponseWriter, r *http.Request) { - version, ok := h.expectedVersion(w, r, r.PathValue("id")) + version, ok := httpx.IfMatchVersion(w, r) if !ok { return } @@ -163,8 +163,13 @@ func (h *Handler) history(w http.ResponseWriter, r *http.Request) { return } httpx.SetETag(w, stick.Version) - limit, offset, ok := historyPagination(w, r) - if !ok { + limit, offset, err := httpx.ParsePagination(r, httpx.PaginationOptions{ + DefaultLimit: defaultHistoryLimit, + MaxLimit: maxHistoryLimit, + MaxOffset: maxHistoryOffset, + }) + if err != nil { + httpx.WriteError(w, http.StatusBadRequest, "invalid history pagination") return } sessions, total, err := h.service.GetHistory(r.Context(), identity, id, limit, offset) diff --git a/internal/api/sticks/subscriptions.go b/internal/api/sticks/subscriptions.go index 7ea792f..c430235 100644 --- a/internal/api/sticks/subscriptions.go +++ b/internal/api/sticks/subscriptions.go @@ -8,7 +8,7 @@ import ( ) func (h *Handler) subscribe(w http.ResponseWriter, r *http.Request) { - version, ok := h.expectedVersion(w, r, r.PathValue("id")) + version, ok := httpx.IfMatchVersion(w, r) if !ok { return } @@ -21,7 +21,7 @@ func (h *Handler) subscribe(w http.ResponseWriter, r *http.Request) { } func (h *Handler) unsubscribe(w http.ResponseWriter, r *http.Request) { - version, ok := h.expectedVersion(w, r, r.PathValue("id")) + version, ok := httpx.IfMatchVersion(w, r) if !ok { return } diff --git a/internal/web/httpx/conditions.go b/internal/web/httpx/conditions.go new file mode 100644 index 0000000..2fcc3f4 --- /dev/null +++ b/internal/web/httpx/conditions.go @@ -0,0 +1,40 @@ +package httpx + +import ( + "errors" + "net/http" + "strconv" + "strings" +) + +// ParseIfMatch parses one numeric entity tag from an If-Match value. +func ParseIfMatch(value string) (int64, error) { + value = strings.TrimSpace(value) + if value == "" { + return 0, errors.New("missing If-Match") + } + if len(value) < 3 || value[0] != '"' || value[len(value)-1] != '"' || strings.HasPrefix(value, "W/") { + return 0, errors.New("invalid entity tag") + } + version, err := strconv.ParseInt(value[1:len(value)-1], 10, 64) + if err != nil || version < 1 || ETag(version) != value { + return 0, errors.New("invalid entity tag") + } + return version, nil +} + +// IfMatchVersion validates the required If-Match header and returns its +// numeric version. +func IfMatchVersion(w http.ResponseWriter, r *http.Request) (int64, bool) { + header := HeaderValue(r, "If-Match") + if strings.TrimSpace(header) == "" { + WriteError(w, http.StatusPreconditionRequired, "If-Match header is required") + return 0, false + } + version, err := ParseIfMatch(header) + if err != nil { + WriteError(w, http.StatusBadRequest, "invalid If-Match header") + return 0, false + } + return version, true +} diff --git a/internal/web/httpx/pagination.go b/internal/web/httpx/pagination.go new file mode 100644 index 0000000..be7584f --- /dev/null +++ b/internal/web/httpx/pagination.go @@ -0,0 +1,45 @@ +package httpx + +import ( + "fmt" + "net/http" + "strconv" +) + +// PaginationOptions controls the accepted pagination range. +type PaginationOptions struct { + DefaultLimit int + MaxLimit int + MaxOffset int +} + +// PaginationError identifies the invalid pagination parameter. +type PaginationError struct { + Parameter string +} + +func (e *PaginationError) Error() string { + return fmt.Sprintf("invalid pagination parameter %q", e.Parameter) +} + +// ParsePagination parses the conventional limit and offset query parameters. +func ParsePagination(r *http.Request, options PaginationOptions) (int, int, error) { + query := r.URL.Query() + limit := options.DefaultLimit + offset := 0 + if raw := query.Get("limit"); raw != "" { + value, err := strconv.Atoi(raw) + if err != nil || value < 1 || value > options.MaxLimit { + return 0, 0, &PaginationError{Parameter: "limit"} + } + limit = value + } + if raw := query.Get("offset"); raw != "" { + value, err := strconv.Atoi(raw) + if err != nil || value < 0 || value > options.MaxOffset { + return 0, 0, &PaginationError{Parameter: "offset"} + } + offset = value + } + return limit, offset, nil +} From 577b3d19928375f5777883e96941607f584f26cc Mon Sep 17 00:00:00 2001 From: alxtr Date: Tue, 1 Sep 2026 01:31:03 +0000 Subject: [PATCH 09/14] move server back to api --- cmd/stickd/main.go | 4 ++-- internal/api/{server => }/server.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) rename internal/api/{server => }/server.go (97%) diff --git a/cmd/stickd/main.go b/cmd/stickd/main.go index d089842..f697f6b 100644 --- a/cmd/stickd/main.go +++ b/cmd/stickd/main.go @@ -20,7 +20,7 @@ import ( "stick/internal/adapters/persistence/mongodb" "stick/internal/adapters/persistence/postgres" "stick/internal/adapters/persistence/sqlite" - "stick/internal/api/server" + "stick/internal/api" "stick/internal/application" "stick/internal/auth" "stick/internal/config" @@ -89,7 +89,7 @@ func mainContext(parent context.Context, args []string) (err error) { }() service := application.NewService(store) - serverRunner, err := server.NewRunner(service, store, server.Options{ + serverRunner, err := api.NewRunner(service, store, api.Options{ PublicURL: cfg.Server.PublicURL, ListenAddr: cfg.Server.ListenAddr, JWT: auth.JWTConfig{Endpoint: cfg.Auth.IDPEndpoint, Audience: cfg.Auth.Audience, Scope: cfg.Auth.Scope}, diff --git a/internal/api/server/server.go b/internal/api/server.go similarity index 97% rename from internal/api/server/server.go rename to internal/api/server.go index ef74b2c..779316c 100644 --- a/internal/api/server/server.go +++ b/internal/api/server.go @@ -1,5 +1,5 @@ -// Package server composes the HTTP application and owns its lifecycle. -package server +// Package api composes the HTTP application and owns its lifecycle. +package api import ( "context" From 223f4472597a9b4722c26cf566079c1ff199717d Mon Sep 17 00:00:00 2001 From: alxtr Date: Tue, 1 Sep 2026 01:38:57 +0000 Subject: [PATCH 10/14] moved httpx --- internal/api/health/handler.go | 2 +- internal/api/health/handler_test.go | 2 +- internal/api/server.go | 2 +- internal/api/sticks/endpoints.go | 2 +- internal/api/sticks/handler.go | 2 +- internal/api/sticks/handler_test.go | 2 +- internal/api/sticks/responses.go | 2 +- internal/api/sticks/subscriptions.go | 2 +- internal/{web => }/httpx/conditions.go | 2 +- internal/{web => }/httpx/headers.go | 2 +- internal/{web => }/httpx/middleware.go | 2 +- internal/{web => }/httpx/middleware_test.go | 2 +- internal/{web => }/httpx/not_found.go | 2 +- internal/{web => }/httpx/pagination.go | 2 +- internal/{web => }/httpx/request_log.go | 2 +- internal/{web => }/httpx/request_log_test.go | 2 +- internal/{web => }/httpx/responses.go | 2 +- internal/{web => }/httpx/router.go | 2 +- internal/{web => }/httpx/router_test.go | 2 +- 19 files changed, 19 insertions(+), 19 deletions(-) rename internal/{web => }/httpx/conditions.go (93%) rename internal/{web => }/httpx/headers.go (78%) rename internal/{web => }/httpx/middleware.go (82%) rename internal/{web => }/httpx/middleware_test.go (98%) rename internal/{web => }/httpx/not_found.go (64%) rename internal/{web => }/httpx/pagination.go (94%) rename internal/{web => }/httpx/request_log.go (97%) rename internal/{web => }/httpx/request_log_test.go (98%) rename internal/{web => }/httpx/responses.go (98%) rename internal/{web => }/httpx/router.go (96%) rename internal/{web => }/httpx/router_test.go (99%) diff --git a/internal/api/health/handler.go b/internal/api/health/handler.go index c19565a..c0b5991 100644 --- a/internal/api/health/handler.go +++ b/internal/api/health/handler.go @@ -6,7 +6,7 @@ import ( "net/http" "time" - "stick/internal/web/httpx" + "stick/internal/httpx" ) const ( diff --git a/internal/api/health/handler_test.go b/internal/api/health/handler_test.go index ff94ce8..410430a 100644 --- a/internal/api/health/handler_test.go +++ b/internal/api/health/handler_test.go @@ -9,7 +9,7 @@ import ( "time" "stick/internal/api/health" - "stick/internal/web/httpx" + "stick/internal/httpx" ) type healthDB struct { diff --git a/internal/api/server.go b/internal/api/server.go index 779316c..75abe02 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -15,8 +15,8 @@ import ( "stick/internal/api/sticks" "stick/internal/application" "stick/internal/auth" + "stick/internal/httpx" "stick/internal/publicurl" - "stick/internal/web/httpx" ) // Options contains the settings required to build the HTTP server. diff --git a/internal/api/sticks/endpoints.go b/internal/api/sticks/endpoints.go index 6b4caac..ee46dae 100644 --- a/internal/api/sticks/endpoints.go +++ b/internal/api/sticks/endpoints.go @@ -4,7 +4,7 @@ import ( "net/http" "stick/internal/auth" - "stick/internal/web/httpx" + "stick/internal/httpx" ) func (h *Handler) listSticks(w http.ResponseWriter, r *http.Request) { diff --git a/internal/api/sticks/handler.go b/internal/api/sticks/handler.go index 5008d4d..aa82c20 100644 --- a/internal/api/sticks/handler.go +++ b/internal/api/sticks/handler.go @@ -9,7 +9,7 @@ import ( "stick/internal/application" "stick/internal/auth" domain "stick/internal/core" - "stick/internal/web/httpx" + "stick/internal/httpx" ) const ( diff --git a/internal/api/sticks/handler_test.go b/internal/api/sticks/handler_test.go index c6855a9..ebf58af 100644 --- a/internal/api/sticks/handler_test.go +++ b/internal/api/sticks/handler_test.go @@ -14,7 +14,7 @@ import ( "stick/internal/api/sticks" "stick/internal/application" domain "stick/internal/core" - "stick/internal/web/httpx" + "stick/internal/httpx" ) type tokenValidator map[string]domain.Identity diff --git a/internal/api/sticks/responses.go b/internal/api/sticks/responses.go index 2074ba6..0574469 100644 --- a/internal/api/sticks/responses.go +++ b/internal/api/sticks/responses.go @@ -7,7 +7,7 @@ import ( "stick/internal/application" domain "stick/internal/core" - "stick/internal/web/httpx" + "stick/internal/httpx" ) func writeStick(w http.ResponseWriter, stick domain.Stick) { diff --git a/internal/api/sticks/subscriptions.go b/internal/api/sticks/subscriptions.go index c430235..e828120 100644 --- a/internal/api/sticks/subscriptions.go +++ b/internal/api/sticks/subscriptions.go @@ -4,7 +4,7 @@ import ( "net/http" "stick/internal/auth" - "stick/internal/web/httpx" + "stick/internal/httpx" ) func (h *Handler) subscribe(w http.ResponseWriter, r *http.Request) { diff --git a/internal/web/httpx/conditions.go b/internal/httpx/conditions.go similarity index 93% rename from internal/web/httpx/conditions.go rename to internal/httpx/conditions.go index 2fcc3f4..20b952e 100644 --- a/internal/web/httpx/conditions.go +++ b/internal/httpx/conditions.go @@ -7,7 +7,7 @@ import ( "strings" ) -// ParseIfMatch parses one numeric entity tag from an If-Match value. +// ParseIfMatch parses one numeric HTTP entity tag from an If-Match value. func ParseIfMatch(value string) (int64, error) { value = strings.TrimSpace(value) if value == "" { diff --git a/internal/web/httpx/headers.go b/internal/httpx/headers.go similarity index 78% rename from internal/web/httpx/headers.go rename to internal/httpx/headers.go index 5b84e3d..946a9a6 100644 --- a/internal/web/httpx/headers.go +++ b/internal/httpx/headers.go @@ -2,7 +2,7 @@ package httpx import "net/http" -// Headers adds response headers useful for an HTTP API. +// Headers adds common response headers useful for an HTTP API. func Headers(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") diff --git a/internal/web/httpx/middleware.go b/internal/httpx/middleware.go similarity index 82% rename from internal/web/httpx/middleware.go rename to internal/httpx/middleware.go index 8436753..415f73e 100644 --- a/internal/web/httpx/middleware.go +++ b/internal/httpx/middleware.go @@ -2,7 +2,7 @@ package httpx import "net/http" -// Middleware wraps an HTTP handler with cross-cutting request behavior. +// Middleware wraps an HTTP handler with cross-cutting HTTP behavior. type Middleware = func(http.Handler) http.Handler // Chain combines middleware in outermost-to-innermost order. diff --git a/internal/web/httpx/middleware_test.go b/internal/httpx/middleware_test.go similarity index 98% rename from internal/web/httpx/middleware_test.go rename to internal/httpx/middleware_test.go index 18f4344..97e8506 100644 --- a/internal/web/httpx/middleware_test.go +++ b/internal/httpx/middleware_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "stick/internal/web/httpx" + "stick/internal/httpx" ) func TestChainAppliesMiddlewareInOrder(t *testing.T) { diff --git a/internal/web/httpx/not_found.go b/internal/httpx/not_found.go similarity index 64% rename from internal/web/httpx/not_found.go rename to internal/httpx/not_found.go index c9b17b3..f394d91 100644 --- a/internal/web/httpx/not_found.go +++ b/internal/httpx/not_found.go @@ -2,7 +2,7 @@ package httpx import "net/http" -// NotFound writes the standard JSON response used for unknown routes. +// NotFound writes the standard JSON HTTP response used for unknown routes. func NotFound(w http.ResponseWriter, _ *http.Request) { WriteError(w, http.StatusNotFound, "not found") } diff --git a/internal/web/httpx/pagination.go b/internal/httpx/pagination.go similarity index 94% rename from internal/web/httpx/pagination.go rename to internal/httpx/pagination.go index be7584f..e478cdc 100644 --- a/internal/web/httpx/pagination.go +++ b/internal/httpx/pagination.go @@ -6,7 +6,7 @@ import ( "strconv" ) -// PaginationOptions controls the accepted pagination range. +// PaginationOptions controls the accepted HTTP pagination range. type PaginationOptions struct { DefaultLimit int MaxLimit int diff --git a/internal/web/httpx/request_log.go b/internal/httpx/request_log.go similarity index 97% rename from internal/web/httpx/request_log.go rename to internal/httpx/request_log.go index 1191189..4e118d2 100644 --- a/internal/web/httpx/request_log.go +++ b/internal/httpx/request_log.go @@ -16,7 +16,7 @@ type contextKey string const requestIDKey contextKey = "request-id" -// RequestLogger assigns or propagates a safe request ID, exposes it in the +// RequestLogger assigns or propagates a safe HTTP request ID, exposes it in the // response, and logs only method/path/status/duration/request ID. Query // strings and headers are intentionally excluded because they may contain // credentials or other user data. diff --git a/internal/web/httpx/request_log_test.go b/internal/httpx/request_log_test.go similarity index 98% rename from internal/web/httpx/request_log_test.go rename to internal/httpx/request_log_test.go index 74e7e8a..9a61afa 100644 --- a/internal/web/httpx/request_log_test.go +++ b/internal/httpx/request_log_test.go @@ -11,7 +11,7 @@ import ( "strings" "testing" - "stick/internal/web/httpx" + "stick/internal/httpx" ) func TestRequestIDContext(t *testing.T) { diff --git a/internal/web/httpx/responses.go b/internal/httpx/responses.go similarity index 98% rename from internal/web/httpx/responses.go rename to internal/httpx/responses.go index 63c21a0..4f009d1 100644 --- a/internal/web/httpx/responses.go +++ b/internal/httpx/responses.go @@ -64,7 +64,7 @@ func WriteJSON(w http.ResponseWriter, status int, value any) { WriteData(w, status, data) } -// WriteData writes already-marshaled JSON response data. +// WriteData writes already-marshaled JSON HTTP response data. func WriteData(w http.ResponseWriter, status int, data []byte) { w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") diff --git a/internal/web/httpx/router.go b/internal/httpx/router.go similarity index 96% rename from internal/web/httpx/router.go rename to internal/httpx/router.go index 25db8cd..0d58ada 100644 --- a/internal/web/httpx/router.go +++ b/internal/httpx/router.go @@ -17,7 +17,7 @@ type Router struct { notFound http.Handler } -// NewRouter returns a mount-aware router. mountPath is the optional path from +// NewRouter returns a mount-aware HTTP router. mountPath is the optional path from // an already parsed and validated public URL; the router has no reason to know // the URL's origin. func NewRouter(mountPath string) *Router { diff --git a/internal/web/httpx/router_test.go b/internal/httpx/router_test.go similarity index 99% rename from internal/web/httpx/router_test.go rename to internal/httpx/router_test.go index dfd4da1..5d7272a 100644 --- a/internal/web/httpx/router_test.go +++ b/internal/httpx/router_test.go @@ -5,7 +5,7 @@ import ( "net/http/httptest" "testing" - "stick/internal/web/httpx" + "stick/internal/httpx" ) func testMountPath(t *testing.T, mountPath string) string { From 44a2bef2a4a150b3b91e44afa5ebfad5fe618306 Mon Sep 17 00:00:00 2001 From: alxtr Date: Tue, 1 Sep 2026 01:49:25 +0000 Subject: [PATCH 11/14] tests --- internal/api/server_test.go | 73 ++++++++++++++++++++++++++++ internal/httpx/conditions_test.go | 62 ++++++++++++++++++++++++ internal/httpx/pagination_test.go | 41 ++++++++++++++++ internal/httpx/responses_test.go | 80 +++++++++++++++++++++++++++++++ 4 files changed, 256 insertions(+) create mode 100644 internal/api/server_test.go create mode 100644 internal/httpx/conditions_test.go create mode 100644 internal/httpx/pagination_test.go create mode 100644 internal/httpx/responses_test.go diff --git a/internal/api/server_test.go b/internal/api/server_test.go new file mode 100644 index 0000000..492686d --- /dev/null +++ b/internal/api/server_test.go @@ -0,0 +1,73 @@ +package api + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "stick/internal/adapters/persistence/sqlite" + "stick/internal/application" +) + +func TestNewHandlerRegistersRouteGroups(t *testing.T) { + store, err := sqlite.Open(filepath.Join(t.TempDir(), "stick.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + + handler, err := newHandler(application.NewService(store), store, Options{ + PublicURL: "http://example.test/ops/stick", + }) + if err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + path string + wantStatus int + wantBody string + }{ + {name: "health route", path: "/ops/stick/healthz", wantStatus: http.StatusOK, wantBody: "ok\n"}, + {name: "protected sticks route", path: "/ops/stick/api/v1/sticks", wantStatus: http.StatusUnauthorized, wantBody: `{"error":"unauthorized"}`}, + {name: "api not found", path: "/ops/stick/missing", wantStatus: http.StatusNotFound, wantBody: `{"error":"not found"}`}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil)) + if recorder.Code != test.wantStatus || recorder.Body.String() != test.wantBody { + t.Fatalf("response = %d %q, want %d %q", recorder.Code, recorder.Body.String(), test.wantStatus, test.wantBody) + } + if recorder.Header().Get("X-Content-Type-Options") != "nosniff" { + t.Error("security response header missing") + } + if recorder.Header().Get("X-Request-ID") == "" { + t.Error("request ID response header missing") + } + }) + } +} + +func TestNewRunnerValidatesPublicURL(t *testing.T) { + if _, err := NewRunner(nil, nil, Options{PublicURL: "not a URL"}); err == nil { + t.Fatal("NewRunner accepted an invalid public URL") + } +} + +func TestRunnerReportsListenFailure(t *testing.T) { + runner, err := NewRunner(nil, nil, Options{ + PublicURL: "http://example.test", + ListenAddr: "invalid-listen-address", + }) + if err != nil { + t.Fatal(err) + } + if err := runner.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "listen") { + t.Fatalf("Run error = %v, want listen error", err) + } +} diff --git a/internal/httpx/conditions_test.go b/internal/httpx/conditions_test.go new file mode 100644 index 0000000..b00a74b --- /dev/null +++ b/internal/httpx/conditions_test.go @@ -0,0 +1,62 @@ +package httpx_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "stick/internal/httpx" +) + +func TestParseIfMatch(t *testing.T) { + for _, test := range []struct { + value string + want int64 + valid bool + }{ + {value: `"1"`, want: 1, valid: true}, + {value: `"0"`}, + {value: `*`}, + {value: `"1", "2"`}, + {value: `W/"1"`}, + } { + t.Run(test.value, func(t *testing.T) { + got, err := httpx.ParseIfMatch(test.value) + if test.valid { + if err != nil || got != test.want { + t.Fatalf("ParseIfMatch = %d, %v; want %d", got, err, test.want) + } + return + } + if err == nil { + t.Fatalf("ParseIfMatch(%q) succeeded", test.value) + } + }) + } +} + +func TestIfMatchVersionWritesValidationErrors(t *testing.T) { + for _, test := range []struct { + name string + header string + wantStatus int + wantOK bool + }{ + {name: "missing", wantStatus: http.StatusPreconditionRequired}, + {name: "invalid", header: `"1", "2"`, wantStatus: http.StatusBadRequest}, + {name: "valid", header: `"3"`, wantStatus: http.StatusOK, wantOK: true}, + } { + t.Run(test.name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodPatch, "/", nil) + request.Header.Set("If-Match", test.header) + recorder := httptest.NewRecorder() + version, ok := httpx.IfMatchVersion(recorder, request) + if recorder.Code != test.wantStatus || ok != test.wantOK { + t.Fatalf("result = %d, %t, want %d, %t", recorder.Code, ok, test.wantStatus, test.wantOK) + } + if test.wantOK && version != 3 { + t.Errorf("version = %d, want 3", version) + } + }) + } +} diff --git a/internal/httpx/pagination_test.go b/internal/httpx/pagination_test.go new file mode 100644 index 0000000..aa31f90 --- /dev/null +++ b/internal/httpx/pagination_test.go @@ -0,0 +1,41 @@ +package httpx_test + +import ( + "errors" + "net/http" + "net/http/httptest" + "testing" + + "stick/internal/httpx" +) + +func TestParsePagination(t *testing.T) { + options := httpx.PaginationOptions{DefaultLimit: 20, MaxLimit: 100, MaxOffset: 1000} + for _, test := range []struct { + name string + query string + wantLimit int + wantOffset int + wantParam string + }{ + {name: "defaults", wantLimit: 20}, + {name: "custom", query: "?limit=10&offset=50", wantLimit: 10, wantOffset: 50}, + {name: "invalid limit", query: "?limit=0", wantParam: "limit"}, + {name: "invalid offset", query: "?offset=1001", wantParam: "offset"}, + } { + t.Run(test.name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodGet, "/history"+test.query, nil) + limit, offset, err := httpx.ParsePagination(request, options) + if test.wantParam == "" { + if err != nil || limit != test.wantLimit || offset != test.wantOffset { + t.Fatalf("result = %d, %d, %v", limit, offset, err) + } + return + } + var paginationErr *httpx.PaginationError + if !errors.As(err, &paginationErr) || paginationErr.Parameter != test.wantParam { + t.Fatalf("error = %v, want parameter %q", err, test.wantParam) + } + }) + } +} diff --git a/internal/httpx/responses_test.go b/internal/httpx/responses_test.go new file mode 100644 index 0000000..2763aa3 --- /dev/null +++ b/internal/httpx/responses_test.go @@ -0,0 +1,80 @@ +package httpx_test + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "stick/internal/httpx" +) + +func TestWriteJSONAndNotFound(t *testing.T) { + recorder := httptest.NewRecorder() + httpx.WriteJSON(recorder, http.StatusCreated, map[string]string{"status": "ok"}) + if recorder.Code != http.StatusCreated || recorder.Body.String() != `{"status":"ok"}` { + t.Fatalf("response = %d %q", recorder.Code, recorder.Body.String()) + } + if recorder.Header().Get("Content-Type") != "application/json" || recorder.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("headers = %v", recorder.Header()) + } + + notFound := httptest.NewRecorder() + httpx.NotFound(notFound, httptest.NewRequest(http.MethodGet, "/missing", nil)) + if notFound.Code != http.StatusNotFound || notFound.Body.String() != `{"error":"not found"}` { + t.Fatalf("not found response = %d %q", notFound.Code, notFound.Body.String()) + } +} + +func TestWriteCollectionSupportsConditionalRequests(t *testing.T) { + first := httptest.NewRecorder() + httpx.WriteCollection(first, httptest.NewRequest(http.MethodGet, "/", nil), []string{"one"}) + etag := first.Header().Get("ETag") + if first.Code != http.StatusOK || etag == "" { + t.Fatalf("first response = %d, ETag %q", first.Code, etag) + } + + request := httptest.NewRequest(http.MethodGet, "/", nil) + request.Header.Set("If-None-Match", etag) + second := httptest.NewRecorder() + httpx.WriteCollection(second, request, []string{"one"}) + if second.Code != http.StatusNotModified || second.Body.Len() != 0 { + t.Fatalf("conditional response = %d %q", second.Code, second.Body.String()) + } +} + +func TestDecodeJSONRejectsInvalidBodies(t *testing.T) { + for _, test := range []struct { + name string + body string + }{ + {name: "malformed", body: "{"}, + {name: "unknown field", body: `{"name":"value","extra":true}`}, + {name: "trailing value", body: `{"name":"value"}{}`}, + } { + t.Run(test.name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(test.body)) + recorder := httptest.NewRecorder() + var destination struct { + Name string `json:"name"` + } + if httpx.DecodeJSON(recorder, request, &destination) { + t.Fatal("DecodeJSON accepted invalid body") + } + if recorder.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", recorder.Code) + } + }) + } +} + +func TestHeadersAddsSecurityHeader(t *testing.T) { + handler := httpx.Headers(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + })) + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if recorder.Code != http.StatusNoContent || recorder.Header().Get("X-Content-Type-Options") != "nosniff" { + t.Fatalf("response = %d, headers = %v", recorder.Code, recorder.Header()) + } +} From ae5ff77840fa760ba6850f9c790811f43e30cbbd Mon Sep 17 00:00:00 2001 From: alxtr Date: Tue, 1 Sep 2026 02:21:14 +0000 Subject: [PATCH 12/14] use sticks/v1 --- internal/api/server.go | 4 +-- internal/api/sticks/{ => v1}/endpoints.go | 4 +-- internal/api/sticks/{ => v1}/handler.go | 31 +++++++++---------- internal/api/sticks/{ => v1}/handler_test.go | 8 ++--- internal/api/sticks/{ => v1}/responses.go | 2 +- internal/api/sticks/{ => v1}/subscriptions.go | 2 +- 6 files changed, 25 insertions(+), 26 deletions(-) rename internal/api/sticks/{ => v1}/endpoints.go (98%) rename internal/api/sticks/{ => v1}/handler.go (61%) rename internal/api/sticks/{ => v1}/handler_test.go (96%) rename internal/api/sticks/{ => v1}/responses.go (99%) rename internal/api/sticks/{ => v1}/subscriptions.go (98%) diff --git a/internal/api/server.go b/internal/api/server.go index 75abe02..2507f6f 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -12,7 +12,7 @@ import ( "time" "stick/internal/api/health" - "stick/internal/api/sticks" + sticksv1 "stick/internal/api/sticks/v1" "stick/internal/application" "stick/internal/auth" "stick/internal/httpx" @@ -62,7 +62,7 @@ func newHandler(service *application.Service, readiness health.ReadinessChecker, router := httpx.NewRouter(parsedPublicURL.Path) healthHandler := health.New(readiness) - sticksHandler := sticks.New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, publicURL, options.NotificationsEnabled) + sticksHandler := sticksv1.New(service, auth.NewJWTValidator(options.JWT), options.AdminEmails, publicURL, options.NotificationsEnabled) healthHandler.Register(router) sticksHandler.Register(router) diff --git a/internal/api/sticks/endpoints.go b/internal/api/sticks/v1/endpoints.go similarity index 98% rename from internal/api/sticks/endpoints.go rename to internal/api/sticks/v1/endpoints.go index ee46dae..3230ab3 100644 --- a/internal/api/sticks/endpoints.go +++ b/internal/api/sticks/v1/endpoints.go @@ -1,4 +1,4 @@ -package sticks +package v1 import ( "net/http" @@ -61,7 +61,7 @@ func (h *Handler) createStick(w http.ResponseWriter, r *http.Request) { return } httpx.SetETag(w, stick.Version) - w.Header().Set("Location", h.publicURL+apiPrefix+"/sticks/"+stick.ID) + w.Header().Set("Location", h.publicURL+"/api/v1/sticks/"+stick.ID) httpx.WriteJSON(w, http.StatusCreated, stickToJSON(stick)) } diff --git a/internal/api/sticks/handler.go b/internal/api/sticks/v1/handler.go similarity index 61% rename from internal/api/sticks/handler.go rename to internal/api/sticks/v1/handler.go index aa82c20..039abb5 100644 --- a/internal/api/sticks/handler.go +++ b/internal/api/sticks/v1/handler.go @@ -1,5 +1,5 @@ -// Package sticks provides the authenticated Stick REST API route group. -package sticks +// Package v1 provides the authenticated Stick REST API route group. +package v1 import ( "context" @@ -13,7 +13,6 @@ import ( ) const ( - apiPrefix = "/api/v1" defaultHistoryLimit = 20 maxHistoryLimit = 100 maxHistoryOffset = 100_000 @@ -54,20 +53,20 @@ func New( // every route in this group. func (h *Handler) Register(router *httpx.Router) { protected := router.With(h.authenticate) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks", h.listSticks) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks", h.createStick) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/archived", h.listArchivedSticks) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}", h.getStick) - protected.HandleFunc(http.MethodPatch, apiPrefix+"/sticks/{id}", h.renameStick) - protected.HandleFunc(http.MethodGet, apiPrefix+"/sticks/{id}/history", h.history) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/claim", h.claimStick) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/release", h.releaseStick) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/archive", h.archiveStick) - protected.HandleFunc(http.MethodPost, apiPrefix+"/sticks/{id}/unarchive", h.unarchiveStick) + protected.HandleFunc(http.MethodGet, "/api/v1/sticks", h.listSticks) + protected.HandleFunc(http.MethodPost, "/api/v1/sticks", h.createStick) + protected.HandleFunc(http.MethodGet, "/api/v1/sticks/archived", h.listArchivedSticks) + protected.HandleFunc(http.MethodGet, "/api/v1/sticks/{id}", h.getStick) + protected.HandleFunc(http.MethodPatch, "/api/v1/sticks/{id}", h.renameStick) + protected.HandleFunc(http.MethodGet, "/api/v1/sticks/{id}/history", h.history) + protected.HandleFunc(http.MethodPost, "/api/v1/sticks/{id}/claim", h.claimStick) + protected.HandleFunc(http.MethodPost, "/api/v1/sticks/{id}/release", h.releaseStick) + protected.HandleFunc(http.MethodPost, "/api/v1/sticks/{id}/archive", h.archiveStick) + protected.HandleFunc(http.MethodPost, "/api/v1/sticks/{id}/unarchive", h.unarchiveStick) if h.notificationsEnabled { - protected.HandleFunc(http.MethodPut, apiPrefix+"/sticks/{id}/subscription", h.subscribe) - protected.HandleFunc(http.MethodDelete, apiPrefix+"/sticks/{id}/subscription", h.unsubscribe) - protected.HandleFunc(http.MethodGet, apiPrefix+"/subscriptions", h.subscriptions) + protected.HandleFunc(http.MethodPut, "/api/v1/sticks/{id}/subscription", h.subscribe) + protected.HandleFunc(http.MethodDelete, "/api/v1/sticks/{id}/subscription", h.unsubscribe) + protected.HandleFunc(http.MethodGet, "/api/v1/subscriptions", h.subscriptions) } } diff --git a/internal/api/sticks/handler_test.go b/internal/api/sticks/v1/handler_test.go similarity index 96% rename from internal/api/sticks/handler_test.go rename to internal/api/sticks/v1/handler_test.go index ebf58af..270e833 100644 --- a/internal/api/sticks/handler_test.go +++ b/internal/api/sticks/v1/handler_test.go @@ -1,4 +1,4 @@ -package sticks_test +package v1_test import ( "context" @@ -11,7 +11,7 @@ import ( "testing" "stick/internal/adapters/persistence/sqlite" - "stick/internal/api/sticks" + sticksv1 "stick/internal/api/sticks/v1" "stick/internal/application" domain "stick/internal/core" "stick/internal/httpx" @@ -36,7 +36,7 @@ func newTestHandler(t *testing.T) http.Handler { t.Cleanup(func() { _ = store.Close() }) publicURL := "http://localhost:8080" admin := domain.Identity{Sub: "admin", Name: "Admin", Email: "admin@example.com", EmailVerified: true} - handler := sticks.New(application.NewService(store), tokenValidator{ + handler := sticksv1.New(application.NewService(store), tokenValidator{ "admin-token": admin, "user-token": {Sub: "user", Name: "User", Email: "user@example.com", EmailVerified: true}, }, []string{"admin@example.com"}, publicURL, true) @@ -148,4 +148,4 @@ func TestAPIMapsAuthorizationAndValidationErrors(t *testing.T) { } } -var _ sticks.TokenValidator = tokenValidator{} +var _ sticksv1.TokenValidator = tokenValidator{} diff --git a/internal/api/sticks/responses.go b/internal/api/sticks/v1/responses.go similarity index 99% rename from internal/api/sticks/responses.go rename to internal/api/sticks/v1/responses.go index 0574469..8d43660 100644 --- a/internal/api/sticks/responses.go +++ b/internal/api/sticks/v1/responses.go @@ -1,4 +1,4 @@ -package sticks +package v1 import ( "errors" diff --git a/internal/api/sticks/subscriptions.go b/internal/api/sticks/v1/subscriptions.go similarity index 98% rename from internal/api/sticks/subscriptions.go rename to internal/api/sticks/v1/subscriptions.go index e828120..0a8af4c 100644 --- a/internal/api/sticks/subscriptions.go +++ b/internal/api/sticks/v1/subscriptions.go @@ -1,4 +1,4 @@ -package sticks +package v1 import ( "net/http" From 67830529bebeffe1d59106c09673bab79a5901a0 Mon Sep 17 00:00:00 2001 From: alxtr Date: Fri, 4 Sep 2026 00:22:13 +0000 Subject: [PATCH 13/14] Fix rebased configuration conflicts --- .../azure_app_configuration_provider_test.go | 2 +- internal/config/config_test.go | 2 +- internal/config/normalize.go | 44 +++---------------- 3 files changed, 8 insertions(+), 40 deletions(-) diff --git a/internal/config/azure_app_configuration_provider_test.go b/internal/config/azure_app_configuration_provider_test.go index ce43e2b..1d53df4 100644 --- a/internal/config/azure_app_configuration_provider_test.go +++ b/internal/config/azure_app_configuration_provider_test.go @@ -97,7 +97,7 @@ func TestAzureAppConfigurationProviderLoadsSettings(t *testing.T) { if cfg.Database.DSN != "/tmp/azure.db" || cfg.Database.Driver != DatabaseDriverSQLite { t.Fatalf("database = %+v", cfg.Database) } - if cfg.Server.PublicURL.String() != "http://localhost:8080" { + if cfg.Server.PublicURL != "http://localhost:8080" { t.Errorf("PublicURL = %q", cfg.Server.PublicURL) } if got := cfg.Auth.AdminEmails; len(got) != 2 || got[0] != "Alice@example.com" || got[1] != "bob@example.com" { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 5228d2a..3fd4b35 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -145,7 +145,7 @@ auth: if cfg.Database.DSN != "/tmp/from-env.db" { t.Errorf("Database.DSN = %q", cfg.Database.DSN) } - if got := cfg.Server.PublicURL.String(); got != "https://env.example.com/stick" { + if got := cfg.Server.PublicURL; got != "https://env.example.com/stick" { t.Errorf("PublicURL = %q", got) } if got := cfg.Auth.AdminEmails; len(got) != 2 || got[0] != " Alice@Example.com" || got[1] != " bob@example.com " { diff --git a/internal/config/normalize.go b/internal/config/normalize.go index f3fbc91..248c928 100644 --- a/internal/config/normalize.go +++ b/internal/config/normalize.go @@ -16,45 +16,9 @@ func normalize(config Config) (Config, error) { if config.Server.ListenAddr == "" { config.Server.ListenAddr = ":8080" } -<<<<<<< HEAD - if err := config.Server.PublicURL.Validate(); err != nil { + if strings.TrimSpace(config.Server.PublicURL) == "" { if err := setPublicURL(&config, "http://localhost"); err != nil { return Config{}, err -======= - database, err := normalizeDatabase(raw.Database) - if err != nil { - return Config{}, err - } - publicURLValue := strings.TrimSpace(raw.Server.PublicURL) - if publicURLValue == "" { - publicURLValue = "http://localhost" - } - publicURL, err := publicurl.Parse(publicURLValue) - if err != nil { - return Config{}, err - } - parsedPublicURL, err := url.Parse(publicURL) - if err != nil { - // publicurl.Parse already parsed and validated this value. Keep this - // guard local to the configuration boundary if that implementation - // changes in the future. - return Config{}, fmt.Errorf("invalid PUBLIC_URL %q: %w", publicURLValue, err) - } - if parsedPublicURL.Scheme != "https" && !netutil.IsLoopbackHost(parsedPublicURL.Hostname()) { - return Config{}, fmt.Errorf("invalid PUBLIC_URL %q: HTTPS is required for non-local addresses", publicURLValue) - } - - listenAddr := strings.TrimSpace(raw.Server.ListenAddr) - if listenAddr == "" { - listenAddr = ":8080" - } - - location := time.UTC - if raw.Timezone != "" { - location, err = time.LoadLocation(raw.Timezone) - if err != nil { - return Config{}, fmt.Errorf("invalid timezone %q: %w", raw.Timezone, err) ->>>>>>> 39d6435 (Trying to factor out publicurl) } } if config.Timezone == nil { @@ -76,7 +40,11 @@ func normalize(config Config) (Config, error) { if err := validateDatabase(config.Database); err != nil { return Config{}, err } - if !config.Server.PublicURL.IsHTTPS() && !config.Server.PublicURL.IsLoopback() { + parsedPublicURL, err := url.Parse(config.Server.PublicURL) + if err != nil { + return Config{}, fmt.Errorf("invalid PUBLIC_URL %q: %w", config.Server.PublicURL, err) + } + if parsedPublicURL.Scheme != "https" && !netutil.IsLoopbackHost(parsedPublicURL.Hostname()) { return Config{}, fmt.Errorf("invalid server.public_url %q: HTTPS is required for non-local addresses", config.Server.PublicURL) } endpoint, err := parseHTTPURL("auth.idp_endpoint", config.Auth.IDPEndpoint) From 4360d1a23027d816ac68982bb209c4ef366cef24 Mon Sep 17 00:00:00 2001 From: alxtr Date: Fri, 4 Sep 2026 00:37:22 +0000 Subject: [PATCH 14/14] errgroup --- go.mod | 2 +- internal/application/lifecycle.go | 40 +++++++++++++++----------- internal/application/lifecycle_test.go | 19 ++++++++++++ 3 files changed, 44 insertions(+), 17 deletions(-) diff --git a/go.mod b/go.mod index 8fca41f..55ae82a 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/testcontainers/testcontainers-go/modules/mongodb v0.44.0 github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 go.mongodb.org/mongo-driver v1.17.9 + golang.org/x/sync v0.22.0 gopkg.in/yaml.v3 v3.0.1 modernc.org/sqlite v1.48.0 ) @@ -91,7 +92,6 @@ require ( golang.org/x/crypto v0.56.0 // indirect golang.org/x/net v0.57.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sync v0.22.0 // indirect golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.41.0 // indirect modernc.org/libc v1.70.0 // indirect diff --git a/internal/application/lifecycle.go b/internal/application/lifecycle.go index ae9ecc0..aa1989d 100644 --- a/internal/application/lifecycle.go +++ b/internal/application/lifecycle.go @@ -4,6 +4,8 @@ import ( "context" "errors" "log/slog" + + "golang.org/x/sync/errgroup" ) // Component is a long-lived application component. @@ -17,28 +19,34 @@ func Run(parent context.Context, components ...Component) error { if len(components) == 0 { return nil } - runCtx, cancel := context.WithCancel(parent) + group, groupCtx := errgroup.WithContext(parent) + runCtx, cancel := context.WithCancel(groupCtx) defer cancel() + stopShutdownLog := context.AfterFunc(parent, func() { + slog.InfoContext(parent, "shutdown requested") + }) + defer stopShutdownLog() results := make(chan error, len(components)) for _, component := range components { - go func(component Component) { results <- component.Run(runCtx) }(component) + component := component + group.Go(func() error { + err := component.Run(runCtx) + // errgroup only cancels its context for non-nil errors. A clean + // component stop must also stop the remaining components. + cancel() + results <- err + return err + }) } + // Preserve Run's contract of returning all component errors rather than + // errgroup's first error. + group.Wait() + close(results) var errs []error - shutdownDone := parent.Done() - remaining := len(components) - for remaining > 0 { - select { - case <-shutdownDone: - shutdownDone = nil - slog.InfoContext(parent, "shutdown requested") - cancel() - case runErr := <-results: - if runErr != nil { - errs = append(errs, runErr) - } - cancel() - remaining-- + for runErr := range results { + if runErr != nil { + errs = append(errs, runErr) } } return errors.Join(errs...) diff --git a/internal/application/lifecycle_test.go b/internal/application/lifecycle_test.go index b2b2b72..168239b 100644 --- a/internal/application/lifecycle_test.go +++ b/internal/application/lifecycle_test.go @@ -29,6 +29,25 @@ func TestRunCancelsSiblingAndReturnsComponentError(t *testing.T) { } } +func TestRunCancelsSiblingWhenComponentStopsCleanly(t *testing.T) { + siblingStopped := make(chan struct{}) + stopper := testComponent{run: func(context.Context) error { return nil }} + sibling := testComponent{run: func(ctx context.Context) error { + <-ctx.Done() + close(siblingStopped) + return nil + }} + + if err := app.Run(context.Background(), stopper, sibling); err != nil { + t.Fatalf("Run error = %v, want nil", err) + } + select { + case <-siblingStopped: + case <-time.After(time.Second): + t.Fatal("sibling component was not canceled") + } +} + func TestRunWithNoComponentsReturnsImmediately(t *testing.T) { if err := app.Run(context.Background()); err != nil { t.Fatalf("Run error = %v, want nil", err)