From 71344a1f8d0fd1b4fe90162bb9282bebe1e7d3f0 Mon Sep 17 00:00:00 2001 From: Adam French Date: Mon, 12 Oct 2026 14:39:19 +0100 Subject: [PATCH] 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 --- backend/README.md | 250 +++- backend/go.mod | 5 - backend/go.sum | 16 - backend/gqlgen.yml | 14 + backend/graph/activity.resolvers.go | 19 +- backend/graph/auth.resolvers.go | 3 + backend/graph/bookmark.resolvers.go | 17 - backend/graph/context.go | 18 +- backend/graph/directives.go | 63 + backend/graph/directives_test.go | 352 ++++++ backend/graph/doc.go | 39 +- backend/graph/favorite.resolvers.go | 15 - backend/graph/generated.go | 1042 +++++++++-------- backend/graph/job_app_reference.resolvers.go | 29 +- backend/graph/job_application.resolvers.go | 54 +- backend/graph/message.resolvers.go | 5 - backend/graph/middleware.go | 7 +- backend/graph/place.resolvers.go | 28 +- backend/graph/post.resolvers.go | 30 +- backend/graph/resolver.go | 10 +- backend/graph/rowing.resolvers.go | 5 - backend/graph/schema/activity.graphql | 2 +- backend/graph/schema/auth.graphql | 4 + backend/graph/schema/bookmark.graphql | 4 +- backend/graph/schema/favorite.graphql | 2 +- .../graph/schema/job_app_reference.graphql | 13 +- backend/graph/schema/job_application.graphql | 50 +- backend/graph/schema/message.graphql | 3 +- backend/graph/schema/place.graphql | 13 +- backend/graph/schema/post.graphql | 8 +- backend/graph/schema/schema.graphql | 17 + backend/graph/schema/spotify.graphql | 3 +- backend/graph/schema/user.graphql | 10 +- backend/graph/spotify.resolvers.go | 2 + backend/graph/user.resolvers.go | 33 +- backend/handlers/handle_job_capture.go | 61 +- backend/handlers/handle_job_capture_test.go | 8 +- backend/handlers/handle_rowing.go | 70 +- backend/handlers/handle_rowing_test.go | 10 +- backend/handlers/store.go | 6 +- backend/main.go | 39 +- backend/models/models.go | 19 +- backend/services/auth_test.go | 4 +- backend/services/claude.go | 25 - backend/services/email_classify_test.go | 185 +++ backend/services/email_status_test.go | 4 +- backend/services/email_sync.go | 181 +-- backend/services/email_sync_test.go | 36 +- backend/services/env_manager_test.go | 87 ++ backend/services/env_registry.json | 2 +- backend/services/job_status.go | 75 ++ backend/services/job_status_test.go | 126 ++ backend/services/python_call.go | 98 ++ backend/services/python_call_test.go | 147 +++ backend/services/services_misc_test.go | 2 - 55 files changed, 2271 insertions(+), 1099 deletions(-) create mode 100644 backend/graph/directives.go create mode 100644 backend/graph/directives_test.go delete mode 100644 backend/services/claude.go create mode 100644 backend/services/email_classify_test.go create mode 100644 backend/services/job_status.go create mode 100644 backend/services/job_status_test.go create mode 100644 backend/services/python_call.go create mode 100644 backend/services/python_call_test.go diff --git a/backend/README.md b/backend/README.md index 24eb5da..9a49924 100644 --- a/backend/README.md +++ b/backend/README.md @@ -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/.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/.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. diff --git a/backend/go.mod b/backend/go.mod index cf18806..526a11f 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -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 diff --git a/backend/go.sum b/backend/go.sum index 387e026..0970d2e 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -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= diff --git a/backend/gqlgen.yml b/backend/gqlgen.yml index 423cf9f..6d1bee4 100644 --- a/backend/gqlgen.yml +++ b/backend/gqlgen.yml @@ -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 diff --git a/backend/graph/activity.resolvers.go b/backend/graph/activity.resolvers.go index d692761..d6462ae 100644 --- a/backend/graph/activity.resolvers.go +++ b/backend/graph/activity.resolvers.go @@ -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 } diff --git a/backend/graph/auth.resolvers.go b/backend/graph/auth.resolvers.go index fcf8c2a..2eb9968 100644 --- a/backend/graph/auth.resolvers.go +++ b/backend/graph/auth.resolvers.go @@ -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") diff --git a/backend/graph/bookmark.resolvers.go b/backend/graph/bookmark.resolvers.go index 5d41182..d0cf747 100644 --- a/backend/graph/bookmark.resolvers.go +++ b/backend/graph/bookmark.resolvers.go @@ -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 } diff --git a/backend/graph/context.go b/backend/graph/context.go index e67b823..553e2ee 100644 --- a/backend/graph/context.go +++ b/backend/graph/context.go @@ -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 { diff --git a/backend/graph/directives.go b/backend/graph/directives.go new file mode 100644 index 0000000..59abb64 --- /dev/null +++ b/backend/graph/directives.go @@ -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) +} diff --git a/backend/graph/directives_test.go b/backend/graph/directives_test.go new file mode 100644 index 0000000..00ecd80 --- /dev/null +++ b/backend/graph/directives_test.go @@ -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) + } +} diff --git a/backend/graph/doc.go b/backend/graph/doc.go index 475f01e..9e8dcca 100644 --- a/backend/graph/doc.go +++ b/backend/graph/doc.go @@ -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 diff --git a/backend/graph/favorite.resolvers.go b/backend/graph/favorite.resolvers.go index d6d86da..7907eb0 100644 --- a/backend/graph/favorite.resolvers.go +++ b/backend/graph/favorite.resolvers.go @@ -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 } diff --git a/backend/graph/generated.go b/backend/graph/generated.go index 787d0b5..6de6d9e 100644 --- a/backend/graph/generated.go +++ b/backend/graph/generated.go @@ -15,6 +15,7 @@ import ( "adam-french.co.uk/backend/graph/model" "adam-french.co.uk/backend/models" + "adam-french.co.uk/backend/services" "github.com/99designs/gqlgen/graphql" "github.com/99designs/gqlgen/graphql/introspection" gqlparser "github.com/vektah/gqlparser/v2" @@ -31,21 +32,15 @@ func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { type Config = graphql.Config[ResolverRoot, DirectiveRoot, ComplexityRoot] type ResolverRoot interface { - Activity() ActivityResolver - Bookmark() BookmarkResolver - Favorite() FavoriteResolver - JobAppReference() JobAppReferenceResolver - JobApplication() JobApplicationResolver Message() MessageResolver Mutation() MutationResolver - Place() PlaceResolver - Post() PostResolver Query() QueryResolver Rowing() RowingResolver - User() UserResolver } type DirectiveRoot struct { + Admin func(ctx context.Context, obj any, next graphql.Resolver) (res any, err error) + SignedIn func(ctx context.Context, obj any, next graphql.Resolver) (res any, err error) } type ComplexityRoot struct { @@ -257,24 +252,7 @@ type ComplexityRoot struct { // region ************************** generated!.gotpl ************************** -type ActivityResolver interface { - ID(ctx context.Context, obj *models.Activity) (int, error) -} -type BookmarkResolver interface { - ID(ctx context.Context, obj *models.Bookmark) (int, error) -} -type FavoriteResolver interface { - ID(ctx context.Context, obj *models.Favorite) (int, error) -} -type JobAppReferenceResolver interface { - ID(ctx context.Context, obj *models.JobAppReference) (int, error) -} -type JobApplicationResolver interface { - ID(ctx context.Context, obj *models.JobApplication) (int, error) -} type MessageResolver interface { - ID(ctx context.Context, obj *models.Message) (int, error) - AuthorID(ctx context.Context, obj *models.Message) (int, error) } type MutationResolver interface { @@ -301,12 +279,6 @@ type MutationResolver interface { DeleteUser(ctx context.Context, id int) (*models.User, error) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) } -type PlaceResolver interface { - ID(ctx context.Context, obj *models.Place) (int, error) -} -type PostResolver interface { - ID(ctx context.Context, obj *models.Post) (int, error) -} type QueryResolver interface { Activities(ctx context.Context) ([]*models.Activity, error) Me(ctx context.Context) (*models.User, error) @@ -329,14 +301,9 @@ type QueryResolver interface { User(ctx context.Context, id int) (*models.User, error) } type RowingResolver interface { - ID(ctx context.Context, obj *models.Rowing) (int, error) - Time(ctx context.Context, obj *models.Rowing) (int, error) Distance(ctx context.Context, obj *models.Rowing) (int, error) } -type UserResolver interface { - ID(ctx context.Context, obj *models.User) (int, error) -} // endregion ************************** generated!.gotpl ************************** @@ -2318,18 +2285,18 @@ func (ec *executionContext) _Activity_id(ctx context.Context, field graphql.Coll return ec.fieldContext_Activity_id(ctx, field) }, func(ctx context.Context) (any, error) { - return ec.Resolvers.Activity().ID(ctx, obj) + return obj.ID, nil }, nil, - func(ctx context.Context, selections ast.SelectionSet, v int) graphql.Marshaler { - return ec.marshalNID2int(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v uint) graphql.Marshaler { + return ec.marshalNID2uint(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_Activity_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("Activity", field, true, true, errors.New("field of type ID does not have child fields")) + return graphql.NewScalarFieldContext("Activity", field, false, false, errors.New("field of type ID does not have child fields")) } func (ec *executionContext) _Activity_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.Activity) (ret graphql.Marshaler) { @@ -2488,18 +2455,18 @@ func (ec *executionContext) _Bookmark_id(ctx context.Context, field graphql.Coll return ec.fieldContext_Bookmark_id(ctx, field) }, func(ctx context.Context) (any, error) { - return ec.Resolvers.Bookmark().ID(ctx, obj) + return obj.ID, nil }, nil, - func(ctx context.Context, selections ast.SelectionSet, v int) graphql.Marshaler { - return ec.marshalNID2int(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v uint) graphql.Marshaler { + return ec.marshalNID2uint(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_Bookmark_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("Bookmark", field, true, true, errors.New("field of type ID does not have child fields")) + return graphql.NewScalarFieldContext("Bookmark", field, false, false, errors.New("field of type ID does not have child fields")) } func (ec *executionContext) _Bookmark_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.Bookmark) (ret graphql.Marshaler) { @@ -2626,18 +2593,18 @@ func (ec *executionContext) _Favorite_id(ctx context.Context, field graphql.Coll return ec.fieldContext_Favorite_id(ctx, field) }, func(ctx context.Context) (any, error) { - return ec.Resolvers.Favorite().ID(ctx, obj) + return obj.ID, nil }, nil, - func(ctx context.Context, selections ast.SelectionSet, v int) graphql.Marshaler { - return ec.marshalNID2int(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v uint) graphql.Marshaler { + return ec.marshalNID2uint(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_Favorite_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("Favorite", field, true, true, errors.New("field of type ID does not have child fields")) + return graphql.NewScalarFieldContext("Favorite", field, false, false, errors.New("field of type ID does not have child fields")) } func (ec *executionContext) _Favorite_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.Favorite) (ret graphql.Marshaler) { @@ -2902,18 +2869,18 @@ func (ec *executionContext) _JobAppReference_id(ctx context.Context, field graph return ec.fieldContext_JobAppReference_id(ctx, field) }, func(ctx context.Context) (any, error) { - return ec.Resolvers.JobAppReference().ID(ctx, obj) + return obj.ID, nil }, nil, - func(ctx context.Context, selections ast.SelectionSet, v int) graphql.Marshaler { - return ec.marshalNID2int(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v uint) graphql.Marshaler { + return ec.marshalNID2uint(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_JobAppReference_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("JobAppReference", field, true, true, errors.New("field of type ID does not have child fields")) + return graphql.NewScalarFieldContext("JobAppReference", field, false, false, errors.New("field of type ID does not have child fields")) } func (ec *executionContext) _JobAppReference_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.JobAppReference) (ret graphql.Marshaler) { @@ -3063,18 +3030,18 @@ func (ec *executionContext) _JobApplication_id(ctx context.Context, field graphq return ec.fieldContext_JobApplication_id(ctx, field) }, func(ctx context.Context) (any, error) { - return ec.Resolvers.JobApplication().ID(ctx, obj) + return obj.ID, nil }, nil, - func(ctx context.Context, selections ast.SelectionSet, v int) graphql.Marshaler { - return ec.marshalNID2int(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v uint) graphql.Marshaler { + return ec.marshalNID2uint(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_JobApplication_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("JobApplication", field, true, true, errors.New("field of type ID does not have child fields")) + return graphql.NewScalarFieldContext("JobApplication", field, false, false, errors.New("field of type ID does not have child fields")) } func (ec *executionContext) _JobApplication_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.JobApplication) (ret graphql.Marshaler) { @@ -3228,14 +3195,14 @@ func (ec *executionContext) _JobApplication_status(ctx context.Context, field gr }, nil, func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) + return ec.marshalNJobStatus2string(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_JobApplication_status(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("JobApplication", field, false, false, errors.New("field of type String does not have child fields")) + return graphql.NewScalarFieldContext("JobApplication", field, false, false, errors.New("field of type JobStatus does not have child fields")) } func (ec *executionContext) _JobApplication_notes(ctx context.Context, field graphql.CollectedField, obj *models.JobApplication) (ret graphql.Marshaler) { @@ -3316,18 +3283,18 @@ func (ec *executionContext) _Message_id(ctx context.Context, field graphql.Colle return ec.fieldContext_Message_id(ctx, field) }, func(ctx context.Context) (any, error) { - return ec.Resolvers.Message().ID(ctx, obj) + return obj.ID, nil }, nil, - func(ctx context.Context, selections ast.SelectionSet, v int) graphql.Marshaler { - return ec.marshalNID2int(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v uint) graphql.Marshaler { + return ec.marshalNID2uint(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_Message_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("Message", field, true, true, errors.New("field of type ID does not have child fields")) + return graphql.NewScalarFieldContext("Message", field, false, false, errors.New("field of type ID does not have child fields")) } func (ec *executionContext) _Message_content(ctx context.Context, field graphql.CollectedField, obj *models.Message) (ret graphql.Marshaler) { @@ -3457,7 +3424,20 @@ func (ec *executionContext) _Mutation_createActivity(ctx context.Context, field fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().CreateActivity(ctx, fc.Args["input"].(model.CreateActivityInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.Activity + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.Activity) graphql.Marshaler { return ec.marshalNActivity2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐActivity(ctx, selections, v) }, @@ -3600,7 +3580,20 @@ func (ec *executionContext) _Mutation_createBookmark(ctx context.Context, field fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().CreateBookmark(ctx, fc.Args["input"].(model.CreateBookmarkInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.Bookmark + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.Bookmark) graphql.Marshaler { return ec.marshalNBookmark2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐBookmark(ctx, selections, v) }, @@ -3644,7 +3637,20 @@ func (ec *executionContext) _Mutation_deleteBookmark(ctx context.Context, field fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().DeleteBookmark(ctx, fc.Args["id"].(int)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.Bookmark + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.Bookmark) graphql.Marshaler { return ec.marshalNBookmark2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐBookmark(ctx, selections, v) }, @@ -3688,7 +3694,20 @@ func (ec *executionContext) _Mutation_createFavorite(ctx context.Context, field fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().CreateFavorite(ctx, fc.Args["input"].(model.CreateFavoriteInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.Favorite + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.Favorite) graphql.Marshaler { return ec.marshalNFavorite2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐFavorite(ctx, selections, v) }, @@ -3732,7 +3751,20 @@ func (ec *executionContext) _Mutation_createJobAppReference(ctx context.Context, fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().CreateJobAppReference(ctx, fc.Args["input"].(model.CreateJobAppReferenceInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.JobAppReference + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.JobAppReference) graphql.Marshaler { return ec.marshalNJobAppReference2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐJobAppReference(ctx, selections, v) }, @@ -3776,7 +3808,20 @@ func (ec *executionContext) _Mutation_updateJobAppReference(ctx context.Context, fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().UpdateJobAppReference(ctx, fc.Args["id"].(int), fc.Args["input"].(model.UpdateJobAppReferenceInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.JobAppReference + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.JobAppReference) graphql.Marshaler { return ec.marshalNJobAppReference2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐJobAppReference(ctx, selections, v) }, @@ -3820,7 +3865,20 @@ func (ec *executionContext) _Mutation_deleteJobAppReference(ctx context.Context, fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().DeleteJobAppReference(ctx, fc.Args["id"].(int)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal bool + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v bool) graphql.Marshaler { return ec.marshalNBoolean2bool(ctx, selections, v) }, @@ -3864,7 +3922,20 @@ func (ec *executionContext) _Mutation_createJobApplication(ctx context.Context, fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().CreateJobApplication(ctx, fc.Args["input"].(model.CreateJobApplicationInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.JobApplication + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.JobApplication) graphql.Marshaler { return ec.marshalNJobApplication2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐJobApplication(ctx, selections, v) }, @@ -3908,7 +3979,20 @@ func (ec *executionContext) _Mutation_updateJobApplication(ctx context.Context, fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().UpdateJobApplication(ctx, fc.Args["id"].(int), fc.Args["input"].(model.UpdateJobApplicationInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.JobApplication + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.JobApplication) graphql.Marshaler { return ec.marshalNJobApplication2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐJobApplication(ctx, selections, v) }, @@ -3952,7 +4036,20 @@ func (ec *executionContext) _Mutation_deleteJobApplication(ctx context.Context, fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().DeleteJobApplication(ctx, fc.Args["id"].(int)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal bool + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v bool) graphql.Marshaler { return ec.marshalNBoolean2bool(ctx, selections, v) }, @@ -3996,7 +4093,20 @@ func (ec *executionContext) _Mutation_createPlace(ctx context.Context, field gra fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().CreatePlace(ctx, fc.Args["input"].(model.CreatePlaceInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.SignedIn == nil { + var zeroVal *models.Place + return zeroVal, errors.New("directive signedIn is not implemented") + } + return ec.Directives.SignedIn(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.Place) graphql.Marshaler { return ec.marshalNPlace2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐPlace(ctx, selections, v) }, @@ -4040,7 +4150,20 @@ func (ec *executionContext) _Mutation_updatePlace(ctx context.Context, field gra fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().UpdatePlace(ctx, fc.Args["id"].(int), fc.Args["input"].(model.UpdatePlaceInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.SignedIn == nil { + var zeroVal *models.Place + return zeroVal, errors.New("directive signedIn is not implemented") + } + return ec.Directives.SignedIn(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.Place) graphql.Marshaler { return ec.marshalNPlace2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐPlace(ctx, selections, v) }, @@ -4084,7 +4207,20 @@ func (ec *executionContext) _Mutation_deletePlace(ctx context.Context, field gra fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().DeletePlace(ctx, fc.Args["id"].(int)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.SignedIn == nil { + var zeroVal *models.Place + return zeroVal, errors.New("directive signedIn is not implemented") + } + return ec.Directives.SignedIn(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.Place) graphql.Marshaler { return ec.marshalNPlace2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐPlace(ctx, selections, v) }, @@ -4128,7 +4264,20 @@ func (ec *executionContext) _Mutation_createPost(ctx context.Context, field grap fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().CreatePost(ctx, fc.Args["input"].(model.CreatePostInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.Post + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.Post) graphql.Marshaler { return ec.marshalNPost2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐPost(ctx, selections, v) }, @@ -4172,7 +4321,20 @@ func (ec *executionContext) _Mutation_updatePost(ctx context.Context, field grap fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().UpdatePost(ctx, fc.Args["id"].(int), fc.Args["input"].(model.UpdatePostInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.Post + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.Post) graphql.Marshaler { return ec.marshalNPost2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐPost(ctx, selections, v) }, @@ -4216,7 +4378,20 @@ func (ec *executionContext) _Mutation_deletePost(ctx context.Context, field grap fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().DeletePost(ctx, fc.Args["id"].(int)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.Post + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.Post) graphql.Marshaler { return ec.marshalNPost2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐPost(ctx, selections, v) }, @@ -4260,7 +4435,20 @@ func (ec *executionContext) _Mutation_createUser(ctx context.Context, field grap fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().CreateUser(ctx, fc.Args["input"].(model.CreateUserInput)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.User + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.User) graphql.Marshaler { return ec.marshalNUser2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐUser(ctx, selections, v) }, @@ -4304,7 +4492,20 @@ func (ec *executionContext) _Mutation_deleteUser(ctx context.Context, field grap fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().DeleteUser(ctx, fc.Args["id"].(int)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.User + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.User) graphql.Marshaler { return ec.marshalNUser2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐUser(ctx, selections, v) }, @@ -4348,7 +4549,20 @@ func (ec *executionContext) _Mutation_setUserAdmin(ctx context.Context, field gr fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Mutation().SetUserAdmin(ctx, fc.Args["id"].(int), fc.Args["admin"].(bool)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.User + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.User) graphql.Marshaler { return ec.marshalNUser2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐUser(ctx, selections, v) }, @@ -4389,18 +4603,18 @@ func (ec *executionContext) _Place_id(ctx context.Context, field graphql.Collect return ec.fieldContext_Place_id(ctx, field) }, func(ctx context.Context) (any, error) { - return ec.Resolvers.Place().ID(ctx, obj) + return obj.ID, nil }, nil, - func(ctx context.Context, selections ast.SelectionSet, v int) graphql.Marshaler { - return ec.marshalNID2int(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v uint) graphql.Marshaler { + return ec.marshalNID2uint(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_Place_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("Place", field, true, true, errors.New("field of type ID does not have child fields")) + return graphql.NewScalarFieldContext("Place", field, false, false, errors.New("field of type ID does not have child fields")) } func (ec *executionContext) _Place_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.Place) (ret graphql.Marshaler) { @@ -4642,18 +4856,18 @@ func (ec *executionContext) _Post_id(ctx context.Context, field graphql.Collecte return ec.fieldContext_Post_id(ctx, field) }, func(ctx context.Context) (any, error) { - return ec.Resolvers.Post().ID(ctx, obj) + return obj.ID, nil }, nil, - func(ctx context.Context, selections ast.SelectionSet, v int) graphql.Marshaler { - return ec.marshalNID2int(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v uint) graphql.Marshaler { + return ec.marshalNID2uint(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_Post_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("Post", field, true, true, errors.New("field of type ID does not have child fields")) + return graphql.NewScalarFieldContext("Post", field, false, false, errors.New("field of type ID does not have child fields")) } func (ec *executionContext) _Post_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.Post) (ret graphql.Marshaler) { @@ -4951,7 +5165,20 @@ func (ec *executionContext) _Query_jobAppReferences(ctx context.Context, field g func(ctx context.Context) (any, error) { return ec.Resolvers.Query().JobAppReferences(ctx) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal []*models.JobAppReference + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v []*models.JobAppReference) graphql.Marshaler { return ec.marshalNJobAppReference2ᚕᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐJobAppReferenceᚄ(ctx, selections, v) }, @@ -4983,7 +5210,20 @@ func (ec *executionContext) _Query_jobApplications(ctx context.Context, field gr func(ctx context.Context) (any, error) { return ec.Resolvers.Query().JobApplications(ctx) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal []*models.JobApplication + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v []*models.JobApplication) graphql.Marshaler { return ec.marshalNJobApplication2ᚕᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐJobApplicationᚄ(ctx, selections, v) }, @@ -5016,7 +5256,20 @@ func (ec *executionContext) _Query_jobApplication(ctx context.Context, field gra fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Query().JobApplication(ctx, fc.Args["id"].(int)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.JobApplication + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.JobApplication) graphql.Marshaler { return ec.marshalOJobApplication2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐJobApplication(ctx, selections, v) }, @@ -5091,7 +5344,20 @@ func (ec *executionContext) _Query_places(ctx context.Context, field graphql.Col func(ctx context.Context) (any, error) { return ec.Resolvers.Query().Places(ctx) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.SignedIn == nil { + var zeroVal []*models.Place + return zeroVal, errors.New("directive signedIn is not implemented") + } + return ec.Directives.SignedIn(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v []*models.Place) graphql.Marshaler { return ec.marshalNPlace2ᚕᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐPlaceᚄ(ctx, selections, v) }, @@ -5350,7 +5616,20 @@ func (ec *executionContext) _Query_users(ctx context.Context, field graphql.Coll func(ctx context.Context) (any, error) { return ec.Resolvers.Query().Users(ctx) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal []*models.User + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v []*models.User) graphql.Marshaler { return ec.marshalNUser2ᚕᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐUserᚄ(ctx, selections, v) }, @@ -5383,7 +5662,20 @@ func (ec *executionContext) _Query_user(ctx context.Context, field graphql.Colle fc := graphql.GetFieldContext(ctx) return ec.Resolvers.Query().User(ctx, fc.Args["id"].(int)) }, - nil, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal *models.User + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, func(ctx context.Context, selections ast.SelectionSet, v *models.User) graphql.Marshaler { return ec.marshalOUser2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐUser(ctx, selections, v) }, @@ -5500,18 +5792,18 @@ func (ec *executionContext) _Rowing_id(ctx context.Context, field graphql.Collec return ec.fieldContext_Rowing_id(ctx, field) }, func(ctx context.Context) (any, error) { - return ec.Resolvers.Rowing().ID(ctx, obj) + return obj.ID, nil }, nil, - func(ctx context.Context, selections ast.SelectionSet, v int) graphql.Marshaler { - return ec.marshalNID2int(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v uint) graphql.Marshaler { + return ec.marshalNID2uint(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_Rowing_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("Rowing", field, true, true, errors.New("field of type ID does not have child fields")) + return graphql.NewScalarFieldContext("Rowing", field, false, false, errors.New("field of type ID does not have child fields")) } func (ec *executionContext) _Rowing_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.Rowing) (ret graphql.Marshaler) { @@ -6129,18 +6421,18 @@ func (ec *executionContext) _User_id(ctx context.Context, field graphql.Collecte return ec.fieldContext_User_id(ctx, field) }, func(ctx context.Context) (any, error) { - return ec.Resolvers.User().ID(ctx, obj) + return obj.ID, nil }, nil, - func(ctx context.Context, selections ast.SelectionSet, v int) graphql.Marshaler { - return ec.marshalNID2int(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v uint) graphql.Marshaler { + return ec.marshalNID2uint(ctx, selections, v) }, true, true, ) } func (ec *executionContext) fieldContext_User_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("User", field, true, true, errors.New("field of type ID does not have child fields")) + return graphql.NewScalarFieldContext("User", field, false, false, errors.New("field of type ID does not have child fields")) } func (ec *executionContext) _User_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.User) (ret graphql.Marshaler) { @@ -7525,7 +7817,7 @@ func (ec *executionContext) unmarshalInputCreateJobApplicationInput(ctx context. it.URL = data case "status": ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("status")) - data, err := ec.unmarshalNString2string(ctx, v) + data, err := ec.unmarshalNJobStatus2string(ctx, v) if err != nil { return it, err } @@ -7845,7 +8137,7 @@ func (ec *executionContext) unmarshalInputUpdateJobApplicationInput(ctx context. it.URL = data case "status": ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("status")) - data, err := ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOJobStatus2ᚖstring(ctx, v) if err != nil { return it, err } @@ -8013,67 +8305,34 @@ func (ec *executionContext) _Activity(ctx context.Context, sel ast.SelectionSet, case "__typename": out.Values[i] = graphql.MarshalString("Activity") case "id": - field := field - - innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Activity_id(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&fs.Invalids, 1) - } - return res + out.Values[i] = ec._Activity_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } - - if field.IsDeferred() { - deferredFieldSet.AddField(field) - fieldIndex := len(deferredFieldSet.Values) - 1 - deferredFieldSet.Concurrently(fieldIndex, func(ctx context.Context) graphql.Marshaler { - return innerFunc(ctx, deferredFieldSet) - }) - - for _, deferrable := range field.Deferrables { - view, ok := deferLabelToView[deferrable.Label] - if !ok { - view = deferredFieldSet.NewView() - deferLabelToView[deferrable.Label] = view - } - view.AddIndices(fieldIndex) - } - - // don't run the out.Concurrently() call below - out.Values[i] = graphql.Null - continue - } - - out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) case "createdAt": out.Values[i] = ec._Activity_createdAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "updatedAt": out.Values[i] = ec._Activity_updatedAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "type": out.Values[i] = ec._Activity_type(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "name": out.Values[i] = ec._Activity_name(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "link": out.Values[i] = ec._Activity_link(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) @@ -8147,67 +8406,34 @@ func (ec *executionContext) _Bookmark(ctx context.Context, sel ast.SelectionSet, case "__typename": out.Values[i] = graphql.MarshalString("Bookmark") case "id": - field := field - - innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Bookmark_id(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&fs.Invalids, 1) - } - return res + out.Values[i] = ec._Bookmark_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } - - if field.IsDeferred() { - deferredFieldSet.AddField(field) - fieldIndex := len(deferredFieldSet.Values) - 1 - deferredFieldSet.Concurrently(fieldIndex, func(ctx context.Context) graphql.Marshaler { - return innerFunc(ctx, deferredFieldSet) - }) - - for _, deferrable := range field.Deferrables { - view, ok := deferLabelToView[deferrable.Label] - if !ok { - view = deferredFieldSet.NewView() - deferLabelToView[deferrable.Label] = view - } - view.AddIndices(fieldIndex) - } - - // don't run the out.Concurrently() call below - out.Values[i] = graphql.Null - continue - } - - out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) case "createdAt": out.Values[i] = ec._Bookmark_createdAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "updatedAt": out.Values[i] = ec._Bookmark_updatedAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "category": out.Values[i] = ec._Bookmark_category(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "name": out.Values[i] = ec._Bookmark_name(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "link": out.Values[i] = ec._Bookmark_link(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) @@ -8243,67 +8469,34 @@ func (ec *executionContext) _Favorite(ctx context.Context, sel ast.SelectionSet, case "__typename": out.Values[i] = graphql.MarshalString("Favorite") case "id": - field := field - - innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Favorite_id(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&fs.Invalids, 1) - } - return res + out.Values[i] = ec._Favorite_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } - - if field.IsDeferred() { - deferredFieldSet.AddField(field) - fieldIndex := len(deferredFieldSet.Values) - 1 - deferredFieldSet.Concurrently(fieldIndex, func(ctx context.Context) graphql.Marshaler { - return innerFunc(ctx, deferredFieldSet) - }) - - for _, deferrable := range field.Deferrables { - view, ok := deferLabelToView[deferrable.Label] - if !ok { - view = deferredFieldSet.NewView() - deferLabelToView[deferrable.Label] = view - } - view.AddIndices(fieldIndex) - } - - // don't run the out.Concurrently() call below - out.Values[i] = graphql.Null - continue - } - - out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) case "createdAt": out.Values[i] = ec._Favorite_createdAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "updatedAt": out.Values[i] = ec._Favorite_updatedAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "type": out.Values[i] = ec._Favorite_type(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "name": out.Values[i] = ec._Favorite_name(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "link": out.Values[i] = ec._Favorite_link(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) @@ -8402,72 +8595,39 @@ func (ec *executionContext) _JobAppReference(ctx context.Context, sel ast.Select case "__typename": out.Values[i] = graphql.MarshalString("JobAppReference") case "id": - field := field - - innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._JobAppReference_id(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&fs.Invalids, 1) - } - return res + out.Values[i] = ec._JobAppReference_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } - - if field.IsDeferred() { - deferredFieldSet.AddField(field) - fieldIndex := len(deferredFieldSet.Values) - 1 - deferredFieldSet.Concurrently(fieldIndex, func(ctx context.Context) graphql.Marshaler { - return innerFunc(ctx, deferredFieldSet) - }) - - for _, deferrable := range field.Deferrables { - view, ok := deferLabelToView[deferrable.Label] - if !ok { - view = deferredFieldSet.NewView() - deferLabelToView[deferrable.Label] = view - } - view.AddIndices(fieldIndex) - } - - // don't run the out.Concurrently() call below - out.Values[i] = graphql.Null - continue - } - - out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) case "createdAt": out.Values[i] = ec._JobAppReference_createdAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "updatedAt": out.Values[i] = ec._JobAppReference_updatedAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "category": out.Values[i] = ec._JobAppReference_category(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "label": out.Values[i] = ec._JobAppReference_label(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "value": out.Values[i] = ec._JobAppReference_value(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "sortOrder": out.Values[i] = ec._JobAppReference_sortOrder(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) @@ -8503,92 +8663,59 @@ func (ec *executionContext) _JobApplication(ctx context.Context, sel ast.Selecti case "__typename": out.Values[i] = graphql.MarshalString("JobApplication") case "id": - field := field - - innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._JobApplication_id(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&fs.Invalids, 1) - } - return res + out.Values[i] = ec._JobApplication_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } - - if field.IsDeferred() { - deferredFieldSet.AddField(field) - fieldIndex := len(deferredFieldSet.Values) - 1 - deferredFieldSet.Concurrently(fieldIndex, func(ctx context.Context) graphql.Marshaler { - return innerFunc(ctx, deferredFieldSet) - }) - - for _, deferrable := range field.Deferrables { - view, ok := deferLabelToView[deferrable.Label] - if !ok { - view = deferredFieldSet.NewView() - deferLabelToView[deferrable.Label] = view - } - view.AddIndices(fieldIndex) - } - - // don't run the out.Concurrently() call below - out.Values[i] = graphql.Null - continue - } - - out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) case "createdAt": out.Values[i] = ec._JobApplication_createdAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "updatedAt": out.Values[i] = ec._JobApplication_updatedAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "jobTitle": out.Values[i] = ec._JobApplication_jobTitle(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "company": out.Values[i] = ec._JobApplication_company(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "location": out.Values[i] = ec._JobApplication_location(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "url": out.Values[i] = ec._JobApplication_url(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "status": out.Values[i] = ec._JobApplication_status(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "notes": out.Values[i] = ec._JobApplication_notes(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "appliedAt": out.Values[i] = ec._JobApplication_appliedAt(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "description": out.Values[i] = ec._JobApplication_description(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) @@ -8624,43 +8751,10 @@ func (ec *executionContext) _Message(ctx context.Context, sel ast.SelectionSet, case "__typename": out.Values[i] = graphql.MarshalString("Message") case "id": - field := field - - innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Message_id(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&fs.Invalids, 1) - } - return res + out.Values[i] = ec._Message_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) } - - if field.IsDeferred() { - deferredFieldSet.AddField(field) - fieldIndex := len(deferredFieldSet.Values) - 1 - deferredFieldSet.Concurrently(fieldIndex, func(ctx context.Context) graphql.Marshaler { - return innerFunc(ctx, deferredFieldSet) - }) - - for _, deferrable := range field.Deferrables { - view, ok := deferLabelToView[deferrable.Label] - if !ok { - view = deferredFieldSet.NewView() - deferLabelToView[deferrable.Label] = view - } - view.AddIndices(fieldIndex) - } - - // don't run the out.Concurrently() call below - out.Values[i] = graphql.Null - continue - } - - out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) case "content": out.Values[i] = ec._Message_content(ctx, field, obj) if out.Values[i] == graphql.Null { @@ -8948,92 +9042,59 @@ func (ec *executionContext) _Place(ctx context.Context, sel ast.SelectionSet, ob case "__typename": out.Values[i] = graphql.MarshalString("Place") case "id": - field := field - - innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Place_id(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&fs.Invalids, 1) - } - return res + out.Values[i] = ec._Place_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } - - if field.IsDeferred() { - deferredFieldSet.AddField(field) - fieldIndex := len(deferredFieldSet.Values) - 1 - deferredFieldSet.Concurrently(fieldIndex, func(ctx context.Context) graphql.Marshaler { - return innerFunc(ctx, deferredFieldSet) - }) - - for _, deferrable := range field.Deferrables { - view, ok := deferLabelToView[deferrable.Label] - if !ok { - view = deferredFieldSet.NewView() - deferLabelToView[deferrable.Label] = view - } - view.AddIndices(fieldIndex) - } - - // don't run the out.Concurrently() call below - out.Values[i] = graphql.Null - continue - } - - out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) case "createdAt": out.Values[i] = ec._Place_createdAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "updatedAt": out.Values[i] = ec._Place_updatedAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "title": out.Values[i] = ec._Place_title(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "location": out.Values[i] = ec._Place_location(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "notes": out.Values[i] = ec._Place_notes(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "imageUrl": out.Values[i] = ec._Place_imageUrl(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "category": out.Values[i] = ec._Place_category(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "cost": out.Values[i] = ec._Place_cost(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "priority": out.Values[i] = ec._Place_priority(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "done": out.Values[i] = ec._Place_done(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) @@ -9069,67 +9130,34 @@ func (ec *executionContext) _Post(ctx context.Context, sel ast.SelectionSet, obj case "__typename": out.Values[i] = graphql.MarshalString("Post") case "id": - field := field - - innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Post_id(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&fs.Invalids, 1) - } - return res + out.Values[i] = ec._Post_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } - - if field.IsDeferred() { - deferredFieldSet.AddField(field) - fieldIndex := len(deferredFieldSet.Values) - 1 - deferredFieldSet.Concurrently(fieldIndex, func(ctx context.Context) graphql.Marshaler { - return innerFunc(ctx, deferredFieldSet) - }) - - for _, deferrable := range field.Deferrables { - view, ok := deferLabelToView[deferrable.Label] - if !ok { - view = deferredFieldSet.NewView() - deferLabelToView[deferrable.Label] = view - } - view.AddIndices(fieldIndex) - } - - // don't run the out.Concurrently() call below - out.Values[i] = graphql.Null - continue - } - - out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) case "createdAt": out.Values[i] = ec._Post_createdAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "updatedAt": out.Values[i] = ec._Post_updatedAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "title": out.Values[i] = ec._Post_title(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "author": out.Values[i] = ec._Post_author(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "content": out.Values[i] = ec._Post_content(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) @@ -9638,43 +9666,10 @@ func (ec *executionContext) _Rowing(ctx context.Context, sel ast.SelectionSet, o case "__typename": out.Values[i] = graphql.MarshalString("Rowing") case "id": - field := field - - innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Rowing_id(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&fs.Invalids, 1) - } - return res + out.Values[i] = ec._Rowing_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) } - - if field.IsDeferred() { - deferredFieldSet.AddField(field) - fieldIndex := len(deferredFieldSet.Values) - 1 - deferredFieldSet.Concurrently(fieldIndex, func(ctx context.Context) graphql.Marshaler { - return innerFunc(ctx, deferredFieldSet) - }) - - for _, deferrable := range field.Deferrables { - view, ok := deferLabelToView[deferrable.Label] - if !ok { - view = deferredFieldSet.NewView() - deferLabelToView[deferrable.Label] = view - } - view.AddIndices(fieldIndex) - } - - // don't run the out.Concurrently() call below - out.Values[i] = graphql.Null - continue - } - - out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) case "createdAt": out.Values[i] = ec._Rowing_createdAt(ctx, field, obj) if out.Values[i] == graphql.Null { @@ -10159,62 +10154,29 @@ func (ec *executionContext) _User(ctx context.Context, sel ast.SelectionSet, obj case "__typename": out.Values[i] = graphql.MarshalString("User") case "id": - field := field - - innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._User_id(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&fs.Invalids, 1) - } - return res + out.Values[i] = ec._User_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } - - if field.IsDeferred() { - deferredFieldSet.AddField(field) - fieldIndex := len(deferredFieldSet.Values) - 1 - deferredFieldSet.Concurrently(fieldIndex, func(ctx context.Context) graphql.Marshaler { - return innerFunc(ctx, deferredFieldSet) - }) - - for _, deferrable := range field.Deferrables { - view, ok := deferLabelToView[deferrable.Label] - if !ok { - view = deferredFieldSet.NewView() - deferLabelToView[deferrable.Label] = view - } - view.AddIndices(fieldIndex) - } - - // don't run the out.Concurrently() call below - out.Values[i] = graphql.Null - continue - } - - out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) case "createdAt": out.Values[i] = ec._User_createdAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "updatedAt": out.Values[i] = ec._User_updatedAt(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "username": out.Values[i] = ec._User_username(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } case "admin": out.Values[i] = ec._User_admin(ctx, field, obj) if out.Values[i] == graphql.Null { - atomic.AddUint32(&out.Invalids, 1) + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) @@ -10805,6 +10767,22 @@ func (ec *executionContext) marshalNID2int(ctx context.Context, sel ast.Selectio return res } +func (ec *executionContext) unmarshalNID2uint(ctx context.Context, v any) (uint, error) { + res, err := graphql.UnmarshalUintID(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNID2uint(ctx context.Context, sel ast.SelectionSet, v uint) graphql.Marshaler { + _ = sel + res := graphql.MarshalUintID(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + graphql.AddErrorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + func (ec *executionContext) unmarshalNInt2int(ctx context.Context, v any) (int, error) { res, err := graphql.UnmarshalInt(v) return res, graphql.ErrorOnPath(ctx, err) @@ -10873,6 +10851,22 @@ func (ec *executionContext) marshalNJobApplication2ᚖadamᚑfrenchᚗcoᚗukᚋ return ec._JobApplication(ctx, sel, v) } +func (ec *executionContext) unmarshalNJobStatus2string(ctx context.Context, v any) (string, error) { + res, err := services.UnmarshalJobStatus(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNJobStatus2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + _ = sel + res := services.MarshalJobStatus(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + graphql.AddErrorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + func (ec *executionContext) unmarshalNLoginInput2adamᚑfrenchᚗcoᚗukᚋbackendᚋgraphᚋmodelᚐLoginInput(ctx context.Context, v any) (model.LoginInput, error) { res, err := ec.unmarshalInputLoginInput(ctx, v) return res, graphql.ErrorOnPath(ctx, err) @@ -11370,6 +11364,24 @@ func (ec *executionContext) marshalOJobApplication2ᚖadamᚑfrenchᚗcoᚗukᚋ return ec._JobApplication(ctx, sel, v) } +func (ec *executionContext) unmarshalOJobStatus2ᚖstring(ctx context.Context, v any) (*string, error) { + if v == nil { + return nil, nil + } + res, err := services.UnmarshalJobStatus(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOJobStatus2ᚖstring(ctx context.Context, sel ast.SelectionSet, v *string) graphql.Marshaler { + if v == nil { + return graphql.Null + } + _ = sel + _ = ctx + res := services.MarshalJobStatus(*v) + return res +} + func (ec *executionContext) marshalOPost2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐPost(ctx context.Context, sel ast.SelectionSet, v *models.Post) graphql.Marshaler { if v == nil { return graphql.Null diff --git a/backend/graph/job_app_reference.resolvers.go b/backend/graph/job_app_reference.resolvers.go index 0c77cf0..4fe10d3 100644 --- a/backend/graph/job_app_reference.resolvers.go +++ b/backend/graph/job_app_reference.resolvers.go @@ -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 } diff --git a/backend/graph/job_application.resolvers.go b/backend/graph/job_application.resolvers.go index 60610ad..5cc7491 100644 --- a/backend/graph/job_application.resolvers.go +++ b/backend/graph/job_application.resolvers.go @@ -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 } diff --git a/backend/graph/message.resolvers.go b/backend/graph/message.resolvers.go index c2cc80e..0e2f9de 100644 --- a/backend/graph/message.resolvers.go +++ b/backend/graph/message.resolvers.go @@ -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. diff --git a/backend/graph/middleware.go b/backend/graph/middleware.go index d0d78ec..289e3fa 100644 --- a/backend/graph/middleware.go +++ b/backend/graph/middleware.go @@ -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. diff --git a/backend/graph/place.resolvers.go b/backend/graph/place.resolvers.go index 8d622da..fefa5b7 100644 --- a/backend/graph/place.resolvers.go +++ b/backend/graph/place.resolvers.go @@ -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 } diff --git a/backend/graph/post.resolvers.go b/backend/graph/post.resolvers.go index 329d43c..8dc1e53 100644 --- a/backend/graph/post.resolvers.go +++ b/backend/graph/post.resolvers.go @@ -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 } diff --git a/backend/graph/resolver.go b/backend/graph/resolver.go index 36ea60b..ed25757 100644 --- a/backend/graph/resolver.go +++ b/backend/graph/resolver.go @@ -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 } diff --git a/backend/graph/rowing.resolvers.go b/backend/graph/rowing.resolvers.go index 3e2b4fd..f2249d4 100644 --- a/backend/graph/rowing.resolvers.go +++ b/backend/graph/rowing.resolvers.go @@ -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. diff --git a/backend/graph/schema/activity.graphql b/backend/graph/schema/activity.graphql index 6cd92a2..b729352 100644 --- a/backend/graph/schema/activity.graphql +++ b/backend/graph/schema/activity.graphql @@ -18,5 +18,5 @@ extend type Query { } extend type Mutation { - createActivity(input: CreateActivityInput!): Activity! + createActivity(input: CreateActivityInput!): Activity! @admin } diff --git a/backend/graph/schema/auth.graphql b/backend/graph/schema/auth.graphql index ffaf3a2..41f319b 100644 --- a/backend/graph/schema/auth.graphql +++ b/backend/graph/schema/auth.graphql @@ -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! diff --git a/backend/graph/schema/bookmark.graphql b/backend/graph/schema/bookmark.graphql index 7bd09a9..1c14bbc 100644 --- a/backend/graph/schema/bookmark.graphql +++ b/backend/graph/schema/bookmark.graphql @@ -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 } diff --git a/backend/graph/schema/favorite.graphql b/backend/graph/schema/favorite.graphql index 04a6a0f..ebe225a 100644 --- a/backend/graph/schema/favorite.graphql +++ b/backend/graph/schema/favorite.graphql @@ -18,5 +18,5 @@ extend type Query { } extend type Mutation { - createFavorite(input: CreateFavoriteInput!): Favorite! + createFavorite(input: CreateFavoriteInput!): Favorite! @admin } diff --git a/backend/graph/schema/job_app_reference.graphql b/backend/graph/schema/job_app_reference.graphql index 9ea756a..1084c8b 100644 --- a/backend/graph/schema/job_app_reference.graphql +++ b/backend/graph/schema/job_app_reference.graphql @@ -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 } diff --git a/backend/graph/schema/job_application.graphql b/backend/graph/schema/job_application.graphql index ead39ad..c56d14f 100644 --- a/backend/graph/schema/job_application.graphql +++ b/backend/graph/schema/job_application.graphql @@ -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 } diff --git a/backend/graph/schema/message.graphql b/backend/graph/schema/message.graphql index f710897..b86b417 100644 --- a/backend/graph/schema/message.graphql +++ b/backend/graph/schema/message.graphql @@ -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! diff --git a/backend/graph/schema/place.graphql b/backend/graph/schema/place.graphql index 71a68ad..e6f973d 100644 --- a/backend/graph/schema/place.graphql +++ b/backend/graph/schema/place.graphql @@ -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 } diff --git a/backend/graph/schema/post.graphql b/backend/graph/schema/post.graphql index 1b3f9e0..dce2ff8 100644 --- a/backend/graph/schema/post.graphql +++ b/backend/graph/schema/post.graphql @@ -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 } diff --git a/backend/graph/schema/schema.graphql b/backend/graph/schema/schema.graphql index 395a840..9d567cb 100644 --- a/backend/graph/schema/schema.graphql +++ b/backend/graph/schema/schema.graphql @@ -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 diff --git a/backend/graph/schema/spotify.graphql b/backend/graph/schema/spotify.graphql index fd85aba..7e89811 100644 --- a/backend/graph/schema/spotify.graphql +++ b/backend/graph/schema/spotify.graphql @@ -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! } diff --git a/backend/graph/schema/user.graphql b/backend/graph/schema/user.graphql index 95aa35b..dc7d918 100644 --- a/backend/graph/schema/user.graphql +++ b/backend/graph/schema/user.graphql @@ -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 } diff --git a/backend/graph/spotify.resolvers.go b/backend/graph/spotify.resolvers.go index 83ecfba..d25d5da 100644 --- a/backend/graph/spotify.resolvers.go +++ b/backend/graph/spotify.resolvers.go @@ -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 } diff --git a/backend/graph/user.resolvers.go b/backend/graph/user.resolvers.go index a1f98ff..dc2afaf 100644 --- a/backend/graph/user.resolvers.go +++ b/backend/graph/user.resolvers.go @@ -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 } diff --git a/backend/handlers/handle_job_capture.go b/backend/handlers/handle_job_capture.go index c3215f4..d09d9af 100644 --- a/backend/handlers/handle_job_capture.go +++ b/backend/handlers/handle_job_capture.go @@ -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 ". @@ -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"}) diff --git a/backend/handlers/handle_job_capture_test.go b/backend/handlers/handle_job_capture_test.go index 555dbba..993d3a0 100644 --- a/backend/handlers/handle_job_capture_test.go +++ b/backend/handlers/handle_job_capture_test.go @@ -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) } }) } diff --git a/backend/handlers/handle_rowing.go b/backend/handlers/handle_rowing.go index db53ba4..5a4744e 100644 --- a/backend/handlers/handle_rowing.go +++ b/backend/handlers/handle_rowing.go @@ -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 diff --git a/backend/handlers/handle_rowing_test.go b/backend/handlers/handle_rowing_test.go index 33ae8d0..99dff2b 100644 --- a/backend/handlers/handle_rowing_test.go +++ b/backend/handlers/handle_rowing_test.go @@ -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) } }) } diff --git a/backend/handlers/store.go b/backend/handlers/store.go index 7ee16e0..1d717e2 100644 --- a/backend/handlers/store.go +++ b/backend/handlers/store.go @@ -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), diff --git a/backend/main.go b/backend/main.go index 1c4f4fc..1d95e03 100644 --- a/backend/main.go +++ b/backend/main.go @@ -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{}) diff --git a/backend/models/models.go b/backend/models/models.go index c5765ed..566aa21 100644 --- a/backend/models/models.go +++ b/backend/models/models.go @@ -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 diff --git a/backend/services/auth_test.go b/backend/services/auth_test.go index 277e3e6..3629195 100644 --- a/backend/services/auth_test.go +++ b/backend/services/auth_test.go @@ -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, diff --git a/backend/services/claude.go b/backend/services/claude.go deleted file mode 100644 index ab13a5e..0000000 --- a/backend/services/claude.go +++ /dev/null @@ -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 -} diff --git a/backend/services/email_classify_test.go b/backend/services/email_classify_test.go new file mode 100644 index 0000000..05cdbac --- /dev/null +++ b/backend/services/email_classify_test.go @@ -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: "

Thanks for applying

"}, + } + email.From.EmailAddress = graphEmailAddress{Name: "Acme Hiring", Address: "no-reply@greenhouse.io"} + 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 \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") + } +} diff --git a/backend/services/email_status_test.go b/backend/services/email_status_test.go index 17b3820..1d2825b 100644 --- a/backend/services/email_status_test.go +++ b/backend/services/email_status_test.go @@ -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 { diff --git a/backend/services/email_sync.go b/backend/services/email_sync.go index 43c199f..618b81f 100644 --- a/backend/services/email_sync.go +++ b/backend/services/email_sync.go @@ -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