Declare GraphQL auth in the schema and drop the Go Claude client

Authorisation: @admin and @signedIn schema directives replace the 25
hand-copied resolver checks. A test fails if a mutation has neither and
is not on the public allow-list, so a new mutation cannot ship unguarded.

IDs: uint model IDs bind through graphql.UintID, removing the ten
int(obj.ID) resolvers.

Job status is a GraphQL enum, tied to services.statusOrder by a test.
Input is strict, so the mutations no longer coerce an unknown status to
"applied"; output is lenient so one legacy row cannot fail the list.

deleteJobApplication and deleteJobAppReference now error on a missing id
like the other deletes.

The rowing reader, the job extractor and now the email classifier reach
the Python service through one services.CallPython helper. The email
pipeline's prompt and fence stripping moved to Python, and
anthropic-sdk-go is gone from go.mod.

Fix the auth test fixture, whose 11-byte secret had been panicking the
services test package since InitAuth began requiring 32 bytes. Add a
test that keeps the python service's compose environment list in step
with the env registry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-12 14:39:19 +01:00
co-authored by Claude Opus 5.5
parent 307268fbea
commit 71344a1f8d
55 changed files with 2271 additions and 1099 deletions
+230 -20
View File
@@ -2,7 +2,8 @@
The Go API for adam-french.co.uk. It is one process behind nginx, serving a
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea, Anthropic).
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything
that needs Claude is asked of the Python service, not called from here.
Nginx strips the `/api` prefix before proxying, so a browser request to
`/api/graphql` arrives here as `/graphql`. Every path below is as this service
@@ -18,9 +19,11 @@ handlers/ REST endpoints + the shared Store dependency container
handle_*.go one file per domain
services/ stateful collaborators (DB, auth, chat hub, API clients)
graph/ GraphQL layer
schema/*.graphql source of truth for the schema
schema/*.graphql source of truth for the schema, including who may call what
*.resolvers.go resolver implementations, one per schema file
*_helpers.go hand-written mapping helpers (never regenerated)
directives.go @admin / @signedIn: the authorisation checks, written once
directives_test.go fails when a mutation is added without one
context.go reading identity out of the resolver context
middleware.go putting it in
doc.go package overview — read this before touching resolvers
@@ -41,9 +44,10 @@ graph/ GraphQL layer
reached through the `admin` group can assume both.
4. **GraphQL**: there is no guarding middleware. `AuthContextMiddleware` only
*annotates* the request context with the Gin context and, if a valid access
token is present, the JWT claims — and then lets everything through. Each
resolver authorises itself with `IsAdminFromCtx` / `UserIDFromCtx`.
**A resolver that forgets to check is public.**
token is present, the JWT claims — and then lets everything through. A
field is guarded by a directive on it in the schema, `@admin` or
`@signedIn`, which runs before the resolver. **A field with neither is
public.** See [GraphQL authorisation](#graphql-authorisation).
5. Handlers and resolvers both reach the database and the caches through the
single `handlers.Store` built in `main`.
@@ -70,6 +74,96 @@ The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
both. They share `services.Auth` and the rate limiter, but each has its own
cookie-writing helper — change one and you must change the other.
## GraphQL authorisation
Who may call a field is written in the schema, on the field:
```graphql
extend type Query {
bookmarks: [Bookmark!]! # public
places: [Place!]! @signedIn # any signed-in user
users: [User!]! @admin # admins only
}
```
| directive | passes when | error otherwise |
| --- | --- | --- |
| `@admin` | the access token's `admin` claim is true | `admin access required` |
| `@signedIn` | there is a valid access token at all | `authentication required` |
| *(none)* | always | — |
Both are declared in `graph/schema/schema.graphql`, implemented once in
`graph/directives.go`, and handed to gqlgen in `main.go`
(`graph.Config{Directives: graph.Directives()}`). gqlgen calls the directive
before the resolver; on an error the resolver never runs and the client gets
that message for the field. The two strings are shown as-is by the front end,
so they are part of the API. If the `Directives` line were ever dropped from
`main.go` the guarded fields would all fail (`directive admin is not
implemented`), not open.
This replaced an `if !IsAdminFromCtx(ctx) { return ... }` that was pasted into
the top of every guarded resolver, where leaving it out was invisible. Now a
guarded resolver has no check in it, and the absence of a guard is something a
test can see.
**What is guarded.** Queries are public and mutations are `@admin`, except:
- `login`, `logout`, `refreshToken` — public; they are how a session starts
and ends.
- `createPlace`, `updatePlace`, `deletePlace` and the `places` query —
`@signedIn`. Places are a shared list with no per-user ownership.
- `users`, `user`, `jobApplications`, `jobApplication`, `jobAppReferences` —
queries, but `@admin`: private data.
**What a directive cannot say stays in the resolver**, using `IsAdminFromCtx` /
`UserIDFromCtx` from `graph/context.go`:
- `updatePost` / `deletePost` are `@admin` *and* require the caller to be the
post's author; `setUserAdmin` refuses to change the caller's own flag.
- `me` has no directive: it returns its own `unauthorized` error.
- `messages` has no directive: it filters private messages out for non-admins
instead of refusing.
- `spotifyNeedsReauth` has no directive: it is `false` for non-admins.
**The safety net** is `graph/directives_test.go`, which walks the parsed
schema:
- every `Mutation` field must carry `@admin` or `@signedIn`, unless it is in
the `publicMutations` list in that file (the three above). A new mutation
with no directive fails the build's tests until one or the other is done;
- the `@signedIn` mutations and the guarded queries are pinned by name, so
loosening `@admin` to `@signedIn`, or dropping a guard from a private query,
has to be done in the test as well;
- the directive functions are unit-tested, and a handful of operations are run
through the real executable schema to pin the messages on the wire.
One caveat: the test reads the `.graphql` files, but enforcement is in
`generated.go`. Adding a directive to an existing field does nothing until
gqlgen is re-run.
## Adding an entity
1. **Model** — add the struct to `models/models.go` with `ID uint`
(`gorm:"primarykey"`) and a `gorm.DeletedAt`, and list it in `AutoMigrate`
in `services/database.go`. There are no migration files.
2. **Schema** — add `graph/schema/<name>.graphql` with the type, its inputs,
and `extend type Query` / `extend type Mutation`. Put `@admin` or
`@signedIn` on every mutation, and on any query that is not for the public.
Use `#` comments, not `"""` descriptions.
3. **Binding** — map the type onto the model in `gqlgen.yml`, with
`deletedAt: resolver: false`. Without the entry gqlgen generates a second,
unrelated struct in `graph/model/`.
4. **Generate** — `go run github.com/99designs/gqlgen generate` (below). This
creates `graph/<name>.resolvers.go` with a stub per query and mutation.
5. **Resolvers** — fill the stubs in. Do not write an auth check; the
directive has run. Do not write an `ID` resolver; `ID uint` binds by itself
(see [IDs](#gotchas)). Put commentary inside the function bodies, since
gqlgen rewrites what is above the signature. A delete should load the row
first and return an error for a missing id, as the existing ones do.
6. **Test** — `go test ./...`. `directives_test.go` will tell you if a
mutation was left unguarded; if you added a guarded *query*, add it to the
pinned list there.
## GraphQL vs REST
GraphQL is the default and covers essentially all the site's data. REST exists
@@ -98,6 +192,15 @@ host, which is the part trusted to act.
read it. It is embedded in the binary and read from the checkout by the host
script, so one file decides what the panel offers and what the host accepts.
A test fails if it and `.env.example` disagree.
- **The `python` service is a third place.** It is the one container given an
explicit `environment:` list in `docker-compose.yml` instead of the whole
`.env`, so that it never holds the database password or the JWT secret. A
new Python variable therefore goes in the registry (with `python` in its
`services`), in `.env.example`, *and* in that list.
`TestEnvRegistryMatchesComposePythonEnvironment` reads the compose file and
fails if a variable the registry says python reads is not passed to it, or
if an editable variable passed to it does not list `python`. Locked
variables carry no `services` and are exempt (`PYTHON_PORT` is one).
- `GET /admin/env` — the registry plus state from this process's own
environment. A secret's value is never sent, only "set" and, for values of
12+ characters, the last four.
@@ -139,7 +242,8 @@ the posting open in the browser to the job tracker.
what status. Drives the script's badge.
- `POST /jobs/capture/extract` — page text in, `{jobTitle, company, location,
notes}` out, read by Claude through the Python service
(`/internal/jobs/extract`). Stores nothing.
(`/internal/jobs/extract`, see [Calling the Python service](#calling-the-python-service)).
Stores nothing.
- `POST /jobs/capture` — an **upsert**. A posting is matched by its canonical
URL (`canonicalJobURL` strips tracking parameters and folds LinkedIn's
several URL shapes into one), then by `(company, job title)` the way the
@@ -151,6 +255,36 @@ one application. It is not watertight: the pipeline still matches on the exact
title, so a posting captured as "Senior Engineer" whose confirmation email
says "Senior Engineer (Platform)" becomes a second row.
## Calling the Python service
Every Claude call the site makes lives in the Python service; this backend has
no Anthropic client and does not read `CLAUDE_API_KEY`. It reaches three
internal routes directly over the Docker network
(`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through
nginx, which answers 404 for `/py/internal/`:
| route | caller | sends | gets back |
| --- | --- | --- | --- |
| `/internal/rowing/read` | `POST /rowing` (`handlers/handle_rowing.go`) | `{media_type, data}` (image, base64) | `{timeMinutes, timeSeconds, distance}` |
| `/internal/jobs/extract` | `POST /jobs/capture/extract` (`handlers/handle_job_capture.go`) | `{url, title, text}` | `{jobTitle, company, location, notes}` |
| `/internal/email/classify` | the email pipeline (`services/email_sync.go`) | `{message}` | `EmailAnalysis` (below) |
All three go through one function, `services.CallPython[T]` in
`services/python_call.go`: marshal the body, POST it, decode a 200 into `T`.
It has the one HTTP client (two-minute timeout, above the Python side's own
worst case of a retried Claude call) and the one rule for failures:
- a **502 whose `detail` is a string** is a message the route wrote for a
person ("failed to parse image data"). It comes back as a
`*services.PythonError`, and the two HTTP handlers relay it to the browser;
- **anything else** — connection refused, a 422 (its `detail` is a list), a
503 for an unset `CLAUDE_API_KEY`, a reply that will not decode — is an
ordinary error. Callers log it and show something generic.
It lives in `services` because both `handlers` and `services` need it and
`handlers` already imports `services`. A new internal route needs only a
request struct, a reply struct and a one-line call.
## Services
Everything is constructed in `main` from environment variables and handed to
@@ -172,17 +306,68 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
(Steam).
- **email_sync.go** / **email_imap.go** — the job-application pipeline: fetch
recent mail (Microsoft Graph *or* a hand-rolled IMAP client), keyword-filter
it, ask Claude to extract structured data, create or advance a
`JobApplication`. Runs on a timer and can be triggered by an admin.
- **claude.go** — the Anthropic client, used by the email pipeline. (The
rowing photo reader's and the job posting reader's Claude calls live in the
Python service; `POST /rowing` and `POST /jobs/capture/extract` reach it
directly at `http://$PYTHON_HOST:$PYTHON_PORT/internal/...`.)
it, have each survivor classified, create or advance a `JobApplication`.
Runs on a timer and can be triggered by an admin.
The classification is the Python service's `/internal/email/classify`,
which owns the prompt, the Claude call and the parsing of the model's
reply. Go sends one string — `Subject:`, `From:` and `Date:` lines, a blank
line, the cleaned body (capped at 4,000 bytes; the whole message at the
200,000 characters Python accepts) — and gets back `EmailAnalysis`:
`isJobEmail`, `action`, `company`, `jobTitle`, `status`, and the nullable
`location`, `url`, `appliedAt`, `notes`. Everything either side of that
call is unchanged and still here: the pre-filter, dedup, retry accounting,
matching on (company, job title), and the forward-only status rule. Any
failure of the call, whatever its status code, is a failed attempt at that
email.
- **python_call.go** — `CallPython`, the one way to reach the Python service's
internal routes. See [Calling the Python service](#calling-the-python-service).
- **job_status.go** — how the `JobStatus` GraphQL enum is read and written.
See [Job status](#job-status).
- **notes.go** — path-traversal-safe file lookup for the notes directory.
- **seed.go** — dev-only test data. Creates an admin with the password
`password`, so it must never run in production (`SEED_DB=true` is set only
in `docker-compose.dev.yml`).
## Job status
A job application's status is one of eight lowercase strings: `saved`,
`applied`, `screening`, `assessment`, `interviewing`, `offer`, `rejected`,
`withdrawn`. The list is `statusOrder` in `services/email_sync.go`, which also
ranks them — the email pipeline and the capture endpoint only ever move a row
forwards through it (`services.StatusAdvances`).
GraphQL knows the same list as `enum JobStatus`
(`graph/schema/job_application.graphql`), used for `JobApplication.status` and
both inputs. `TestJobStatusEnumMatchesStatusOrder` in
`services/job_status_test.go` parses the schema file and fails unless the enum
and the map hold the same statuses in the same order, so adding a status means
editing both. (The classifier prompt in the Python service, the tracker page
and the userscript list them too, and nothing checks those.)
The enum is bound in `gqlgen.yml` to `services.MarshalJobStatus` /
`UnmarshalJobStatus` instead of a generated Go type, for two reasons:
- **The column stays a `string`.** `models.JobApplication.Status` binds as it
is; there is no migration and no conversion in the pipeline.
- **Input is strict, output is lenient.** A mutation with a status outside the
list is refused (`"hired" is not a valid JobStatus`) — nothing is coerced to
`applied` any more. But a row already holding something else, such as the
Title Case values the tracker once wrote, must not break reads: `status` is
non-null, so a serialisation error on one row would null the entire
`jobApplications` list. On the way out a value that matches once trimmed and
lowercased is sent in its canonical form, and anything else is sent exactly
as stored for the tracker to display and correct.
On the wire nothing changed from when the field was a `String`: the client
sends `"applied"` as a JSON string variable and reads back `"applied"`. (An
enum does differ for a status written *inline* in a query document, which must
now be `status: applied`, unquoted. The front end only uses variables.)
`services.NormalizeStatus`, which trims, lowercases and falls back to
`applied`, is still what the email pipeline and `POST /jobs/capture` use on
values that do not come through GraphQL.
## Regenerating gqlgen
The `.graphql` files are the source of truth.
@@ -205,6 +390,14 @@ the end of it — which is why shared helpers live in `*_helpers.go` instead.
to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh
generated struct rather than the model you expected.
Two scalar-level bindings in `gqlgen.yml` are worth knowing about: `ID` lists
both `graphql.IntID` and `graphql.UintID` (see IDs under Gotchas), and
`JobStatus` points at the hand-written marshaller described above.
If you delete a field or stop needing a resolver, delete the resolver function
by hand before regenerating; otherwise gqlgen keeps it, commented out, in a
warning block at the end of the file.
## Gotchas
- **Soft delete everywhere.** Every model except `ProcessedEmail` has a
@@ -213,8 +406,18 @@ generated struct rather than the model you expected.
with deleted rows — a soft-deleted username cannot be reused.
- **`Preload` is not lazy.** `Post.Author` is nil unless the query preloads it;
there is no error to tell you why the field came back null.
- **IDs.** Models use `uint`, GraphQL uses `Int`. That is why nearly every type
has a hand-written `ID` resolver doing `int(obj.ID)`.
- **IDs.** Models use `uint`; the schema uses `ID`. `gqlgen.yml` binds `ID` to
`graphql.IntID` *and* `graphql.UintID`, so a model's `ID uint` field is
served directly — there are no `ID` resolvers, and a new type does not need
one. `IntID` is listed first, which is why resolver *arguments* are still
`id int`. Both write an id as a quoted decimal string (`"12"`) and accept a
string or a number, so the wire format is the same either way. Other
unsigned fields are not IDs and still have resolvers: `Message.authorId`,
`Rowing.time`, `Rowing.distance`.
- **Deletes error on a missing id.** Every delete mutation loads the row
first. `deleteJobApplication` and `deleteJobAppReference` return `Boolean!`
rather than the row, so the only value they ever return is `true`; a wrong
id is a `record not found` error, not `false`.
- **`Message.AuthorID` is not a user id.** It is a per-process counter handed
out by the chat hub on connect, meaningless across restarts.
- **The chat table is capped.** Every insert soft-deletes all but the newest
@@ -222,9 +425,10 @@ generated struct rather than the model you expected.
- **Store's caches are unsynchronised** and shared by all requests. The races
are benign (at worst a duplicate upstream fetch), but do not add a field
there that would be unsafe to tear.
- **Claude output is parsed as JSON** after stripping a possible markdown code
fence — `services.StripMarkdownFence` in `email_sync.go`, with a port of it
in `python/app/rowing.py` for the rowing photo reader.
- **Claude's output is never parsed here.** Prompts, the markdown-fence
stripping and the JSON parsing are all in the Python service; this side
receives typed JSON or an error (see
[Calling the Python service](#calling-the-python-service)).
- **The email pipeline retries a failure up to `maxEmailAttempts` (3) times.**
A failed email is recorded with action `"error"` and an attempt counter;
while it has attempts left the next sync reprocesses it and updates the same
@@ -232,7 +436,10 @@ generated struct rather than the model you expected.
already moved past the failure, the sync also rewinds the window to the
oldest retryable row's `ReceivedAt` — otherwise the email could never be
re-fetched. Once the cap is reached the row is terminal, so an email Claude
can never parse stops costing API calls.
can never parse stops costing API calls. A failure is any error from the
classify call — Python down, a 502, a 503 because `CLAUDE_API_KEY` is unset
— so an outage of the Python service uses up attempts just as an Anthropic
outage does. The one exception is a cancelled sync, which records nothing.
- **Authenticating email after start-up does not start the scheduler**, which
only checks readiness once — restart, or trigger syncs by hand.
- **Introspection and the playground are off** unless `DEV_MODE=true` *and*
@@ -253,8 +460,7 @@ generated struct rather than the model you expected.
| `SEED_DB` | seed dev test data (never in production) |
| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras |
| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth |
| `CLAUDE_API_KEY` | Anthropic API (email pipeline; the python service reads it too) |
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the rowing photo reader (default `python:8000`) |
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the three Claude routes (default `python:8000`) |
| `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed |
| `STEAM_API_KEY` / `STEAM_ID` | Steam presence |
| `EMAIL_SYNC_ENABLED` / `EMAIL_BACKEND` / `EMAIL_SYNC_INTERVAL` | email pipeline (`graph` or `imap`) |
@@ -265,3 +471,7 @@ Paths baked into the code, all inside mounted volumes so they survive a
container restart: `/backend/logs`, `/backend/notes`, `/backend/uploads`,
`/backend/fallback_music`, `/backend/token/` (Spotify and Microsoft Graph
OAuth tokens).
`CLAUDE_API_KEY` is not in the table: the backend does not read it. It is in
the registry with `services: ["python"]`, because the Python service is the
only container that uses it.
-5
View File
@@ -4,7 +4,6 @@ go 1.26
require (
github.com/99designs/gqlgen v0.17.95
github.com/anthropics/anthropic-sdk-go v1.26.0
github.com/gin-gonic/gin v1.11.0
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/gorilla/websocket v1.5.3
@@ -49,10 +48,6 @@ require (
github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.54.0 // indirect
github.com/sosodev/duration v1.4.0 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect
go.uber.org/mock v0.5.0 // indirect
-16
View File
@@ -37,8 +37,6 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
github.com/anthropics/anthropic-sdk-go v1.26.0 h1:oUTzFaUpAevfuELAP1sjL6CQJ9HHAfT7CoSYSac11PY=
github.com/anthropics/anthropic-sdk-go v1.26.0/go.mod h1:qUKmaW+uuPB64iy1l+4kOSvaLqPXnHTTBKH6RVZ7q5Q=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
@@ -60,8 +58,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
@@ -205,16 +201,6 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
@@ -522,8 +508,6 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
+14
View File
@@ -16,9 +16,23 @@ resolver:
filename_template: "{name}.resolvers.go"
models:
# Two bindings, tried in order. IntID comes first, so it is what gqlgen
# picks where it has a free choice — resolver arguments stay `id int`.
# UintID is there so a model's `ID uint` field binds to `id: ID!` directly,
# with no hand-written resolver converting it. Both write an id as a quoted
# decimal string ("12") and read a string or a number, so which one a field
# uses is invisible on the wire.
ID:
model:
- github.com/99designs/gqlgen/graphql.IntID
- github.com/99designs/gqlgen/graphql.UintID
# Bound to MarshalJobStatus / UnmarshalJobStatus in services, so the Go
# type stays `string` (models.JobApplication.Status binds as it is) and the
# marshaller, not a generated enum type, decides what is accepted and what
# is emitted. See services/job_status.go for why.
JobStatus:
model:
- adam-french.co.uk/backend/services.JobStatus
User:
model:
- adam-french.co.uk/backend/models.User
+3 -16
View File
@@ -7,24 +7,16 @@ package graph
import (
"context"
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// ID is the resolver for the id field.
func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, error) {
return int(obj.ID), nil
}
// CreateActivity is the resolver for the createActivity field.
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
// No middleware guards GraphQL, so each mutation checks for itself.
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
// Admin-only, but there is no check to see here: the field is marked
// @admin in the schema and the directive (directives.go) has already
// refused anyone else by the time this runs.
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
if err := r.Store.DB.Create(&activity).Error; err != nil {
return nil, err
@@ -41,8 +33,3 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
}
return ptrs(activities), nil
}
// Activity returns ActivityResolver implementation.
func (r *Resolver) Activity() ActivityResolver { return &activityResolver{r} }
type activityResolver struct{ *Resolver }
+3
View File
@@ -121,6 +121,9 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
// Me is the resolver for the me field.
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
// Checked here rather than with @signedIn because the message differs:
// this query has always answered "unauthorized", and the directive's is
// "authentication required".
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
-17
View File
@@ -7,22 +7,13 @@ package graph
import (
"context"
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// ID is the resolver for the id field.
func (r *bookmarkResolver) ID(ctx context.Context, obj *models.Bookmark) (int, error) {
return int(obj.ID), nil
}
// CreateBookmark is the resolver for the createBookmark field.
func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.CreateBookmarkInput) (*models.Bookmark, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
bookmark := models.Bookmark{Category: input.Category, Name: input.Name, Link: input.Link}
if err := r.Store.DB.Create(&bookmark).Error; err != nil {
return nil, err
@@ -32,9 +23,6 @@ func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.Creat
// DeleteBookmark is the resolver for the deleteBookmark field.
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
// Loaded first so the deleted record can be returned to the client, and
// so a missing id is a clean "not found" rather than a silent no-op.
// Delete is a soft delete: deleted_at is set and the row stays.
@@ -56,8 +44,3 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
}
return ptrs(bookmarks), nil
}
// Bookmark returns BookmarkResolver implementation.
func (r *Resolver) Bookmark() BookmarkResolver { return &bookmarkResolver{r} }
type bookmarkResolver struct{ *Resolver }
+12 -6
View File
@@ -27,7 +27,8 @@ const (
// UserClaimsFromCtx returns the verified JWT claims, or nil when the request
// is anonymous. nil means "not authenticated": a missing or invalid token is
// not an error here, because many queries are public.
// not an error here, because many queries are public. Turning "anonymous"
// into a refusal is the job of the schema directives, per field.
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
if !ok {
@@ -38,6 +39,10 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
// float64 because claims are decoded by encoding/json, hence the conversion.
//
// ok is also the test behind the @signedIn directive. A resolver calls this
// itself when it needs the id for more than a gate: to record a post's
// author, or to compare the caller with a row's owner.
func UserIDFromCtx(ctx context.Context) (uint, bool) {
claims := UserClaimsFromCtx(ctx)
if claims == nil {
@@ -50,11 +55,12 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
return uint(idF), true
}
// IsAdminFromCtx reports whether the request carries an admin token. This is
// the authorisation check for nearly every mutation — there is no middleware
// in front of the GraphQL endpoint, so a resolver that forgets to call this
// is public. Admin comes from the token, not the database, so a revoked admin
// flag only bites once the access token expires.
// IsAdminFromCtx reports whether the request carries an admin token. It is
// what the @admin directive tests (directives.go), which is how nearly every
// mutation is authorised; resolvers call it directly only for the softer
// cases a directive cannot express, such as the messages query filtering
// rather than refusing. Admin comes from the token, not the database, so a
// revoked admin flag only bites once the access token expires.
func IsAdminFromCtx(ctx context.Context) bool {
claims := UserClaimsFromCtx(ctx)
if claims == nil {
+63
View File
@@ -0,0 +1,63 @@
package graph
import (
"context"
"fmt"
"github.com/99designs/gqlgen/graphql"
)
// The schema's two authorisation directives. A field marked @admin or
// @signedIn in graph/schema/*.graphql has the matching function here run
// before its resolver; if it returns an error the resolver is never called
// and the error is what the client receives for that field.
//
// This replaces a check that used to be copied into the top of every guarded
// resolver. The rule itself is unchanged — it is the same IsAdminFromCtx /
// UserIDFromCtx test against the claims AuthContextMiddleware verified — but
// it is now declared next to the field, where a missing one can be seen and
// tested for (directives_test.go), instead of being a line someone has to
// remember to paste.
//
// The two error strings are part of the contract with the front end, which
// shows them as they are; the tracker page, for one, explains "admin access
// required" as a lapsed session. Do not reword them.
//
// This file is hand-written and never touched by gqlgen.
const (
errAdminRequired = "admin access required"
errSignedInRequired = "authentication required"
)
// Directives is the set gqlgen needs in graph.Config. It is a function so
// that main and the tests wire exactly the same implementations.
//
// Leaving a directive nil in the Config does not open the fields that use it:
// the generated code answers "directive admin is not implemented" for each.
func Directives() DirectiveRoot {
return DirectiveRoot{
Admin: requireAdmin,
SignedIn: requireSignedIn,
}
}
// requireAdmin implements @admin: the request must carry an access token
// whose admin claim is true. Admin comes from the token, not the database, so
// demoting a user only bites once their access token is replaced.
func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf(errAdminRequired)
}
return next(ctx)
}
// requireSignedIn implements @signedIn: any verified access token will do,
// admin or not. An admin is signed in, so this never needs pairing with
// @admin.
func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
if _, ok := UserIDFromCtx(ctx); !ok {
return nil, fmt.Errorf(errSignedInRequired)
}
return next(ctx)
}
+352
View File
@@ -0,0 +1,352 @@
package graph
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"sort"
"strings"
"testing"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/transport"
"github.com/golang-jwt/jwt/v5"
"github.com/vektah/gqlparser/v2/ast"
"adam-french.co.uk/backend/handlers"
)
// Authorisation is declared in the schema (@admin / @signedIn) and enforced
// by directives.go. These tests cover both halves: that the two functions
// decide correctly, and that the schema marks the fields it should — the
// second being the one that matters day to day, since the way this goes
// wrong is a new field added without a directive.
//
// Nothing here needs a database: a refused field never reaches its resolver,
// and the tests only ever drive fields that are refused or that return before
// touching the Store.
// withClaims builds the context AuthContextMiddleware would for a verified
// token. Claims are decoded from JSON in production, hence float64 for the id.
func withClaims(id float64, admin bool) context.Context {
claims := jwt.MapClaims{"id": id, "admin": admin}
return context.WithValue(context.Background(), userClaimsKey, &claims)
}
func TestDirectives(t *testing.T) {
anonymous := context.Background()
user := withClaims(2, false)
admin := withClaims(1, true)
// A token that verified but carries no id: not something GenerateJWT
// mints, but it must not count as signed in.
noID := func() context.Context {
claims := jwt.MapClaims{"admin": false}
return context.WithValue(context.Background(), userClaimsKey, &claims)
}()
cases := []struct {
name string
directive func(context.Context, any, graphql.Resolver) (any, error)
ctx context.Context
wantErr string // "" means the resolver must run
}{
{"@admin refuses an anonymous request", requireAdmin, anonymous, "admin access required"},
{"@admin refuses a signed-in non-admin", requireAdmin, user, "admin access required"},
{"@admin admits an admin", requireAdmin, admin, ""},
{"@signedIn refuses an anonymous request", requireSignedIn, anonymous, "authentication required"},
{"@signedIn refuses a token with no id", requireSignedIn, noID, "authentication required"},
{"@signedIn admits a non-admin", requireSignedIn, user, ""},
{"@signedIn admits an admin", requireSignedIn, admin, ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
called := false
next := func(ctx context.Context) (any, error) {
called = true
return "resolved", nil
}
res, err := c.directive(c.ctx, nil, next)
if c.wantErr == "" {
if err != nil || !called || res != "resolved" {
t.Fatalf("res = %v, err = %v, resolver called = %v; want the resolver's result", res, err, called)
}
return
}
// The exact strings are what the front end displays.
if err == nil || err.Error() != c.wantErr {
t.Fatalf("err = %v, want %q", err, c.wantErr)
}
if called {
t.Fatal("the resolver ran for a refused request")
}
if res != nil {
t.Fatalf("res = %v, want nil alongside the error", res)
}
})
}
}
// Directives() must supply every directive the schema declares; a nil one
// makes gqlgen fail each field that uses it.
func TestDirectivesAreAllImplemented(t *testing.T) {
d := Directives()
if d.Admin == nil || d.SignedIn == nil {
t.Fatal("Directives() left a directive unimplemented")
}
}
// guardOf reports which authorisation directive a field carries: "admin",
// "signedIn", or "" for none. Carrying both is a mistake (@signedIn adds
// nothing to @admin) and fails the test rather than being quietly accepted.
func guardOf(t *testing.T, field *ast.FieldDefinition) string {
t.Helper()
admin := field.Directives.ForName("admin") != nil
signedIn := field.Directives.ForName("signedIn") != nil
switch {
case admin && signedIn:
t.Errorf("%s carries both @admin and @signedIn", field.Name)
return "admin"
case admin:
return "admin"
case signedIn:
return "signedIn"
}
return ""
}
func schemaUnderTest() *ast.Schema {
return NewExecutableSchema(Config{}).Schema()
}
// publicMutations is the complete list of mutations that anyone may call.
// A mutation is public only by being named here, so adding one to the schema
// without a directive fails TestEveryMutationIsGuarded until it is either
// guarded or deliberately listed.
//
// All three are how a session is obtained or given up, so they cannot require
// one: login checks a password, refreshToken checks the refresh cookie, and
// logout is a no-op for a visitor who is not signed in.
var publicMutations = []string{"login", "logout", "refreshToken"}
func TestEveryMutationIsGuarded(t *testing.T) {
schema := schemaUnderTest()
var seen []string
for _, field := range schema.Mutation.Fields {
if strings.HasPrefix(field.Name, "__") {
continue
}
seen = append(seen, field.Name)
guard := guardOf(t, field)
public := slices.Contains(publicMutations, field.Name)
switch {
case guard == "" && !public:
t.Errorf("mutation %s has neither @admin nor @signedIn, so anyone can call it; "+
"add a directive in the schema, or add it to publicMutations if that is intended", field.Name)
case guard != "" && public:
t.Errorf("mutation %s is listed as public but carries @%s", field.Name, guard)
}
}
// A renamed or removed mutation must not leave a stale exemption behind.
for _, name := range publicMutations {
if !slices.Contains(seen, name) {
t.Errorf("publicMutations lists %s, which is not in the schema", name)
}
}
}
// The mutations that need only a session rather than an admin. Pinned so that
// loosening a mutation from @admin to @signedIn — which the test above would
// accept — has to be done here too.
func TestSignedInMutationsArePinned(t *testing.T) {
want := []string{"createPlace", "deletePlace", "updatePlace"}
var got []string
for _, field := range schemaUnderTest().Mutation.Fields {
if guardOf(t, field) == "signedIn" {
got = append(got, field.Name)
}
}
sort.Strings(got)
if !slices.Equal(got, want) {
t.Fatalf("@signedIn mutations = %v, want %v", got, want)
}
}
// Queries are public by default — the home page is built from them — so the
// rule cannot be "every field is guarded". Instead the guarded set is pinned
// exactly: removing a directive from one of these, or adding a query that
// exposes private data without one, has to be a visible change to this map.
//
// Three queries are sensitive to who is asking without being in it, because
// they answer rather than refuse: `me` returns "unauthorized" itself,
// `messages` filters out private rows for non-admins, and
// `spotifyNeedsReauth` is false for non-admins.
func TestGuardedQueriesArePinned(t *testing.T) {
want := map[string]string{
"users": "admin",
"user": "admin",
"jobApplications": "admin",
"jobApplication": "admin",
"jobAppReferences": "admin",
"places": "signedIn",
}
got := map[string]string{}
for _, field := range schemaUnderTest().Query.Fields {
if strings.HasPrefix(field.Name, "__") {
continue
}
if guard := guardOf(t, field); guard != "" {
got[field.Name] = guard
}
}
for name, guard := range want {
if got[name] != guard {
t.Errorf("query %s: guard = %q, want @%s", name, got[name], guard)
}
}
for name, guard := range got {
if _, ok := want[name]; !ok {
t.Errorf("query %s carries @%s but is not in the pinned list; add it there if the guard is intended", name, guard)
}
}
}
// The directives are FIELD_DEFINITION only and are meant for the two root
// types. One on an object's field would be enforced, but nothing above would
// notice it being removed, so keep them where the tests look.
func TestDirectivesOnlyOnRootFields(t *testing.T) {
schema := schemaUnderTest()
for name, def := range schema.Types {
if def == schema.Query || def == schema.Mutation || strings.HasPrefix(name, "__") {
continue
}
for _, field := range def.Fields {
if guardOf(t, field) != "" {
t.Errorf("%s.%s carries an authorisation directive outside Query/Mutation", name, field.Name)
}
}
}
}
// execute runs one operation through the real executable schema, wired the
// way main wires it, and returns the response's error messages. The Store is
// empty: every operation below is refused, or returns, before its resolver
// would touch the database.
func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string {
t.Helper()
srv := handler.New(NewExecutableSchema(Config{
Resolvers: &Resolver{Store: &handlers.Store{}},
Directives: Directives(),
}))
srv.AddTransport(transport.POST{})
body, err := json.Marshal(map[string]any{"query": query, "variables": variables})
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/graphql", bytes.NewReader(body)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, req)
var resp struct {
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decoding response %s: %v", rec.Body, err)
}
var messages []string
for _, e := range resp.Errors {
messages = append(messages, e.Message)
}
return messages
}
// End to end: the message a client receives for a refused field is the bare
// string the resolvers used to return, with nothing wrapped around it.
func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
cases := []struct {
name string
ctx context.Context
query string
want string
}{
{"anonymous admin query", context.Background(), `{ users { id } }`, "admin access required"},
{"non-admin admin query", withClaims(2, false), `{ jobApplications { id } }`, "admin access required"},
{"anonymous admin mutation", context.Background(), `mutation { deleteJobApplication(id: 1) }`, "admin access required"},
{"non-admin admin mutation", withClaims(2, false), `mutation { deleteUser(id: 1) { id } }`, "admin access required"},
{"anonymous signed-in query", context.Background(), `{ places { id } }`, "authentication required"},
{"anonymous signed-in mutation", context.Background(), `mutation { deletePlace(id: 1) { id } }`, "authentication required"},
// Not a directive, and a different message on purpose.
{"me keeps its own message", context.Background(), `{ me { id } }`, "unauthorized"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := execute(t, c.ctx, c.query, nil)
if !slices.Equal(got, []string{c.want}) {
t.Fatalf("errors = %q, want exactly %q", got, c.want)
}
})
}
}
// The JobStatus enum over the wire, from the side the tracker page uses it:
// status sent as a JSON string variable. A value in the vocabulary reaches the
// resolver (shown by the resolver's own validation error, which comes before
// any database access); one outside it is refused before the resolver runs.
func TestJobStatusInputOverTheWire(t *testing.T) {
const mutation = `mutation ($input: CreateJobApplicationInput!) { createJobApplication(input: $input) { id status } }`
admin := withClaims(1, true)
input := func(status any) map[string]any {
// A blank title makes the resolver return early, so no test here
// needs a database.
return map[string]any{"input": map[string]any{"jobTitle": " ", "company": "Acme", "status": status}}
}
for _, status := range []string{"saved", "applied", "screening", "assessment", "interviewing", "offer", "rejected", "withdrawn"} {
got := execute(t, admin, mutation, input(status))
if !slices.Equal(got, []string{"jobTitle and company are required"}) {
t.Errorf("status %q: errors = %q, want it accepted and the resolver reached", status, got)
}
}
for _, status := range []any{"hired", "Applied", "", " applied", 3} {
got := execute(t, admin, mutation, input(status))
if len(got) != 1 || got[0] == "jobTitle and company are required" {
t.Errorf("status %#v: errors = %q, want it refused before the resolver", status, got)
}
}
// The guard still comes first: an anonymous caller learns nothing about
// the vocabulary from a valid input.
if got := execute(t, context.Background(), mutation, input("applied")); !slices.Equal(got, []string{"admin access required"}) {
t.Errorf("anonymous: errors = %q", got)
}
}
// IDs: the wire form must be what it was when every type had a hand-written
// resolver returning int. Both marshallers write a quoted decimal string and
// both read a string or a number.
func TestUintIDWireFormatMatchesIntID(t *testing.T) {
for _, id := range []uint{0, 1, 12, 4294967295} {
var asUint, asInt bytes.Buffer
graphql.MarshalUintID(id).MarshalGQL(&asUint)
graphql.MarshalIntID(int(id)).MarshalGQL(&asInt)
if asUint.String() != asInt.String() {
t.Errorf("id %d: UintID writes %s, IntID wrote %s", id, &asUint, &asInt)
}
}
if got := func() string {
var b bytes.Buffer
graphql.MarshalUintID(12).MarshalGQL(&b)
return b.String()
}(); got != `"12"` {
t.Errorf("MarshalUintID(12) = %s, want \"12\"", got)
}
}
+30 -9
View File
@@ -9,8 +9,13 @@
// matching *.resolvers.go. Never edit those two generated files.
// - gqlgen.yml maps most GraphQL object types straight onto the GORM
// structs in backend/models, so model/ holds only input and payload
// types. That is also why almost every type has a hand-written ID
// resolver: model IDs are uint, GraphQL's Int is a Go int.
// types. A model's `ID uint` binds to `id: ID!` directly, because
// gqlgen.yml lists graphql.UintID for the ID scalar; no resolver is
// needed for it. A field resolver is only written where the Go type has
// no binding (Message.authorId and Rowing's time/distance are unsigned in
// Go and Int in the schema).
// - The JobStatus enum is bound to a custom marshaller in
// services/job_status.go rather than a generated type; see that file.
// - Resolvers reach the database and the third-party caches through
// Resolver.Store, the same handlers.Store the REST endpoints use.
// - context.go and middleware.go carry the caller's identity from Gin into
@@ -18,13 +23,29 @@
//
// Authorisation, which is the thing most likely to catch out a newcomer:
// there is NO middleware guarding this endpoint. AuthContextMiddleware only
// annotates the context and lets everything through, so each resolver checks
// for itself with IsAdminFromCtx or UserIDFromCtx. A resolver that omits that
// check is fully public. The rule of thumb in this schema is that queries are
// public and mutations are admin-only, with these exceptions: the job
// application and job reference queries are admin-only (they are private
// data), the places mutations need only a signed-in user, and the messages
// query hides private messages from non-admins rather than refusing.
// annotates the context and lets everything through. What guards a field is a
// directive on it in the schema:
//
// createUser(input: CreateUserInput!): User! @admin
// places: [Place!]! @signedIn
//
// @admin requires an admin's access token, @signedIn any valid one. Both are
// implemented once, in directives.go, and run before the resolver, so a
// guarded resolver contains no check of its own. A field with NEITHER
// directive is fully public.
//
// The rule of thumb in this schema is that queries are public and mutations
// are @admin, with these exceptions: login, logout and refreshToken are
// public; the places mutations and query are @signedIn; and the users, job
// application and job reference queries are @admin (they are private data).
// directives_test.go holds that list and fails when the schema departs from
// it — in particular when a mutation is added with no directive.
//
// A directive is only a gate. Anything finer stays in the resolver and uses
// IsAdminFromCtx / UserIDFromCtx directly: a post can only be edited by its
// author, `me` answers for the caller (with its own "unauthorized" error),
// the messages query hides private messages from non-admins rather than
// refusing, and spotifyNeedsReauth is simply false for non-admins.
//
// The files ending in _helpers.go are hand-written and are not touched by
// gqlgen; the *.resolvers.go files are partly generated, so anything added to
-15
View File
@@ -7,23 +7,13 @@ package graph
import (
"context"
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// ID is the resolver for the id field.
func (r *favoriteResolver) ID(ctx context.Context, obj *models.Favorite) (int, error) {
return int(obj.ID), nil
}
// CreateFavorite is the resolver for the createFavorite field.
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
if err := r.Store.DB.Create(&favorite).Error; err != nil {
return nil, err
@@ -40,8 +30,3 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
}
return ptrs(favorites), nil
}
// Favorite returns FavoriteResolver implementation.
func (r *Resolver) Favorite() FavoriteResolver { return &favoriteResolver{r} }
type favoriteResolver struct{ *Resolver }
+527 -515
View File
File diff suppressed because it is too large Load Diff
+6 -23
View File
@@ -7,22 +7,13 @@ package graph
import (
"context"
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// ID is the resolver for the id field.
func (r *jobAppReferenceResolver) ID(ctx context.Context, obj *models.JobAppReference) (int, error) {
return int(obj.ID), nil
}
// CreateJobAppReference is the resolver for the createJobAppReference field.
func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input model.CreateJobAppReferenceInput) (*models.JobAppReference, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
ref := models.JobAppReference{
Category: input.Category,
Label: input.Label,
@@ -39,9 +30,6 @@ func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input mode
// UpdateJobAppReference is the resolver for the updateJobAppReference field.
func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, input model.UpdateJobAppReferenceInput) (*models.JobAppReference, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var ref models.JobAppReference
if err := r.Store.DB.First(&ref, id).Error; err != nil {
return nil, err
@@ -66,10 +54,13 @@ func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, in
// DeleteJobAppReference is the resolver for the deleteJobAppReference field.
func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (bool, error) {
if !IsAdminFromCtx(ctx) {
return false, fmt.Errorf("admin access required")
// Loaded first so a missing id is an error rather than a `true` that
// deleted nothing; see DeleteJobApplication.
var ref models.JobAppReference
if err := r.Store.DB.First(&ref, id).Error; err != nil {
return false, err
}
if err := r.Store.DB.Delete(&models.JobAppReference{}, id).Error; err != nil {
if err := r.Store.DB.Delete(&ref).Error; err != nil {
return false, err
}
return true, nil
@@ -77,9 +68,6 @@ func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (b
// JobAppReferences is the resolver for the jobAppReferences field.
func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppReference, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var refs []*models.JobAppReference
// created_at is the final tie-break so entries sharing a sort_order (the
// default 0) keep a stable, insertion-ordered sequence.
@@ -88,8 +76,3 @@ func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppR
}
return refs, nil
}
// JobAppReference returns JobAppReferenceResolver implementation.
func (r *Resolver) JobAppReference() JobAppReferenceResolver { return &jobAppReferenceResolver{r} }
type jobAppReferenceResolver struct{ *Resolver }
+23 -31
View File
@@ -12,19 +12,10 @@ import (
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
)
// ID is the resolver for the id field.
func (r *jobApplicationResolver) ID(ctx context.Context, obj *models.JobApplication) (int, error) {
return int(obj.ID), nil
}
// CreateJobApplication is the resolver for the createJobApplication field.
func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model.CreateJobApplicationInput) (*models.JobApplication, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
// String! is non-null but not non-empty, and the columns are only
// `not null`, so "" stores happily and then never matches the email
// pipeline's LOWER(company) lookup — an orphan row no sync can advance.
@@ -33,12 +24,15 @@ func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model
if jobTitle == "" || company == "" {
return nil, fmt.Errorf("jobTitle and company are required")
}
// input.Status is already one of the JobStatus values: the enum's
// unmarshaller (services.UnmarshalJobStatus) refused anything else before
// this resolver was reached, so it is stored as it came.
app := models.JobApplication{
JobTitle: jobTitle,
Company: company,
Location: input.Location,
URL: input.URL,
Status: services.NormalizeStatus(input.Status),
Status: input.Status,
Notes: input.Notes,
AppliedAt: input.AppliedAt,
Description: input.Description,
@@ -51,9 +45,6 @@ func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model
// UpdateJobApplication is the resolver for the updateJobApplication field.
func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, input model.UpdateJobApplicationInput) (*models.JobApplication, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
// Partial update: every input field is a pointer so that "not supplied"
// is distinguishable from "set to empty". A nil field is left untouched.
// An explicit "" on a nullable column does clear it — that is how the UI
@@ -82,7 +73,7 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
app.URL = input.URL
}
if input.Status != nil {
app.Status = services.NormalizeStatus(*input.Status)
app.Status = *input.Status
}
if input.Notes != nil {
app.Notes = input.Notes
@@ -101,12 +92,19 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
// DeleteJobApplication is the resolver for the deleteJobApplication field.
func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bool, error) {
if !IsAdminFromCtx(ctx) {
return false, fmt.Errorf("admin access required")
// Loaded first so a missing id is an error, as it is for the deletes that
// return the row (deletePost, deletePlace, deleteBookmark). Deleting by
// id alone reports success whether or not anything matched, which told
// the tracker a row was gone when it had never existed. The return type
// stays Boolean! for the front end's sake, so the only value is true.
//
// Soft delete: the row is kept, which is what lets the email pipeline see
// that an application was deleted and not re-create it.
var app models.JobApplication
if err := r.Store.DB.First(&app, id).Error; err != nil {
return false, err
}
// Soft delete straight by id, without loading first — so deleting an id
// that does not exist still returns true.
if err := r.Store.DB.Delete(&models.JobApplication{}, id).Error; err != nil {
if err := r.Store.DB.Delete(&app).Error; err != nil {
return false, err
}
return true, nil
@@ -114,10 +112,12 @@ func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bo
// JobApplications is the resolver for the jobApplications field.
func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobApplication, error) {
// Admin-only even though it is a query: job applications are private.
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
// Admin-only even though it is a query (@admin in the schema): job
// applications are private.
//
// A row whose stored status is outside the JobStatus enum does not fail
// this list: services.MarshalJobStatus passes it through.
//
// Find can populate a slice of pointers directly, avoiding the
// copy-to-pointers loop the other list resolvers need.
var apps []*models.JobApplication
@@ -132,17 +132,9 @@ func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobAppli
// JobApplication is the resolver for the jobApplication field.
func (r *queryResolver) JobApplication(ctx context.Context, id int) (*models.JobApplication, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var app models.JobApplication
if err := r.Store.DB.First(&app, id).Error; err != nil {
return nil, err
}
return &app, nil
}
// JobApplication returns JobApplicationResolver implementation.
func (r *Resolver) JobApplication() JobApplicationResolver { return &jobApplicationResolver{r} }
type jobApplicationResolver struct{ *Resolver }
-5
View File
@@ -11,11 +11,6 @@ import (
"adam-french.co.uk/backend/models"
)
// ID is the resolver for the id field.
func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, error) {
return int(obj.ID), nil
}
// AuthorID is the resolver for the authorId field.
// AuthorID is the resolver for the authorId field. The value is the chat
// hub's per-connection counter, not a User id — see models.Message.
+4 -3
View File
@@ -13,9 +13,10 @@ import (
// It always attaches the *gin.Context, and attaches the JWT claims only when a
// valid access token is present. Crucially it never rejects a request: a
// missing, expired or forged token simply leaves the context anonymous, which
// is what lets public queries work and pushes every authorisation decision
// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify
// errors are swallowed for exactly that reason.
// is what lets public queries work and leaves every authorisation decision
// to the field being resolved — the @admin / @signedIn directives on it (see
// directives.go), or the resolver itself for anything finer. Both cookie and
// verify errors are swallowed for exactly that reason.
//
// It takes the database because validating a token means loading the user to
// compare token versions; see services.Auth.AuthenticateTokenWithClaims.
+3 -25
View File
@@ -7,7 +7,6 @@ package graph
import (
"context"
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
@@ -16,11 +15,9 @@ import (
// CreatePlace is the resolver for the createPlace field.
func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) {
// Any signed-in user, not just an admin — places are the one shared,
// collaboratively edited list on the site. There is no per-user
// ownership, so any signed-in user can edit or delete any place.
if _, ok := UserIDFromCtx(ctx); !ok {
return nil, fmt.Errorf("authentication required")
}
// collaboratively edited list on the site, so the schema marks these
// fields @signedIn rather than @admin. There is no per-user ownership, so
// any signed-in user can edit or delete any place.
place := models.Place{
Title: input.Title,
Location: input.Location,
@@ -43,9 +40,6 @@ func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePl
// UpdatePlace is the resolver for the updatePlace field.
func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) {
if _, ok := UserIDFromCtx(ctx); !ok {
return nil, fmt.Errorf("authentication required")
}
// Partial update, same pointer-means-supplied convention as job
// applications: nil fields are left as they are.
var place models.Place
@@ -84,9 +78,6 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.
// DeletePlace is the resolver for the deletePlace field.
func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Place, error) {
if _, ok := UserIDFromCtx(ctx); !ok {
return nil, fmt.Errorf("authentication required")
}
var place models.Place
if err := r.Store.DB.First(&place, id).Error; err != nil {
return nil, err
@@ -97,24 +88,11 @@ func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Pla
return &place, nil
}
// ID is the resolver for the id field.
func (r *placeResolver) ID(ctx context.Context, obj *models.Place) (int, error) {
return int(obj.ID), nil
}
// Places is the resolver for the places field.
func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
if _, ok := UserIDFromCtx(ctx); !ok {
return nil, fmt.Errorf("authentication required")
}
var places []models.Place
if err := r.Store.DB.Order("done ASC, priority DESC, created_at DESC").Find(&places).Error; err != nil {
return nil, err
}
return ptrs(places), nil
}
// Place returns PlaceResolver implementation.
func (r *Resolver) Place() PlaceResolver { return &placeResolver{r} }
type placeResolver struct{ *Resolver }
+6 -24
View File
@@ -15,10 +15,9 @@ import (
// CreatePost is the resolver for the createPost field.
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
// @admin has already established that there is a session; the id is read
// here because the post needs an author, not as a second gate. The !ok
// branch is only reachable with a token that has admin but no usable id.
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
@@ -34,10 +33,6 @@ func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePos
// UpdatePost is the resolver for the updatePost field.
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
@@ -48,8 +43,9 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
return nil, fmt.Errorf("post not found")
}
// Admin alone is not enough: a post may only be edited by its author, so
// one admin cannot rewrite another's posts.
// Admin alone (the @admin on the field) is not enough: a post may only be
// edited by its author, so one admin cannot rewrite another's posts. This
// is the kind of rule a directive cannot express, so it stays here.
if post.AuthorID != userID {
return nil, fmt.Errorf("you can only update your own posts")
}
@@ -67,10 +63,6 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
// DeletePost is the resolver for the deletePost field.
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
@@ -95,11 +87,6 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
return &post, nil
}
// ID is the resolver for the id field.
func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
return int(obj.ID), nil
}
// Posts is the resolver for the posts field.
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
// Preload issues a second query for the authors and fills in Post.Author.
@@ -120,8 +107,3 @@ func (r *queryResolver) Post(ctx context.Context, id int) (*models.Post, error)
}
return &post, nil
}
// Post returns PostResolver implementation.
func (r *Resolver) Post() PostResolver { return &postResolver{r} }
type postResolver struct{ *Resolver }
+6 -4
View File
@@ -12,10 +12,12 @@ import "adam-french.co.uk/backend/handlers"
// same handlers.Store the REST handlers use, so GraphQL and REST share one
// database handle and one set of third-party caches.
//
// The generated code embeds *Resolver in per-type resolver structs
// (queryResolver, mutationResolver, postResolver, ...), which is why those
// one-line `struct{ *Resolver }` declarations appear at the bottom of each
// resolvers file.
// The generated code embeds *Resolver in per-type resolver structs, which is
// why one-line `struct{ *Resolver }` declarations appear at the bottom of some
// resolvers files. A type only gets one when a field of it needs a resolver:
// queryResolver and mutationResolver always, messageResolver and
// rowingResolver for their unsigned-to-Int fields. Most object types bind
// every field straight to the model and have none.
type Resolver struct {
Store *handlers.Store
}
-5
View File
@@ -20,11 +20,6 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
return ptrs(rows), nil
}
// ID is the resolver for the id field.
func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error) {
return int(obj.ID), nil
}
// Time is the resolver for the time field.
// Time is the resolver for the time field: total session seconds, narrowed
// from uint64 to GraphQL's Int.
+1 -1
View File
@@ -18,5 +18,5 @@ extend type Query {
}
extend type Mutation {
createActivity(input: CreateActivityInput!): Activity!
createActivity(input: CreateActivityInput!): Activity! @admin
}
+4
View File
@@ -7,10 +7,14 @@ type AuthPayload {
user: User!
}
# `me` carries no directive although it needs a session: it answers
# "unauthorized", not @signedIn's "authentication required", and the front end
# relies on that query failing quietly for an anonymous visitor.
extend type Query {
me: User
}
# Deliberately public: these are how a session is obtained and given up.
extend type Mutation {
login(input: LoginInput!): AuthPayload!
logout: Boolean!
+2 -2
View File
@@ -18,6 +18,6 @@ extend type Query {
}
extend type Mutation {
createBookmark(input: CreateBookmarkInput!): Bookmark!
deleteBookmark(id: ID!): Bookmark!
createBookmark(input: CreateBookmarkInput!): Bookmark! @admin
deleteBookmark(id: ID!): Bookmark! @admin
}
+1 -1
View File
@@ -18,5 +18,5 @@ extend type Query {
}
extend type Mutation {
createFavorite(input: CreateFavoriteInput!): Favorite!
createFavorite(input: CreateFavoriteInput!): Favorite! @admin
}
@@ -1,3 +1,6 @@
# Reusable snippets for filling in application forms. Private, like the
# applications themselves, so the query is @admin as well as the mutations.
type JobAppReference {
id: ID!
createdAt: Time!
@@ -23,11 +26,13 @@ input UpdateJobAppReferenceInput {
}
extend type Query {
jobAppReferences: [JobAppReference!]!
jobAppReferences: [JobAppReference!]! @admin
}
extend type Mutation {
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference!
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference!
deleteJobAppReference(id: ID!): Boolean!
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference! @admin
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference! @admin
# Errors on an id that does not exist, like the other deletes; the Boolean
# is only ever true.
deleteJobAppReference(id: ID!): Boolean! @admin
}
+36 -14
View File
@@ -1,16 +1,36 @@
# Job application tracker. Rows come from these mutations, automatically from
# the email sync pipeline (backend/services/email_sync.go), or from the browser
# capture userscript (backend/handlers/handle_job_capture.go). These are
# private data, so the queries here are admin-only as well as the mutations.
#
# status is a free-form String, but only the values ranked in
# services.statusOrder can be advanced automatically by the email pipeline:
# saved, applied, screening, assessment, interviewing, offer, rejected,
# withdrawn.
# private data, so the queries here are @admin as well as the mutations.
#
# description is the captured posting text. It can run to tens of kilobytes,
# so the tracker's list query leaves it out and asks for it per row.
# The lifecycle of an application, in the order the email pipeline and the
# capture endpoint are allowed to advance it. The values are lowercase on
# purpose: they are exactly the strings stored in the status column and ranked
# in services.statusOrder (backend/services/email_sync.go), and a test there
# fails if this list and that map ever differ. Adding a status means adding
# it in both places, and to the tracker page and the capture userscript.
#
# It is bound to a custom marshaller (services/job_status.go, via gqlgen.yml)
# rather than a generated Go type: input is strict, so a mutation carrying a
# status outside this list is refused, while output passes a legacy stored
# value through so one old row cannot fail the whole jobApplications query.
#
# On the wire it is still a JSON string ("applied"), as it was when the field
# was a String, both in variables and in responses.
enum JobStatus {
saved
applied
screening
assessment
interviewing
offer
rejected
withdrawn
}
type JobApplication {
id: ID!
createdAt: Time!
@@ -19,7 +39,7 @@ type JobApplication {
company: String!
location: String
url: String
status: String!
status: JobStatus!
notes: String
appliedAt: Time
description: String
@@ -30,7 +50,7 @@ input CreateJobApplicationInput {
company: String!
location: String
url: String
status: String!
status: JobStatus!
notes: String
appliedAt: Time
description: String
@@ -41,19 +61,21 @@ input UpdateJobApplicationInput {
company: String
location: String
url: String
status: String
status: JobStatus
notes: String
appliedAt: Time
description: String
}
extend type Query {
jobApplications: [JobApplication!]!
jobApplication(id: ID!): JobApplication
jobApplications: [JobApplication!]! @admin
jobApplication(id: ID!): JobApplication @admin
}
extend type Mutation {
createJobApplication(input: CreateJobApplicationInput!): JobApplication!
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication!
deleteJobApplication(id: ID!): Boolean!
createJobApplication(input: CreateJobApplicationInput!): JobApplication! @admin
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication! @admin
# Errors on an id that does not exist, like the other deletes; the Boolean
# is only ever true.
deleteJobApplication(id: ID!): Boolean! @admin
}
+2 -1
View File
@@ -3,7 +3,8 @@
#
# Two gotchas: authorId is a per-connection counter from the chat hub, not a
# User id, and private messages are silently filtered out for non-admins
# rather than causing an error.
# rather than causing an error — which is why the query has no @admin: the
# resolver makes that decision per row.
type Message {
id: ID!
+7 -6
View File
@@ -1,5 +1,6 @@
# Places to go. Unlike most mutations these require only a signed-in user,
# not an admin, and there is no per-user ownership: the list is shared.
# Places to go. Unlike most mutations these require only a signed-in user
# (@signedIn), not an admin, and there is no per-user ownership: the list is
# shared. The query is guarded too — the list is not public.
type Place {
id: ID!
@@ -38,11 +39,11 @@ input UpdatePlaceInput {
}
extend type Query {
places: [Place!]!
places: [Place!]! @signedIn
}
extend type Mutation {
createPlace(input: CreatePlaceInput!): Place!
updatePlace(id: ID!, input: UpdatePlaceInput!): Place!
deletePlace(id: ID!): Place!
createPlace(input: CreatePlaceInput!): Place! @signedIn
updatePlace(id: ID!, input: UpdatePlaceInput!): Place! @signedIn
deletePlace(id: ID!): Place! @signedIn
}
+5 -3
View File
@@ -22,8 +22,10 @@ extend type Query {
post(id: ID!): Post
}
# @admin is only the first half of the rule for updatePost and deletePost:
# the resolver also requires the caller to be the post's author.
extend type Mutation {
createPost(input: CreatePostInput!): Post!
updatePost(id: ID!, input: UpdatePostInput!): Post!
deletePost(id: ID!): Post!
createPost(input: CreatePostInput!): Post! @admin
updatePost(id: ID!, input: UpdatePostInput!): Post! @admin
deletePost(id: ID!): Post! @admin
}
+17
View File
@@ -16,5 +16,22 @@
scalar Time
# Authorisation. There is no middleware in front of /graphql, so a field is
# PUBLIC unless it carries one of these. Each is implemented once, in
# graph/directives.go, and runs before the field's resolver:
#
# @admin the request must carry an admin's access token
# (error: "admin access required")
# @signedIn any valid access token will do
# (error: "authentication required")
#
# Every mutation needs one of them unless it is deliberately public (login,
# logout, refreshToken); graph/directives_test.go fails otherwise, and pins
# which queries are guarded. Rules that are not a plain gate stay in the
# resolver: a post is only editable by its author, `me` answers for whoever is
# signed in, and `messages` filters private rows rather than refusing.
directive @admin on FIELD_DEFINITION
directive @signedIn on FIELD_DEFINITION
type Query
type Mutation
+2 -1
View File
@@ -36,6 +36,7 @@ extend type Query {
spotifyRecent: [SpotifyRecentItem!]
# True only for an admin session while the backend lacks a Spotify client
# (OAuth never completed or the token was revoked), used by the Listening
# widget to offer a reconnect link. Everyone else gets false.
# widget to offer a reconnect link. Everyone else gets false — a soft
# check in the resolver, not @admin, so the home page query never errors.
spotifyNeedsReauth: Boolean!
}
+5 -5
View File
@@ -12,12 +12,12 @@ input CreateUserInput {
}
extend type Query {
users: [User!]!
user(id: ID!): User
users: [User!]! @admin
user(id: ID!): User @admin
}
extend type Mutation {
createUser(input: CreateUserInput!): User!
deleteUser(id: ID!): User!
setUserAdmin(id: ID!, admin: Boolean!): User!
createUser(input: CreateUserInput!): User! @admin
deleteUser(id: ID!): User! @admin
setUserAdmin(id: ID!, admin: Boolean!): User! @admin
}
+2
View File
@@ -61,6 +61,8 @@ func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
return false, nil
}
// A soft check, deliberately not @admin: the directive would turn this
// into an error on the public home page query.
if !IsAdminFromCtx(ctx) {
return false, nil
}
+3 -30
View File
@@ -16,12 +16,9 @@ import (
// CreateUser is the resolver for the createUser field.
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
// Only an existing admin can create accounts — there is no public
// sign-up. New users are created non-admin; setUserAdmin promotes them.
// Only an existing admin can create accounts (@admin in the schema) —
// there is no public sign-up. New users are created non-admin;
// setUserAdmin promotes them.
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
if err != nil {
return nil, err
@@ -37,10 +34,6 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse
// DeleteUser is the resolver for the deleteUser field.
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
@@ -55,10 +48,6 @@ func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User
// SetUserAdmin is the resolver for the setUserAdmin field.
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
callerID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
@@ -85,9 +74,6 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
// Users is the resolver for the users field.
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var users []models.User
if err := r.Store.DB.Find(&users).Error; err != nil {
return nil, err
@@ -97,22 +83,9 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
// User is the resolver for the user field.
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
}
return &user, nil
}
// ID is the resolver for the id field.
func (r *userResolver) ID(ctx context.Context, obj *models.User) (int, error) {
return int(obj.ID), nil
}
// User returns UserResolver implementation.
func (r *Resolver) User() UserResolver { return &userResolver{r} }
type userResolver struct{ *Resolver }
+7 -54
View File
@@ -1,12 +1,8 @@
package handlers
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
@@ -20,7 +16,7 @@ import (
"gorm.io/gorm"
)
// Job capture: the three endpoints behind userscripts/job-capture.user.js,
// Job capture: the three endpoints behind vue/public/job-capture.user.js,
// which adds the posting open in the browser to the job tracker.
//
// These are REST, and token-authenticated, because the caller is a userscript
@@ -51,10 +47,6 @@ const (
maxPageRunes = 40_000
)
// jobExtractClient bounds the wait on the Python service; see
// rowingReadClient for why two minutes.
var jobExtractClient = &http.Client{Timeout: 2 * time.Minute}
// CaptureTokenMiddleware guards the capture routes with the token generated
// in the admin panel (services.CaptureToken), presented as
// "Authorization: Bearer <token>".
@@ -250,55 +242,16 @@ type ExtractedJobPosting struct {
Notes *string `json:"notes"`
}
// postingReadError is a failure the Python service reported in words that are
// safe to show in the capture popup (its 502 detail); the job-capture
// counterpart of displayReadError.
type postingReadError struct{ detail string }
func (e *postingReadError) Error() string { return e.detail }
// extractJobPosting sends a page's text to the Python service and returns the
// fields Claude picked out. It mirrors readRowingDisplay, including which
// replies are relayed and which are only logged.
// fields Claude picked out. Like readRowingDisplay it is a thin wrapper over
// services.CallPython, which decides which replies are relayed (a
// *services.PythonError) and which are only logged.
func (store *Store) extractJobPosting(ctx context.Context, pageURL, title, text string) (ExtractedJobPosting, error) {
var posting ExtractedJobPosting
body, err := json.Marshal(struct {
return services.CallPython[ExtractedJobPosting](ctx, store.PythonURL, jobExtractPath, struct {
URL string `json:"url"`
Title string `json:"title"`
Text string `json:"text"`
}{pageURL, title, text})
if err != nil {
return posting, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, store.PythonURL+jobExtractPath, bytes.NewReader(body))
if err != nil {
return posting, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := jobExtractClient.Do(req)
if err != nil {
return posting, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var failure struct {
Detail string `json:"detail"`
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
return posting, &postingReadError{detail: failure.Detail}
}
return posting, fmt.Errorf("job extractor returned %d: %s", resp.StatusCode, raw)
}
if err := json.NewDecoder(resp.Body).Decode(&posting); err != nil {
return posting, fmt.Errorf("decoding job extractor response: %w", err)
}
return posting, nil
}
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
@@ -344,9 +297,9 @@ func (store *Store) JobCaptureExtract(ctx *gin.Context) {
truncateRunes(input.URL, 2000), truncateRunes(input.Title, 500), truncateRunes(text, maxPageRunes))
if err != nil {
log.Println("Job extract failed:", err)
var readErr *postingReadError
var readErr *services.PythonError
if errors.As(err, &readErr) {
ctx.JSON(http.StatusBadGateway, gin.H{"error": readErr.detail})
ctx.JSON(http.StatusBadGateway, gin.H{"error": readErr.Detail})
return
}
ctx.JSON(http.StatusBadGateway, gin.H{"error": "failed to read the page"})
+4 -4
View File
@@ -308,7 +308,7 @@ func TestExtractJobPostingErrors(t *testing.T) {
name string
status int
body string
wantDetail string // non-empty: a postingReadError with this message
wantDetail string // non-empty: a services.PythonError with this message
}{
{"extractor failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse the posting"}`, "failed to parse the posting"},
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
@@ -325,12 +325,12 @@ func TestExtractJobPostingErrors(t *testing.T) {
if err == nil {
t.Fatal("expected an error")
}
var readErr *postingReadError
var readErr *services.PythonError
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
t.Fatalf("relayed = %v, err = %v", relayed, err)
}
if readErr != nil && readErr.detail != c.wantDetail {
t.Fatalf("detail = %q, want %q", readErr.detail, c.wantDetail)
if readErr != nil && readErr.Detail != c.wantDetail {
t.Fatalf("detail = %q, want %q", readErr.Detail, c.wantDetail)
}
})
}
+10 -60
View File
@@ -1,19 +1,16 @@
package handlers
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/rwcarlsen/goexif/exif"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
@@ -39,68 +36,21 @@ type ExtractedRowingData struct {
// rowingReadPath is the Python route. It is internal: nginx refuses
// /py/internal/ and the route itself refuses anything nginx forwarded, so the
// only way in is this direct container-to-container call.
// only way in is the direct container-to-container call services.CallPython
// makes.
const rowingReadPath = "/internal/rowing/read"
// rowingReadClient bounds the wait on the Python service. Two minutes sits
// above that side's own worst case (a 30s Claude timeout, retried twice with
// backoff), so a slow Claude surfaces as Python's error rather than as a
// timeout here.
var rowingReadClient = &http.Client{Timeout: 2 * time.Minute}
// displayReadError is a failure the Python service reported in words that are
// safe and useful to show the admin (its 502 detail), as opposed to a
// transport or decoding failure, which is only logged.
type displayReadError struct{ detail string }
func (e *displayReadError) Error() string { return e.detail }
// readRowingDisplay sends the image to the Python service and returns what
// Claude read off it. No plausibility checking happens on either side of this
// call; that is CreateRowing's job.
// call; that is CreateRowing's job. A failure the reader described in its own
// words comes back as a *services.PythonError (see services.CallPython).
func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) {
var extracted ExtractedRowingData
// encoding/json writes a []byte as standard base64, which is the form the
// Anthropic API wants and so what the Python side passes straight through.
body, err := json.Marshal(struct {
// Data is a []byte so that it is sent as standard base64, the encoding
// the Anthropic API expects.
return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct {
MediaType string `json:"media_type"`
Data []byte `json:"data"`
}{mediaType, image})
if err != nil {
return extracted, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, store.PythonURL+rowingReadPath, bytes.NewReader(body))
if err != nil {
return extracted, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := rowingReadClient.Do(req)
if err != nil {
return extracted, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
// FastAPI errors are {"detail": ...}. Only a 502 carries one of the
// reader's own fixed messages; a 422's detail is a list, which fails
// to decode into the string and falls through to the generic error.
var failure struct {
Detail string `json:"detail"`
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
return extracted, &displayReadError{detail: failure.Detail}
}
return extracted, fmt.Errorf("rowing reader returned %d: %s", resp.StatusCode, raw)
}
if err := json.NewDecoder(resp.Body).Decode(&extracted); err != nil {
return extracted, fmt.Errorf("decoding rowing reader response: %w", err)
}
return extracted, nil
}
// GetRowing backs the public GET /rowing with every logged session, newest
@@ -219,9 +169,9 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
// passed on; anything else is a plumbing failure the admin can do
// nothing with.
msg := "failed to process image"
var readErr *displayReadError
var readErr *services.PythonError
if errors.As(err, &readErr) {
msg = readErr.detail
msg = readErr.Detail
}
ctx.JSON(http.StatusInternalServerError, gin.H{"error": msg})
return
+6 -4
View File
@@ -7,6 +7,8 @@ import (
"net/http"
"net/http/httptest"
"testing"
"adam-french.co.uk/backend/services"
)
// readRowingDisplay is the Go half of the contract with the Python service's
@@ -63,7 +65,7 @@ func TestReadRowingDisplayErrors(t *testing.T) {
name string
status int
body string
wantDetail string // non-empty: a displayReadError with this message
wantDetail string // non-empty: a services.PythonError with this message
}{
{"reader failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"},
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
@@ -82,12 +84,12 @@ func TestReadRowingDisplayErrors(t *testing.T) {
if err == nil {
t.Fatal("expected an error")
}
var readErr *displayReadError
var readErr *services.PythonError
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
t.Fatalf("relayed = %v, err = %v", relayed, err)
}
if readErr != nil && readErr.detail != c.wantDetail {
t.Fatalf("detail = %q, want %q", readErr.detail, c.wantDetail)
if readErr != nil && readErr.Detail != c.wantDetail {
t.Fatalf("detail = %q, want %q", readErr.Detail, c.wantDetail)
}
})
}
+4 -2
View File
@@ -35,8 +35,10 @@ type Store struct {
EmailSync *services.EmailSyncService
// Base URL of the Python service on the Docker network, no trailing
// slash. Used for the calls that bypass nginx: reading a rowing display
// photo (handle_rowing.go) and a job posting (handle_job_capture.go).
// slash. Used for the calls that bypass nginx, all through
// services.CallPython: reading a rowing display photo (handle_rowing.go)
// and a job posting (handle_job_capture.go). The email pipeline makes the
// third such call and holds its own copy of this value.
PythonURL string
// Bearer token for the browser capture routes (handle_job_capture.go),
+23 -16
View File
@@ -27,8 +27,9 @@ import (
// setting from the environment, builds the services, packs them into one
// handlers.Store, and registers the routes. There are three route groups —
// open, `protected` (valid access token) and `admin` (token with admin=true)
// — plus the GraphQL endpoint, which does its own per-resolver authorisation
// instead of using middleware. See backend/README.md for the wider picture.
// — plus the GraphQL endpoint, which is authorised by the @admin / @signedIn
// directives in its schema instead of by middleware. See backend/README.md
// for the wider picture.
func main() {
// Logs go to both stdout (so `docker compose logs` works) and a file in a
// mounted volume (so they survive the container).
@@ -89,12 +90,10 @@ func main() {
spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
// CLAUDE
// Only the email pipeline uses this client now; the rowing photo reader's
// Claude call moved to the Python service, which reads the same key.
claudeAPIKey := os.Getenv("CLAUDE_API_KEY")
claudeConfig := services.ClaudeConfig{APIKey: claudeAPIKey}
claudeClient := services.InitClaude(&claudeConfig)
// No Claude client here: every Claude call — the rowing photo reader, the
// job posting reader and the email classifier — is made by the Python
// service, which is the only container that reads CLAUDE_API_KEY. The
// backend reaches those routes at pythonURL, below.
authSecret := os.Getenv("BACKEND_SECRET")
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
@@ -117,9 +116,9 @@ func main() {
steamID := os.Getenv("STEAM_ID")
// PYTHON SERVICE
// Called directly over the Docker network, not through nginx, for the
// rowing photo reader. The defaults mirror docker-compose.yml, where both
// variables are optional.
// Called directly over the Docker network, not through nginx, for its
// three /internal/ Claude routes (services/python_call.go). The defaults
// mirror docker-compose.yml, where both variables are optional.
pythonHost := os.Getenv("PYTHON_HOST")
if pythonHost == "" {
pythonHost = "python"
@@ -154,7 +153,7 @@ func main() {
SyncInterval: emailSyncInterval,
Enabled: os.Getenv("EMAIL_SYNC_ENABLED") == "true",
}
emailSync := services.InitEmailSync(&emailSyncConfig, db, claudeClient)
emailSync := services.InitEmailSync(&emailSyncConfig, db, pythonURL)
// 5 login attempts per IP per minute, applied by both the REST handler
// and the GraphQL login mutation. Nginx rate-limits the login route too.
@@ -251,11 +250,19 @@ func main() {
// GraphQL is assembled by hand rather than with handler.NewDefaultServer
// so the transports and extensions below are explicit.
//
// Note the whole API is one POST route with no middleware guard:
// authorisation happens per resolver via IsAdminFromCtx / UserIDFromCtx,
// so a new resolver is PUBLIC until it checks for itself.
// Note the whole API is one POST route with no middleware guard.
// Authorisation is declared in the schema instead: a field marked @admin
// or @signedIn is refused by the matching function in graph.Directives()
// before its resolver runs. A field with neither is PUBLIC, so a new
// mutation needs one — graph/directives_test.go fails until it has one or
// is added to the list of deliberately public fields there.
//
// Directives must stay wired here: gqlgen fails closed on a nil directive
// (the field errors with "directive admin is not implemented"), so
// dropping this line breaks every guarded field rather than opening it.
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
Resolvers: &graph.Resolver{Store: &store},
Resolvers: &graph.Resolver{Store: &store},
Directives: graph.Directives(),
}))
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
gqlSrv.AddTransport(transport.Options{})
+12 -7
View File
@@ -20,8 +20,9 @@ import (
// every subsequent query silently filters those rows out. Rows are never
// actually removed, and a uniqueIndex still sees deleted rows, so a
// soft-deleted username cannot be reused.
// - IDs are uint in Go but Int in GraphQL, which is why nearly every type
// has a hand-written ID resolver doing int(obj.ID).
// - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the
// two directly (graphql.UintID), so an `ID uint` field needs no resolver.
// On the wire an id is a quoted decimal string, "12".
// User is an account. There is no public sign-up: users are created by an
// existing admin through the createUser mutation, or by the dev seeder.
@@ -210,11 +211,15 @@ type Place struct {
// through GraphQL, automatically by the email pipeline, or from the browser
// by the capture userscript (handlers/handle_job_capture.go).
//
// Status is a free-form string, but only the values ranked in
// services.statusOrder ("saved", "applied", "screening", "assessment",
// "interviewing", "offer", "rejected", "withdrawn") can be advanced
// automatically; the pipeline matches an existing application on
// (Company, JobTitle) compared case-insensitively.
// Status is a plain string column, but its vocabulary is fixed: the values
// ranked in services.statusOrder ("saved", "applied", "screening",
// "assessment", "interviewing", "offer", "rejected", "withdrawn"), which the
// GraphQL schema repeats as `enum JobStatus`. Every writer keeps to it —
// GraphQL refuses anything else, the email pipeline and the capture endpoint
// coerce with services.NormalizeStatus — but the column predates that, so a
// reader must not assume an old row conforms (services.MarshalJobStatus does
// not). The pipeline matches an existing application on (Company, JobTitle)
// compared case-insensitively.
//
// Description is the posting's text as captured from the page, kept because
// postings are usually taken down long before the interview. It is large, so
+3 -1
View File
@@ -18,7 +18,9 @@ import (
func testAuth() *Auth {
return InitAuth(&AuthConfig{
Secret: []byte("test-secret"),
// InitAuth panics on anything under 32 bytes, so the fixture has to be
// a realistic length even though nothing here depends on its value.
Secret: []byte("test-secret-0123456789abcdef0123456789"),
Domain: "example.test",
AccessTokenLifetime: time.Hour,
RefreshTokenLifetime: 24 * time.Hour,
-25
View File
@@ -1,25 +0,0 @@
package services
import (
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
// ClaudeConfig holds the Anthropic API credentials.
type ClaudeConfig struct {
APIKey string
}
// InitClaude builds the Anthropic client used to classify job-application
// emails (EmailSyncService.processEmail). The other Claude caller, the rowing
// photo reader, lives in the Python service and builds its own client from
// the same CLAUDE_API_KEY.
//
// No validation happens here: with an empty or wrong API key construction
// still succeeds and the failure only surfaces on the first request.
func InitClaude(config *ClaudeConfig) *anthropic.Client {
// anthropic.NewClient returns a value, not a pointer, so take its address
// so it can be handed around without copying.
client := anthropic.NewClient(option.WithAPIKey(config.APIKey))
return &client
}
+185
View File
@@ -0,0 +1,185 @@
package services
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"unicode/utf8"
)
// The classify step of the email pipeline: the request the Python service's
// /internal/email/classify receives, and what processEmail does with each
// kind of reply. A stub server stands in for Python.
//
// processEmail is driven only as far as it can go without a database. That
// covers every failure (they all return before the first query) and the two
// "nothing to do" answers; an email that is about a job goes on to look the
// application up, which needs Postgres and is not exercised here.
func classifierStub(t *testing.T, handler http.HandlerFunc) *EmailSyncService {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
return &EmailSyncService{PythonURL: srv.URL}
}
func testEmail() graphMessage {
email := graphMessage{
ID: "msg-1",
Subject: "Your application to Acme",
ReceivedDateTime: "2026-03-15T10:30:00Z",
Body: graphBody{ContentType: "html", Content: "<p>Thanks&nbsp;for applying</p>"},
}
email.From.EmailAddress = graphEmailAddress{Name: "Acme Hiring", Address: "[email protected]"}
return email
}
func TestClassifyEmailRequest(t *testing.T) {
var path string
var body map[string]any
s := classifierStub(t, func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decoding request: %v", err)
}
w.Write([]byte(`{"isJobEmail": true, "action": "create", "company": "Acme", "jobTitle": "Engineer",
"status": "applied", "location": "London", "url": null, "appliedAt": "2026-03-15", "notes": null}`))
})
analysis, err := s.classifyEmail(context.Background(), testEmail())
if err != nil {
t.Fatalf("classifyEmail: %v", err)
}
if path != "/internal/email/classify" {
t.Fatalf("path = %q", path)
}
// The whole contract: one key, holding the headers, a blank line and the
// cleaned body. The Python side hands this string to Claude unchanged.
want := "Subject: Your application to Acme\nFrom: Acme Hiring <[email protected]>\nDate: 2026-03-15T10:30:00Z\n\nThanks for applying"
if len(body) != 1 || body["message"] != want {
t.Fatalf("request body = %v\nwant message %q", body, want)
}
if !analysis.IsJobEmail || analysis.Action != "create" || analysis.Company != "Acme" ||
analysis.JobTitle != "Engineer" || analysis.Status != "applied" {
t.Fatalf("analysis = %+v", analysis)
}
if analysis.Location == nil || *analysis.Location != "London" || analysis.URL != nil ||
analysis.AppliedAt == nil || *analysis.AppliedAt != "2026-03-15" || analysis.Notes != nil {
t.Fatalf("nullable fields = %+v", analysis)
}
}
func TestProcessEmailWithoutAJob(t *testing.T) {
cases := []struct {
name string
reply string
}{
// What Python sends for a non-job email: every other field defaulted.
{"not a job email", `{"isJobEmail": false, "action": "", "company": "", "jobTitle": "", "status": "",
"location": null, "url": null, "appliedAt": null, "notes": null}`},
// (company, job title) is the only key an application has, so an
// answer missing either cannot be matched or created.
{"a job email with no company", `{"isJobEmail": true, "action": "create", "company": "", "jobTitle": "Engineer", "status": "applied"}`},
{"a job email with no title", `{"isJobEmail": true, "action": "create", "company": "Acme", "jobTitle": "", "status": "applied"}`},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := classifierStub(t, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(c.reply))
})
action, jobAppID, err := s.processEmail(context.Background(), testEmail())
if err != nil || action != "skipped" || jobAppID != nil {
t.Fatalf("processEmail = (%q, %v, %v), want (skipped, nil, nil)", action, jobAppID, err)
}
})
}
}
// Every way the classifier can fail must come back from processEmail as an
// error with no action: that is what makes SyncEmails record the email as
// Action "error" with one more attempt used, to be retried next sync.
func TestProcessEmailClassifierFailures(t *testing.T) {
cases := []struct {
name string
status int
body string
wantRelayed string // the 502 detail, when there is one
}{
{"Claude failed", http.StatusBadGateway, `{"detail": "failed to classify the email"}`, "failed to classify the email"},
{"Claude's reply was unparseable", http.StatusBadGateway, `{"detail": "failed to parse the email classification"}`, "failed to parse the email classification"},
{"no API key", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
{"request rejected", http.StatusUnprocessableEntity, `{"detail": [{"msg": "too long"}]}`, ""},
{"malformed 200 body", http.StatusOK, `not json`, ""},
{"200 body of the wrong shape", http.StatusOK, `{"isJobEmail": "yes"}`, ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := classifierStub(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(c.status)
w.Write([]byte(c.body))
})
action, jobAppID, err := s.processEmail(context.Background(), testEmail())
if err == nil {
t.Fatal("expected an error")
}
if action != "" || jobAppID != nil {
t.Fatalf("processEmail = (%q, %v) alongside an error", action, jobAppID)
}
// Not a cancellation: SyncEmails skips those without recording
// anything, which would leave a real failure retried for ever.
if errors.Is(err, context.Canceled) {
t.Fatalf("err = %v reads as a cancelled sync", err)
}
var pyErr *PythonError
if errors.As(err, &pyErr) != (c.wantRelayed != "") {
t.Fatalf("err = %v, want PythonError: %v", err, c.wantRelayed != "")
}
if pyErr != nil && pyErr.Detail != c.wantRelayed {
t.Fatalf("detail = %q, want %q", pyErr.Detail, c.wantRelayed)
}
})
}
}
// The other half of the rule above: a sync abandoned mid-call (the admin
// closed the tab) must be recognisable, so the email's attempts do not advance.
func TestProcessEmailCancelled(t *testing.T) {
s := classifierStub(t, func(http.ResponseWriter, *http.Request) {})
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, _, err := s.processEmail(ctx, testEmail()); !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want it to wrap context.Canceled", err)
}
}
func TestClassifierMessageIsCapped(t *testing.T) {
// An ordinary email is nowhere near the cap and is not touched.
if got := classifierMessage(testEmail()); !strings.HasSuffix(got, "\n\nThanks for applying") {
t.Fatalf("message = %q", got)
}
// cleanEmailBody bounds the body, so only the headers can push a message
// over. Multi-byte runes: the cap counts characters, as the Python side
// does, and the cut must not split one.
long := testEmail()
long.Subject = strings.Repeat("é", maxClassifyRunes+50)
got := classifierMessage(long)
if n := utf8.RuneCountInString(got); n != maxClassifyRunes {
t.Fatalf("message is %d runes, want %d", n, maxClassifyRunes)
}
if !utf8.ValidString(got) {
t.Fatal("the cut split a rune")
}
// More bytes than the cap but fewer runes: within the limit, so intact.
wide := testEmail()
wide.Subject = strings.Repeat("é", maxClassifyRunes/2+10)
if got := classifierMessage(wide); !strings.HasSuffix(got, "\n\nThanks for applying") {
t.Fatal("a message under the rune cap was cut")
}
}
+2 -2
View File
@@ -6,8 +6,8 @@ import "testing"
// predicate extracted out of updateJobApplication. The rest of
// updateJobApplication (note appending, the DB.Save, the returned counters)
// needs a live *gorm.DB and the only driver in go.mod is postgres, so it is
// deliberately not exercised here. Nothing in this file touches Claude or the
// Graph API either; email classification is a network call by construction.
// deliberately not exercised here. Nothing in this file touches the classifier
// or the Graph API either; see email_classify_test.go for the former.
func TestStatusAdvances(t *testing.T) {
cases := []struct {
+96 -85
View File
@@ -17,7 +17,6 @@ import (
"time"
"adam-french.co.uk/backend/models"
"github.com/anthropics/anthropic-sdk-go"
"golang.org/x/oauth2"
"gorm.io/gorm"
)
@@ -27,6 +26,13 @@ import (
// recruitment-related, asks Claude to turn each into structured data, and
// creates or advances a models.JobApplication row. Every email it has looked
// at is recorded as a models.ProcessedEmail so it is never handled twice.
//
// The Claude call itself is not made here: like the site's other two, it
// lives in the Python service (python/app/email_classify.py, which owns the
// prompt and the parsing of the model's reply) and is reached through
// CallPython. Everything that needs the mailbox or the database — fetching,
// the pre-filter, dedup and retry accounting, matching an email to an
// application, the forward-only status rule — stays in this file.
// MSGRAPH_TOKEN_JSON_PATH lives in a Docker volume so the OAuth refresh token
// survives restarts, exactly like the Spotify token.
@@ -54,9 +60,12 @@ type EmailSyncService struct {
// handler refuse to run while it is nil. On the Graph backend it is a
// real token-injecting client; on the IMAP backend it is set to
// http.DefaultClient purely so this check passes (IMAP never uses it).
HTTPClient *http.Client
DB *gorm.DB
ClaudeClient *anthropic.Client
HTTPClient *http.Client
DB *gorm.DB
// PythonURL is the Python service's base URL on the Docker network, no
// trailing slash: the same value as handlers.Store.PythonURL. The
// classifier is called there (see classifyEmail).
PythonURL string
// mu is used with TryLock, not Lock: it makes a sync a no-op while
// another one is running rather than queueing behind it, so the manual
// admin trigger cannot pile up on top of the scheduled run.
@@ -103,11 +112,15 @@ type graphBody struct {
Content string `json:"content"`
}
// Claude response type
// Classifier response type
// EmailAnalysis is the JSON contract Claude is asked to return; the keys here
// must stay in step with emailClassificationPrompt at the bottom of this file.
// Pointer fields are the ones Claude is allowed to answer null for.
// EmailAnalysis is the JSON contract with the Python service's
// /internal/email/classify: the body of its 200 reply. The keys here must stay
// in step with EmailAnalysis and the prompt in python/app/email_classify.py,
// which asks Claude for exactly these. Pointer fields are the ones that may
// come back null; the plain strings come back "" when the model had nothing
// (or when the email is not a job email, in which case only IsJobEmail means
// anything).
type EmailAnalysis struct {
IsJobEmail bool `json:"isJobEmail"`
Action string `json:"action"`
@@ -122,7 +135,7 @@ type EmailAnalysis struct {
// Email filtering config
// Cheap pre-filter, applied before any Claude call so that the bulk of a
// Cheap pre-filter, applied before any classifier call so that the bulk of a
// mailbox never costs an API request. It is intentionally over-inclusive:
// false positives are cheap (Claude rejects them), false negatives are not
// (the email is never looked at again once its window has passed).
@@ -155,6 +168,13 @@ var senderDomains = []string{
// "saved" is the one status no email can produce: it marks a posting captured
// from the browser but not applied to yet (handlers/handle_job_capture.go).
// It ranks lowest so that the "thanks for applying" email advances the row.
//
// This map is the vocabulary. It is written down in four other places, which
// must list the same statuses: `enum JobStatus` in
// graph/schema/job_application.graphql (enforced —
// TestJobStatusEnumMatchesStatusOrder fails on any difference), the
// classifier prompt in python/app/email_classify.py (all but "saved"), the
// tracker page and the capture userscript.
var statusOrder = map[string]int{
"saved": 0,
"applied": 1,
@@ -263,11 +283,15 @@ func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
// while the rest of the backend starts normally. For Graph, the authorisation
// URL is printed to the container log for a one-off manual sign-in that
// lands on GET /email/callback.
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, claudeClient *anthropic.Client) *EmailSyncService {
//
// pythonURL is where the classifier lives. It is not validated or probed: an
// unreachable Python service shows up as each email failing and being
// retried, the same way a bad API key used to.
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, pythonURL string) *EmailSyncService {
svc := &EmailSyncService{
Config: config,
DB: db,
ClaudeClient: claudeClient,
Config: config,
DB: db,
PythonURL: pythonURL,
}
switch config.Backend {
@@ -618,48 +642,66 @@ func (s *EmailSyncService) matchesFilter(email graphMessage) bool {
return false
}
// processEmail sends a single email to Claude and creates/updates a JobApplication.
// Returns the action taken ("created", "updated", "skipped") and the job application ID if applicable.
func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) (string, *uint, error) {
cleaned := cleanEmailBody(email.Body.Content, email.Body.ContentType)
// emailClassifyPath is the Python route, internal in the same way as the
// rowing and job-posting readers' (see python_call.go).
const emailClassifyPath = "/internal/email/classify"
userMsg := fmt.Sprintf("Subject: %s\nFrom: %s <%s>\nDate: %s\n\n%s",
// maxClassifyRunes mirrors MAX_MESSAGE_CHARS in python/app/email_classify.py,
// which answers 422 to anything longer. cleanEmailBody already caps the body
// far below this, so the limit only bites on a pathological subject or sender
// — but a 422 would be recorded as a failed attempt and retried to the cap,
// so the cut is made here rather than left to chance.
const maxClassifyRunes = 200_000
// classifierMessage formats one email as the classifier's user turn: Subject,
// From and Date lines, a blank line, then the cleaned body. The Python side
// passes the string to Claude unchanged, so this layout is part of what the
// prompt there was written against.
//
// The result is cut to maxClassifyRunes on a rune boundary. The body comes
// last, so it is what gives way first.
func classifierMessage(email graphMessage) string {
msg := fmt.Sprintf("Subject: %s\nFrom: %s <%s>\nDate: %s\n\n%s",
email.Subject,
email.From.EmailAddress.Name,
email.From.EmailAddress.Address,
email.ReceivedDateTime,
cleaned,
cleanEmailBody(email.Body.Content, email.Body.ContentType),
)
// Counting runes means converting; skip it for the ordinary case, where
// even the byte length (never less than the rune count) is under the cap.
if len(msg) <= maxClassifyRunes {
return msg
}
runes := []rune(msg)
if len(runes) <= maxClassifyRunes {
return msg
}
return string(runes[:maxClassifyRunes])
}
message, err := s.ClaudeClient.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaudeHaiku4_5,
MaxTokens: 512,
System: []anthropic.TextBlockParam{
{Text: emailClassificationPrompt},
},
Messages: []anthropic.MessageParam{
{
Role: "user",
Content: []anthropic.ContentBlockParamUnion{anthropic.NewTextBlock(userMsg)},
},
},
})
// classifyEmail asks the Python service what an email is. Every failure —
// the service unreachable, Claude failing (502), no API key (503), a reply
// that will not decode — comes back as an error, which SyncEmails records as
// a retryable failure of this email.
func (s *EmailSyncService) classifyEmail(ctx context.Context, email graphMessage) (EmailAnalysis, error) {
analysis, err := CallPython[EmailAnalysis](ctx, s.PythonURL, emailClassifyPath, struct {
Message string `json:"message"`
}{classifierMessage(email)})
if err != nil {
return "", nil, fmt.Errorf("Claude API error: %w", err)
// %w keeps context.Canceled visible to SyncEmails, which must not
// count an abandoned sync against the email.
return EmailAnalysis{}, fmt.Errorf("classifying email: %w", err)
}
return analysis, nil
}
if len(message.Content) == 0 {
return "", nil, fmt.Errorf("empty response from Claude")
}
// Only the first content block is read, and the prompt asks for bare JSON,
// but models still wrap output in a markdown fence often enough that it is
// stripped defensively here.
raw := StripMarkdownFence(message.Content[0].Text)
var analysis EmailAnalysis
if err := json.Unmarshal([]byte(raw), &analysis); err != nil {
return "", nil, fmt.Errorf("parsing Claude response: %w (raw: %s)", err, raw)
// processEmail has a single email classified and creates/updates a JobApplication.
// Returns the action taken ("created", "updated", "skipped") and the job application ID if applicable.
func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) (string, *uint, error) {
analysis, err := s.classifyEmail(ctx, email)
if err != nil {
return "", nil, err
}
if !analysis.IsJobEmail {
@@ -708,6 +750,11 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
// statusOrder. An unrecognised status stored verbatim would disable the
// forward-only guard for that row (updateJobApplication allows any recognised
// status over an unknown one), so the safe fallback is the pipeline's default.
//
// It is for values that arrive outside GraphQL: the classifier's answer and
// the capture endpoint's body. The GraphQL mutations do not use it — their
// status is a JobStatus, which UnmarshalJobStatus refuses outright when it is
// not in the vocabulary rather than quietly storing "applied".
func NormalizeStatus(s string) string {
lowered := strings.ToLower(strings.TrimSpace(s))
if _, ok := statusOrder[lowered]; ok {
@@ -798,7 +845,7 @@ func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication,
}
// cleanEmailBody reduces an email body to plain-ish text before it is sent to
// Claude, cutting token cost and noise.
// the classifier, cutting token cost and noise.
//
// The HTML handling is a regex tag-strip, not a parser: fine for extracting
// prose, but it would mangle inline <script>/<style> content and mis-handle
@@ -859,7 +906,9 @@ func cleanEmailBody(content string, contentType string) string {
text = strings.Join(cleaned, "\n")
// Cap the prompt size. This slices by bytes, so a cut can land mid-rune
// and leave an invalid UTF-8 tail; harmless for a model prompt.
// and leave an invalid UTF-8 tail. That is harmless: the text travels to
// the classifier as JSON, and encoding/json replaces the broken tail with
// U+FFFD rather than emitting invalid UTF-8.
if len(text) > 4000 {
text = text[:4000]
}
@@ -876,44 +925,6 @@ func truncate(s string, maxLen int) string {
return s[:maxLen]
}
// emailClassificationPrompt must stay in sync with the EmailAnalysis struct:
// every key it names is a field there, and the status values it lists are the
// keys of statusOrder — all but "saved", which only the browser capture sets
// and no email can mean.
const emailClassificationPrompt = `You are an email classifier for job applications. You will receive the subject line, sender, and body of an email. Determine if this email is related to a job application, and if so, extract structured data.
Return ONLY a JSON object with these exact keys:
- "isJobEmail": boolean - true if this email is about a job application
- "action": "create" | "update" | "none" - whether this represents a new application confirmation or an update to an existing one
- "company": string - the company name
- "jobTitle": string - the job title/position
- "status": string - one of: "applied", "screening", "interviewing", "assessment", "offer", "rejected", "withdrawn"
- "location": string or null - job location if mentioned
- "url": string or null - any application portal URL
- "appliedAt": string or null - ISO 8601 date if an application date is mentioned (YYYY-MM-DD format)
- "notes": string or null - brief summary of what this email communicates (e.g. "Interview scheduled for March 15", "Application confirmed via Greenhouse")
If isJobEmail is false, only include that field. No text, no markdown, no explanation. Just the JSON object.`
// StripMarkdownFence removes a surrounding markdown code fence from a model's
// response, so text that should have been bare JSON can be unmarshalled
// whether or not the model wrapped it.
//
// The two TrimPrefix calls are ordered so that "```json" is removed first and
// a plain "```" otherwise. It is deliberately forgiving: unfenced input is
// returned unchanged apart from surrounding whitespace.
//
// python/app/rowing.py carries a port of this for the rowing photo reader,
// which prompts for bare JSON in the same way and gets the same fenced output.
func StripMarkdownFence(raw string) string {
raw = strings.TrimSpace(raw)
raw = strings.TrimPrefix(raw, "```json")
raw = strings.TrimPrefix(raw, "```")
raw = strings.TrimSuffix(raw, "```")
return strings.TrimSpace(raw)
}
// maxEmailAttempts caps how many times a failing email is reprocessed. Each
// attempt costs a Claude call, so the cap is what stops one permanently
// unparseable email billing on every sync forever. Three gives a transient
+7 -29
View File
@@ -8,12 +8,13 @@ import (
"adam-french.co.uk/backend/models"
)
// These tests cover only the pure helpers of the email sync: body cleaning,
// truncation, fence stripping, timestamp parsing, the retry predicate and the
// filter. Everything else in email_sync.go — token acquisition, the Graph
// paging loop, processEmail and the create/update paths — needs either a live
// *gorm.DB, a Microsoft Graph endpoint or a Claude call, none of which exist
// in a test run, so they are deliberately not exercised here.
// These tests cover the pure helpers of the email sync: body cleaning,
// truncation, timestamp parsing, the retry predicate and the filter. The
// classify step, which is an HTTP call to the Python service, is covered in
// email_classify_test.go. What is left uncovered — token acquisition, the
// Graph paging loop, and the create/update paths processEmail ends in — needs
// either a live *gorm.DB or a Microsoft Graph endpoint, neither of which
// exists in a test run.
//
// matchesFilter is a method but reads no field of the receiver (it matches
// against the package-level subjectKeywords/senderDomains), which is why a
@@ -135,29 +136,6 @@ func TestTruncate(t *testing.T) {
}
}
func TestStripMarkdownFence(t *testing.T) {
cases := []struct {
name string
raw string
want string
}{
{"json-tagged fence", "```json\n{\"a\":1}\n```", `{"a":1}`},
{"bare fence", "```\n{\"a\":1}\n```", `{"a":1}`},
{"unfenced input is returned as-is", `{"a":1}`, `{"a":1}`},
{"surrounding whitespace is trimmed", "\n\n {\"a\":1} \n", `{"a":1}`},
{"leading whitespace before the fence", " ```json\n{\"a\":1}\n``` ", `{"a":1}`},
{"opening fence only", "```json\n{\"a\":1}", `{"a":1}`},
{"empty input", "", ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := StripMarkdownFence(c.raw); got != c.want {
t.Fatalf("StripMarkdownFence(%q) = %q, want %q", c.raw, got, c.want)
}
})
}
}
func TestParseReceivedAt(t *testing.T) {
cases := []struct {
name string
+87
View File
@@ -63,6 +63,93 @@ func TestEnvRegistryMatchesEnvExample(t *testing.T) {
}
}
// composePythonEnv returns the variable names in the `environment:` list of
// the `python` service in docker-compose.yml.
//
// It reads the file as text rather than through a YAML library — there is
// none among this module's direct dependencies, and the shape needed is
// narrow: a two-space-indented `python:` key under `services:`, a
// four-space-indented `environment:` under it, and `- NAME=value` items. If
// the compose file is ever restructured so that this finds nothing, the test
// below fails loudly rather than passing on an empty list.
func composePythonEnv(t *testing.T) []string {
t.Helper()
raw, err := os.ReadFile("../../docker-compose.yml")
if err != nil {
t.Fatalf("reading docker-compose.yml: %v", err)
}
item := regexp.MustCompile(`^ - ["']?([A-Z][A-Z0-9_]*)(=|["']?\s*$)`)
var names []string
inPython, inEnvironment := false, false
for _, line := range strings.Split(string(raw), "\n") {
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
indent := len(line) - len(strings.TrimLeft(line, " "))
switch {
case indent <= 2:
// A new service (or a top-level key) ends the block.
inPython, inEnvironment = line == " python:", false
case inPython && indent == 4:
inEnvironment = trimmed == "environment:"
case inPython && inEnvironment:
match := item.FindStringSubmatch(line)
if match == nil {
t.Fatalf("python.environment has an entry this test cannot read: %q", line)
}
names = append(names, match[1])
}
}
if len(names) == 0 {
t.Fatal("found no python.environment list in docker-compose.yml; has the file's layout changed?")
}
return names
}
// The python service is the one container given an explicit `environment:`
// list instead of the whole .env, so that it never holds the database
// password or the JWT secret. The cost is a third place a new Python variable
// has to be added — the registry, .env.example and that list — and forgetting
// the third is silent: the variable is simply empty inside the container.
//
// So the registry's claim "python reads this" and the compose list must
// agree, in both directions:
//
// - a variable the registry says python reads must be passed to it;
// - an editable variable that is passed to it must say so in the registry,
// or changing it in the admin panel would not recreate the container.
//
// Locked variables are exempt from the second rule. They are never applied
// through the panel, so the registry gives none of them a services list
// (PYTHON_PORT is passed to python and is one of these). Names in the compose
// list that are not registry variables at all, such as the literal ROOT_PATH,
// are not this test's business.
func TestEnvRegistryMatchesComposePythonEnvironment(t *testing.T) {
compose := composePythonEnv(t)
registry := map[string]EnvVar{}
for _, v := range newEnvManager(t).Vars() {
registry[v.Name] = v
if slices.Contains(v.Services, "python") && !slices.Contains(compose, v.Name) {
t.Errorf("%s lists the python service in env_registry.json but is not in "+
"python.environment in docker-compose.yml, so the container never receives it", v.Name)
}
}
for _, name := range compose {
v, known := registry[name]
if !known || !v.Editable {
continue
}
if !slices.Contains(v.Services, "python") {
t.Errorf("%s is passed to the python service in docker-compose.yml but env_registry.json "+
"does not list python among its services, so editing it would not recreate the container", name)
}
}
}
func TestEnvRegistryEntriesAreWellFormed(t *testing.T) {
kinds := []string{"secret", "generated", "text", "url", "bool", "duration", "number", "enum"}
for _, v := range newEnvManager(t).Vars() {
+1 -1
View File
@@ -1,5 +1,5 @@
[
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Email pipeline, rowing photo reader, job posting reader", "kind": "secret", "editable": true, "services": ["backend", "python"], "docsUrl": "https://console.anthropic.com/settings/keys"},
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Claude calls, all made by the Python service: email classifier, rowing photo reader, job posting reader", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://console.anthropic.com/settings/keys"},
{"name": "STEAM_API_KEY", "group": "API keys", "purpose": "Steam status widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://steamcommunity.com/dev/apikey"},
{"name": "STEAM_ID", "group": "API keys", "purpose": "Steam account the widget reports on (64-bit ID)", "kind": "text", "editable": true, "services": ["backend"]},
{"name": "TFL_APP_KEY", "group": "API keys", "purpose": "TfL Unified API, used by the hotel finder", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://api-portal.tfl.gov.uk/profile"},
+75
View File
@@ -0,0 +1,75 @@
package services
import (
"fmt"
"strings"
"github.com/99designs/gqlgen/graphql"
)
// The job-status vocabulary, as GraphQL sees it.
//
// The schema declares `enum JobStatus` (graph/schema/job_application.graphql)
// and gqlgen.yml binds it to the two functions below instead of letting
// gqlgen generate a Go enum type. That keeps models.JobApplication.Status a
// plain string column — no migration, and the email pipeline and the capture
// endpoint go on writing strings — while the GraphQL boundary still refuses a
// status nobody ranked.
//
// statusOrder (email_sync.go) is the vocabulary; the enum in the schema has to
// list the same values, and TestJobStatusEnumMatchesStatusOrder fails when
// they differ. The functions live in this package, rather than in graph,
// because this is where statusOrder is and graph already imports services.
// KnownStatus reports whether s is exactly one of the tracked statuses. No
// trimming or case folding: see NormalizeStatus for the forgiving version the
// email pipeline and the capture endpoint use on values that did not come
// through GraphQL.
func KnownStatus(s string) bool {
_, ok := statusOrder[s]
return ok
}
// MarshalJobStatus writes a stored status to a GraphQL response.
//
// It is deliberately lenient, where the input side is strict. The column is
// older than the enum, so a row can hold a status outside the vocabulary: the
// tracker's early Title Case values ("Rejected"), or something written by
// hand. A generated enum type would fail to serialise such a row, and because
// JobApplication.status is non-null that one error would null out the whole
// jobApplications list — one stale row hiding every application. So:
//
// - a value that is in the vocabulary once trimmed and lowered is emitted
// in that canonical form, which also means an edit form sends back
// something the input side accepts;
// - anything else is emitted exactly as stored. That is not a legal
// JobStatus, strictly, but the response is JSON and the tracker page
// shows an unlisted status as-is so that it can be corrected, which is
// more use than an error or a made-up substitute.
//
// The value is written with gqlgen's own String marshaller, so it is the same
// quoted JSON string the field produced when it was declared String.
func MarshalJobStatus(s string) graphql.Marshaler {
if canonical := strings.ToLower(strings.TrimSpace(s)); KnownStatus(canonical) {
s = canonical
}
return graphql.MarshalString(s)
}
// UnmarshalJobStatus reads a status from a mutation's input, and is where
// drift is refused: only the exact lowercase values are accepted, so nothing
// outside the vocabulary can be written through GraphQL.
//
// The value arrives as a string whether the client sent a JSON string
// variable ("applied", which is what the tracker page does) or wrote the enum
// literal in the query document (applied).
func UnmarshalJobStatus(v any) (string, error) {
s, ok := v.(string)
if !ok {
return "", fmt.Errorf("status must be a string")
}
if !KnownStatus(s) {
return "", fmt.Errorf("%q is not a valid JobStatus", s)
}
return s, nil
}
+126
View File
@@ -0,0 +1,126 @@
package services
import (
"bytes"
"os"
"slices"
"sort"
"testing"
"github.com/vektah/gqlparser/v2"
"github.com/vektah/gqlparser/v2/ast"
)
// jobStatusEnumValues reads `enum JobStatus` out of the schema file itself.
// The test lives here, not in graph, because statusOrder is unexported and
// graph imports this package; parsing the file directly avoids both an
// export that exists only for a test and an import cycle.
func jobStatusEnumValues(t *testing.T) []string {
t.Helper()
const path = "../graph/schema/job_application.graphql"
raw, err := os.ReadFile(path)
if err != nil {
t.Fatalf("reading the schema: %v", err)
}
// The file extends Query and Mutation and uses Time and the two
// authorisation directives, all declared in schema.graphql; give it just
// enough of those to parse on its own.
const prelude = "scalar Time\ndirective @admin on FIELD_DEFINITION\ndirective @signedIn on FIELD_DEFINITION\ntype Query\ntype Mutation\n"
schema, gqlErr := gqlparser.LoadSchema(
&ast.Source{Name: "prelude", Input: prelude},
&ast.Source{Name: path, Input: string(raw)},
)
if gqlErr != nil {
t.Fatalf("parsing the schema: %v", gqlErr)
}
def := schema.Types["JobStatus"]
if def == nil || def.Kind != ast.Enum {
t.Fatal("the schema has no `enum JobStatus`")
}
var values []string
for _, v := range def.EnumValues {
values = append(values, v.Name)
}
return values
}
// One vocabulary, two places it has to be written down: the enum the GraphQL
// API validates against and the map the email pipeline ranks with. A status
// in the enum but not the map could be saved from the tracker and then never
// advanced; one in the map but not the enum could be stored by the pipeline
// and then not edited.
func TestJobStatusEnumMatchesStatusOrder(t *testing.T) {
enum := jobStatusEnumValues(t)
var ranked []string
for status := range statusOrder {
ranked = append(ranked, status)
}
sort.Strings(ranked)
sorted := slices.Clone(enum)
sort.Strings(sorted)
if !slices.Equal(sorted, ranked) {
t.Fatalf("enum JobStatus = %v\nstatusOrder = %v\nthe two must list the same statuses", sorted, ranked)
}
// The schema lists them in lifecycle order, which is the order the
// tracker shows; keep it agreeing with the ranks.
for i, status := range enum {
if statusOrder[status] != i {
t.Errorf("enum lists %q at position %d but statusOrder ranks it %d", status, i, statusOrder[status])
}
}
}
// The exact strings, spelled out once: these are what is stored in the
// database and sent by the front end and the userscript, so a rename is a
// data migration, not an edit.
func TestJobStatusVocabulary(t *testing.T) {
want := []string{"saved", "applied", "screening", "assessment", "interviewing", "offer", "rejected", "withdrawn"}
if got := jobStatusEnumValues(t); !slices.Equal(got, want) {
t.Fatalf("enum JobStatus = %v, want %v", got, want)
}
}
func TestUnmarshalJobStatus(t *testing.T) {
for status := range statusOrder {
if got, err := UnmarshalJobStatus(status); err != nil || got != status {
t.Errorf("UnmarshalJobStatus(%q) = %q, %v", status, got, err)
}
}
// Strict on the way in: none of the forgiveness NormalizeStatus shows the
// email pipeline. In particular nothing is coerced to "applied".
for _, bad := range []any{"hired", "Applied", " applied", "", "on hold", 3, nil, true} {
if got, err := UnmarshalJobStatus(bad); err == nil {
t.Errorf("UnmarshalJobStatus(%#v) = %q, want an error", bad, got)
}
}
}
func TestMarshalJobStatus(t *testing.T) {
cases := []struct {
name string
stored string
want string
}{
{"a tracked status is a quoted string, as when the field was a String", "interviewing", `"interviewing"`},
{"the tracker's old Title Case rows read back canonical", "Rejected", `"rejected"`},
{"stray whitespace is dropped for a tracked status", " offer ", `"offer"`},
// The reason this is a custom marshaller: a generated enum type would
// error here, and status is non-null, so one such row would null the
// whole jobApplications list.
{"an untracked status is passed through, not refused", "Interview", `"Interview"`},
{"an untracked status is not rewritten to the default", "on hold", `"on hold"`},
{"an empty status stays empty", "", `""`},
{"quotes in a stray value are escaped", `a"b`, `"a\"b"`},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
var b bytes.Buffer
MarshalJobStatus(c.stored).MarshalGQL(&b)
if b.String() != c.want {
t.Fatalf("MarshalJobStatus(%q) wrote %s, want %s", c.stored, &b, c.want)
}
})
}
}
+98
View File
@@ -0,0 +1,98 @@
package services
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// Every Claude call the site makes lives in the Python service, behind an
// /internal/ route. This file is the one way the Go backend reaches those
// routes: the rowing photo reader and the job posting reader (handlers), and
// the email classifier (email_sync.go). It sits in services rather than
// handlers because both packages need it and handlers already imports
// services, not the other way round.
//
// The routes are internal in a specific sense: nginx answers 404 for
// /py/internal/, and each route itself refuses a request carrying a proxy
// header, so the only way in is this direct container-to-container call. That
// is why the request below sets nothing but Content-Type.
// pythonClient bounds the wait on the Python service. Two minutes sits above
// that side's own worst case (a 30s Claude timeout, retried twice with
// backoff), so a slow Claude surfaces as Python's error rather than as a
// timeout here. One client for every route, so they share a connection pool.
var pythonClient = &http.Client{Timeout: 2 * time.Minute}
// PythonError is a failure the Python service reported in words that are safe
// and useful to show a person: the string `detail` of a 502, which is always
// one of that route's own fixed messages ("failed to parse image data", ...).
//
// Everything else — a refused connection, a 422, a 503 for a missing API key,
// a reply that will not decode — comes back as an ordinary error instead. The
// distinction is the point: a caller relays a PythonError and only logs the
// rest, because the rest describe plumbing the user can do nothing about and
// may quote internals.
type PythonError struct{ Detail string }
func (e *PythonError) Error() string { return e.Detail }
// CallPython POSTs body as JSON to baseURL+path and decodes a 200 reply into
// T. baseURL is the service's address on the Docker network with no trailing
// slash (handlers.Store.PythonURL); path is the route, starting with a slash.
//
// Any non-200 is an error. See PythonError for which ones are relayable. A
// cancelled ctx is wrapped, not replaced, so errors.Is(err, context.Canceled)
// still holds — the email pipeline relies on that to tell an abandoned sync
// from a failed email.
func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T, error) {
var out T
// Note for callers sending bytes: encoding/json writes a []byte as
// standard base64, which is the form the Anthropic API wants and so what
// the Python side passes straight through.
payload, err := json.Marshal(body)
if err != nil {
return out, fmt.Errorf("encoding request for %s: %w", path, err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+path, bytes.NewReader(payload))
if err != nil {
return out, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := pythonClient.Do(req)
if err != nil {
return out, fmt.Errorf("calling %s: %w", path, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
// FastAPI errors are {"detail": ...}. Only a 502 carries one of the
// route's own fixed messages; a 422's detail is a list, which fails
// to decode into the string and falls through to the generic error,
// and a 503's detail names an environment variable, which is for the
// log rather than the page. The body is capped because it is only
// ever quoted in a log line.
var failure struct {
Detail string `json:"detail"`
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
return out, &PythonError{Detail: failure.Detail}
}
return out, fmt.Errorf("%s returned %d: %s", path, resp.StatusCode, raw)
}
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
// A fresh zero value, so a half-decoded T never escapes with an error.
var zero T
return zero, fmt.Errorf("decoding %s response: %w", path, err)
}
return out, nil
}
+147
View File
@@ -0,0 +1,147 @@
package services
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// CallPython is the one path from this backend to the Python service's
// internal routes, so its contract is tested here once rather than per
// caller: what the request looks like, and which replies come back as a
// relayable *PythonError, which as a plain error.
type pythonReply struct {
Name string `json:"name"`
Count int `json:"count"`
Note *string `json:"note"`
}
func pythonStub(t *testing.T, handler http.HandlerFunc) string {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
return srv.URL
}
func TestCallPythonRequestAndReply(t *testing.T) {
var (
method, path, contentType string
forwarded bool
got map[string]any
)
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
method, path, contentType = r.Method, r.URL.Path, r.Header.Get("Content-Type")
// The Python routes treat either header as "came through nginx" and
// answer 404, so the helper must never send them.
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
t.Errorf("decoding request: %v", err)
}
w.Write([]byte(`{"name": "x", "count": 3, "note": null}`))
})
reply, err := CallPython[pythonReply](context.Background(), url, "/internal/thing", struct {
Text string `json:"text"`
Data []byte `json:"data"`
}{"hello", []byte("hello")})
if err != nil {
t.Fatalf("CallPython: %v", err)
}
if reply.Name != "x" || reply.Count != 3 || reply.Note != nil {
t.Fatalf("reply = %+v", reply)
}
if method != http.MethodPost || path != "/internal/thing" || contentType != "application/json" {
t.Fatalf("request was %s %s (%s)", method, path, contentType)
}
if forwarded {
t.Fatal("request carried a proxy header the Python routes reject")
}
// A []byte travels as standard base64, which is what the rowing reader
// relies on for the image.
if got["text"] != "hello" || got["data"] != "aGVsbG8=" {
t.Fatalf("request body = %v", got)
}
}
func TestCallPythonErrors(t *testing.T) {
cases := []struct {
name string
status int
body string
wantDetail string // non-empty: a *PythonError with this message
}{
{"a 502's string detail is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"},
{"a 502 with an empty detail is not", http.StatusBadGateway, `{"detail": ""}`, ""},
{"a 502 that is not JSON is not", http.StatusBadGateway, `<html>bad gateway</html>`, ""},
// A 422's detail is a list of validation errors, not a message.
{"a validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
// Its detail is a string, but it names an environment variable: for
// the log, not for the page.
{"a missing API key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
{"a 404 is not relayed", http.StatusNotFound, `{"detail": "Not Found"}`, ""},
{"a malformed success body is an error", http.StatusOK, `not json`, ""},
{"a success body of the wrong shape is an error", http.StatusOK, `{"count": "three"}`, ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(c.status)
w.Write([]byte(c.body))
})
reply, err := CallPython[pythonReply](context.Background(), url, "/internal/thing", struct{}{})
if err == nil {
t.Fatal("expected an error")
}
if reply != (pythonReply{}) {
t.Fatalf("reply = %+v alongside an error, want the zero value", reply)
}
var pyErr *PythonError
if relayed := errors.As(err, &pyErr); relayed != (c.wantDetail != "") {
t.Fatalf("relayed = %v, err = %v", relayed, err)
}
if pyErr != nil && (pyErr.Detail != c.wantDetail || pyErr.Error() != c.wantDetail) {
t.Fatalf("detail = %q, want %q", pyErr.Detail, c.wantDetail)
}
// A plumbing error names the route, so the log line says which
// of the three calls it was.
if pyErr == nil && !strings.Contains(err.Error(), "/internal/thing") {
t.Fatalf("err = %v, want it to name the route", err)
}
})
}
}
func TestCallPythonUnreachable(t *testing.T) {
url := pythonStub(t, func(http.ResponseWriter, *http.Request) {})
// Port 1 on localhost: nothing listens there.
_, err := CallPython[pythonReply](context.Background(), "http://127.0.0.1:1", "/internal/thing", struct{}{})
if err == nil {
t.Fatal("expected an error")
}
var pyErr *PythonError
if errors.As(err, &pyErr) {
t.Fatalf("a transport failure was reported as relayable: %v", err)
}
// A cancelled call must still read as context.Canceled: the email
// pipeline uses that to avoid counting an abandoned sync as a failure.
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := CallPython[pythonReply](ctx, url, "/internal/thing", struct{}{}); !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want it to wrap context.Canceled", err)
}
}
func TestCallPythonUnencodableBody(t *testing.T) {
// Channels cannot be marshalled; the point is that this fails before any
// request is made, so the URL is never dialled.
if _, err := CallPython[pythonReply](context.Background(), "http://127.0.0.1:1", "/internal/thing", make(chan int)); err == nil {
t.Fatal("expected an error")
}
}
-2
View File
@@ -16,8 +16,6 @@ import (
// - FetchLatestFeed: it is an HTTP call to the Gitea container. Its only
// logic beyond the request is the empty-feed nil,nil case, and testing it
// would mean either a network or an injected client that does not exist.
// - claude.go: InitClaude is a single SDK constructor with no validation and
// no prompt building; there is nothing to assert that is not the SDK's.
// - The 1-minute Gitea cache TTL: it lives in handlers.Store, not here.
// - RateLimiter's window expiry uses the real clock (Allow calls time.Now
// directly and there is no injectable clock), so the expiry case below