Editor API

The Rust backend behind the law editor: corpus reads, traject-scoped writes, tasks, and proxies to the pipeline and harvester-admin services.

The editor API is the HTTP server behind the law editor. It serves the compiled frontend, exposes the corpus over REST, and runs every write the editor makes. Writes always go to a traject: an editing session with its own members and its own corpus repository branch.

Overview

  • Language: Rust (Axum)
  • Location: packages/editor-api/
  • Port: 8000 (fixed in serve() in main.rs)
  • Database: PostgreSQL, shared with the pipeline. Sessions, accounts, trajects, favorites, notes, tasks and feature flags live there. Migrations come from the pipeline crate (regelrecht_pipeline::ensure_schema).

Authorization model

Every route sits in one router group, and each group carries one role gate. The groups and their gates are put together in one place, router() in packages/editor-api/src/router.rs; the binary serves that router behind its session layer, and tests send requests through the same function. The roles are Keycloak realm roles: editor-reader, editor-writer, editor-admin, plus harvester-reader for the harvester proxy. Keycloak composite roles make a writer also a reader. See Auth and roles for the role model.

GateWhat it checks
PublicNothing. Reads the global corpus only.
ReaderSession carries editor-reader.
WriterSession carries editor-writer.
AdminSession carries editor-admin.
+ accountThe request also resolves an accounts row (account_middleware). Without a database this answers 503.
+ membershipThe handler checks traject membership on every request. Some actions are owner-only.

A missing session answers 401, a missing role 403. When OIDC is not configured, every role gate passes: that mode exists for local development only, and the server logs a warning at startup. In that mode there is no database pool, so every route that needs an account answers 503, and the GitHub OAuth routes are not mounted at all.

The login itself has a separate gate: OIDC_REQUIRED_ROLE is the minimum role needed to complete a login at all.

tests/router_gates_test.rs holds the gate of every route as a table and checks it through the router, with a memory session store and no database: 401 without a session, 403 with every role except the required one, and past the gate with that role. A second test reads the methods each .route(..) call in router.rs and github_oauth.rs mounts and compares them with the table, so a new route, or a new method on an existing path, fails the tests until it has a row. That check reads the source because HTTP cannot tell: a gate runs before the method is matched, so an unmounted method answers like a mounted one.

Endpoints

Derived from the router in packages/editor-api/src/router.rs (and github_oauth.rs for /auth/github/*). That file is the authority, and tests/router_gates_test.rs holds its gates as a table; this list is a map of it.

Service and session

MethodPathGate
GET/health, /health/readyPublic (liveness and readiness; see Health checks)
GET/auth/login, /auth/callback, /auth/logout, /auth/statusPublic (OIDC flow from regelrecht-auth)
GET/api/feature-flagsPublic
PUT/api/feature-flags/{key}Admin
GET/api/document-upload-formatsPublic

Any other path falls through to the single-page app in STATIC_DIR.

Global corpus (read-only)

All public. These serve the global corpus, without any traject overlay.

MethodPath
GET/api/sources
GET/api/corpus/laws
GET/api/corpus/laws/{law_id}
GET/api/corpus/laws/{law_id}/versions
GET/api/corpus/laws/{law_id}/outputs
GET/api/corpus/laws/{law_id}/scenarios
GET/api/corpus/laws/{law_id}/scenarios/{filename}
GET/api/corpus/laws/{law_id}/annotations
POST/api/corpus/reload (Admin)

Startup reads only the source registry and the GitHub settings, so it does not wait for GitHub, and a traject created at that moment gets its sources. The global corpus loads in the background (corpus_load.rs). Until it is in, the global law, scenario and annotation routes answer 503 with X-Error-Code: corpus_loading and a Retry-After header. /api/sources does answer, with loading: true on every source. Traject routes and /health/ready do not depend on the global corpus.

A load first sets up the backends that are still missing. It then loads every local source and every law of a GitHub source marked load_all, and indexes the other laws of each GitHub source by path from one tree listing, so search finds them. The laws and their backends become visible in one step. The sources load independently: one that fails is reported as index_error and does not hold up the others. That includes a GitHub source whose backend is not ready, which is left out, and a load_all source of which some files could not be fetched or were refused because another source at the same priority supplies that law.

While there is nothing to serve, the load is tried again after 5 seconds, doubling to at most 60. Once the corpus is available, the bodies of the laws listed in favorites.json are fetched; until they are in, a favourite is read like any other indexed law. If a source failed or a favourite has no body yet, the load is tried again at most five times. A corpus that is available is replaced only when nothing is lost by it. The current corpus stays when a source newly fails, or when a law would lose its version or body because something could not be read. That is tracked per source and per law: the source that supplied the law was not read, or its file for that law could not be fetched. Another source does not replace it then, unless it has priority for the same version. A law that moved to another source also counts when its body could not be fetched there. A change that was read, such as a law that was removed or moved, is an update, even while the same source fails on another law. This also holds for POST /api/corpus/reload, which then answers 500. A request works on the corpus as it was when the request came in and holds no lock while it waits for GitHub. All loads hold one lock, so a reload requested during another load answers 429. The bodies of the indexed laws are fetched from GitHub when someone opens one, and kept in a cache of at most 1024 bodies that a reload empties. Until then such a law has no name and never counts as enriched, so search matches it on its $id only. Anyone can open a law without an account, and each uncached body costs a call on the service token that trajecten also read with, so the global scope fetches at most 1000 bodies an hour (GLOBAL_FETCHES_PER_HOUR); past that an uncached law answers 503 with X-Error-Code: fetch_limit_reached until the hour is over. A GitHub source that fails to list is reported as index_error on /api/sources. A reload fetches again only the bodies that were loaded up front, plus any law it is asked for, and lists the sources again. The current version of a law is the one in force today among the versions loaded, across sources (see Federated Corpus).

/api/corpus/laws (and its traject variant) filters with q (search: every word of the query must occur in the law’s id or name, in any order, ignoring case and accents; a query without letters or digits finds nothing, and only its first 200 characters and 10 distinct words count), ids (exact ids), source (one source), enriched=true (only laws whose current version is enriched) and loaded=true (only laws whose body is loaded, the ones that carry a name; the editor asks for these to show display names). A search returns the best matches first, within each source in priority order: a law whose id or name is the query, then one that starts with it (as characters, so wetboek counts for wet), then one where every word sits at the start or end of a word (a Dutch compound such as zorgverzekeringswet ends in its head), then any other match. Laws whose body is loaded go before the rest of the same rank, then the shorter id. The total before the cap is in X-Total-Count. Each entry carries enriched, and, when the current version is not enriched but another version is, enriched_version with that version’s date. A law from a source marked enriched: false never counts as enriched. A law from a GitHub source carries source_url, the folder of its current version on GitHub at the ref the source reads (inside a traject, the traject’s branch for its own repository).

Error codes

The status 503 has several causes, so every 503 that the editor API produces itself names its cause in the X-Error-Code header (error.rs). Only the readiness probe /health/ready answers 503 without a code. Two tests guard this. One scans the source and fails when another file names the status or passes a literal 503 to a call. The other requests every route on a server without a database and fails on a 503 without a code. A 503 without the header can come from the ingress, for example during a deploy, or from a service behind /api/harvest/* or /api/harvest-admin/*, whose status is passed on. The code does not change the body: plain text, JSON for the feature flags, or empty. Not every message is written for a user, so the frontend shows one only for the codes it lists as such.

CodeMeaning
corpus_loadingThe global corpus has not been loaded yet. Try again after Retry-After seconds.
fetch_limit_reachedThis hour’s fetches for the global scope are used up. Trying again soon does not help.
database_unavailableThe request needs a database, and the server has no database pool, as when OIDC is off.
account_unavailableThe route needs an account, and the session has no user to find one for.
source_unavailableThe source that the traject reads from or writes to has no backend.
service_not_configuredA setting is missing: the URL of the pipeline API or the harvester-admin API, or the token for a repository.
github_unreachableGitHub could not be reached, or its rate limit is used up.
github_client_failedThe GitHub client could not be built.

Trajects

Reader + account for reads, Writer + account for changes. Membership is checked in the handler.

MethodPathNotes
GET/api/trajectsTrajects you are a member of
POST/api/trajectsCreator becomes owner
GET/api/trajects/{id}
PATCH, DELETE/api/trajects/{id}Owner only
POST/api/trajects/{id}/leave
POST/api/trajects/{id}/membersOwner only; adds a member or an invite
PATCH, DELETE/api/trajects/{id}/members/{account_id}Owner only
DELETE/api/trajects/{id}/invites/{email}Owner only
GET/api/trajects/{traject_ref}/integrityIntegrity report over the traject’s corpus repo
GET/api/trajects/{traject_ref}/sources
GET/api/trajects/{traject_ref}/runsThe traject’s harvests, enrichments and conversions, running or finished, newest first (at most 200), from every member. ?law_id= narrows them to one law, &bwb_id= adds the harvest that fetched it. See below
GET/api/trajects/{traject_ref}/favorites
PUT, DELETE/api/trajects/{traject_ref}/favorites/{law_id}

Member roles are owner and contributor.

A run belongs to a traject through the ref it was requested under, matched on the id part at its end, so the runs of a renamed traject stay with it. Each run carries its state, its timestamps, the name of the member who requested it, the last error, and for an enrichment the provider, the article counts from its result and how its review tasks were resolved, with a separate count of the open ones assigned to the member asking. While a run is processing it also carries activity: the step it is in and how many of the law’s articles are executable. That is all the editor gets of the worker’s progress (see Pipeline: Progress and stalls). The running jobs in /api/tasks carry the same activity, with attempts and max_attempts.

With law_id, the list holds the runs whose law_id is that law’s $id (its enrichments), plus, with bwb_id, the traject harvest that carries that BWB id: a harvest is requested before the law has an $id. The filter is applied in the query, so the cap of 200 counts that law’s runs only.

Traject corpus

The traject-scoped view of the corpus: the global corpus with the traject’s own changes on top. Reads are Reader + account, writes Writer + account, and all of them check membership.

MethodPathGate
GET/api/trajects/{traject_ref}/corpus/lawsReader
POST/api/trajects/{traject_ref}/corpus/lawsWriter; create a new law (body cap 5 MiB)
POST/api/trajects/{traject_ref}/corpus/laws/uploadWriter; upload a law document for conversion (25 MiB)
GET/api/trajects/{traject_ref}/corpus/changed-lawsReader
GET, PUT/api/trajects/{traject_ref}/corpus/laws/{law_id}Reader / Writer (5 MiB)
GET.../corpus/laws/{law_id}/versionsReader
GET.../corpus/laws/{law_id}/outputsReader
GET.../corpus/laws/{law_id}/implementorsReader
GET.../corpus/laws/{law_id}/scenariosReader
GET, PUT, DELETE.../corpus/laws/{law_id}/scenarios/{filename}Reader / Writer (1 MiB)
GET, PUT.../corpus/laws/{law_id}/annotationsReader / Writer (1 MiB)
POST.../corpus/laws/{law_id}/promoteWriter; copy a law from the central corpus into the traject repo
POST.../corpus/laws/{law_id}/enrichWriter; request an enrichment task. An optional body {"provider": "opencode"} picks the provider; without it TASK_ENRICH_PROVIDER decides, and an unknown name returns 400
POST/api/trajects/{traject_ref}/corpus/harvestWriter; harvest a law into the traject via a task
GET/api/trajects/{traject_ref}/corpus/documentsReader
POST.../corpus/documents/uploadWriter; PDF or Word, converted to markdown asynchronously (25 MiB)
GET.../corpus/documents/jobsReader; running conversions
DELETE.../corpus/documents/jobs/{job_id}Reader; any member may cancel a conversion
GET, PUT, DELETE.../corpus/documents/{*doc_path}Reader / Writer (1 MiB)

... stands for /api/trajects/{traject_ref}.

The first request to a traject after a restart builds its index, and every request waits for that build. After that the index is served from memory and refreshed in the background once it is a minute old. A later request waits only when the traject’s own repository could not be listed and its own GitHub token can repair the index. The list of changed laws works the same way: when only a member’s own GitHub token can read the traject repository, the first member past the minute lends that token to the background refresh and gets the previous list meanwhile.

A build or a refresh lists the tree of each source, all sources at the same time and while the backends check their branches. A listing is kept per repository branch together with the commit it was taken at, and reused as long as the branch still points at that commit, so GitHub is only asked for the commit. The global corpus lists the central corpus at startup, which leaves a traject build only its own repository to list, and a refresh fetches a tree only after a new commit. Reusing a listing takes the commit, which GitHub shows only to someone who can read the repository.

The index of a traject holds the laws of a GitHub source by path, and a law’s body is fetched when someone opens it. A fetched body is kept, per version file and at most 1024 per traject, together with the git blob sha of its text. A refresh keeps the bodies whose file the new listing reports with that same sha and drops the others, so an unchanged law is fetched once and a changed one is fetched again within a minute. A save through the editor drops the kept body of that law; the saved text is served from then on.

A law without notes gets an empty notes document (annotations: []) with status 200; a 404 means the law is not in the traject. Whether a law has notes comes from the tree listing of the index, at the repository root or at the older location under the source’s subpath, so a law without notes costs no call to GitHub. A note saved through the editor counts at once; a notes file added to the repository some other way shows up with the next refresh.

Tasks

Review tasks produced by asynchronous jobs, scoped to the account that requested them. Reader + account for reads, Writer + account for resolving.

MethodPath
GET/api/tasks
GET/api/tasks/{task_id}
POST/api/tasks/{task_id}/resolve
GET/api/tasks/jobs/{job_id}
POST/api/tasks/jobs/{job_id}/apply

Personal data

MethodPathGate
GET/api/favoritesReader
PUT, DELETE/api/favorites/{law_id}Reader
GET/api/user/settingsReader
PUT/api/user/settings/{key}Writer (4 KiB body)
GET/api/user/notes/{law_id}Reader + account
POST/api/user/notes/{law_id}Writer + account (128 KiB)
PUT, DELETE/api/user/notes/{law_id}/{note_id}Writer + account

Personal notes stay in Postgres and never reach a git repository.

Harvesting and the harvester-admin proxy

MethodPathGateForwards to
GET/api/harvest/statusPublicpipeline-api /harvest/status
GET/api/harvest/searchReaderpipeline-api /harvest/search
POST/api/harvestWriterpipeline-api /harvest
POST/api/harvest/batchWriterpipeline-api /harvest/batch
any/api/harvest-admin/{*rest}harvester-readerharvester-admin /api/{rest}

The pipeline proxy strips /api and forwards only content-type. The search endpoint is behind a login because it makes outbound requests to zoekservice.overheid.nl.

The harvester-admin proxy is how the editor’s Corpusinwinning section reaches the harvester-admin API; the browser never calls that API directly. It also forwards the session cookie. The two services share the Postgres session store, so harvester-admin resolves the same session and enforces its own harvester-writer and harvester-admin gates. The harvester-reader gate here is a first filter only.

Both proxies answer 503 when their upstream URL cannot be resolved.

Only mounted when OIDC is enabled. Writer + account, except the relay.

MethodPathNotes
GET/auth/github/loginStart the OAuth flow
GET/auth/github/callback
GET/auth/github/statusWhether a token is linked, and whether one is required
POST/auth/github/disconnect
GET/auth/github/relayPublic. Forwards the OAuth callback from the fixed callback host to the originating deployment, limited to GITHUB_OAUTH_ALLOWED_ORIGIN_SUFFIXES

When GITHUB_OAUTH_* is not configured the handlers answer 501. The github.user_oauth feature flag decides whether traject writes require the user’s own token.

Configuration

Service

From main.rs, config.rs and packages/shared/src/telemetry.rs.

VariableDefaultPurpose
STATIC_DIRstaticCompiled frontend to serve
DATABASE_URLnonePostgres connection. Required when OIDC is on; DATABASE_SERVER_FULL is accepted as fallback. Without OIDC no pool is opened.
HOSTNAMEset by the platformPod hostname. When it names a ZAD deployment, the proxy targets are derived from it and win over the two variables below.
PIPELINE_API_URLnonePipeline-api base URL when HOSTNAME does not yield one (http://<deployment>-pipelineapi:8000)
HARVEST_ADMIN_URLnoneHarvester-admin base URL when HOSTNAME does not yield one (http://<deployment>-harvester-admin:8000)
TASK_ENRICH_PROVIDERclaudeDefault LLM provider for enrichment tasks requested from a traject; a request may name another. Must be one of the pipeline’s providers (opencode, claude); any other value stops startup.
RUST_LOGinfoLog filter
LOG_FORMATtextjson for one JSON object per log line
LOG_SPAN_EVENTSon for this serviceSpan-close timing lines; none turns them off

Login (OIDC)

From packages/auth/src/config.rs, shared with harvester-admin. Leaving OIDC_CLIENT_ID unset disables login entirely.

VariableDefaultPurpose
OIDC_CLIENT_IDnoneEnables OIDC when set
OIDC_CLIENT_SECRETnoneRequired once OIDC_CLIENT_ID is set
OIDC_DISCOVERY_URLnoneIssuer discovery URL; takes priority over the Keycloak pair
KEYCLOAK_BASE_URL, KEYCLOAK_REALMnoneBuild the issuer as <base>/realms/<realm> when there is no discovery URL
OIDC_REQUIRED_ROLEallowed-userMinimum realm role to log in. Set it to editor-reader; the default only exists for old deployments and logs a warning.
BASE_URLderived from request headersPublic origin used for redirect URLs. An http://localhost value also drops the Secure flag from the session cookie.

Corpus

From read_corpus_config in main.rs, packages/corpus/src/auth.rs and, for GITHUB_API_BASE, packages/github/src/client.rs.

VariableDefaultPurpose
CORPUS_REGISTRY_PATHcorpus-registry.yamlRegistry manifest with the corpus sources
CORPUS_REGISTRY_LOCAL_PATHcorpus-registry.local.yamlLocal overrides on the manifest
CORPUS_AUTH_FILEcorpus-auth.yamlPer-source tokens, file-backed
CORPUS_AUTH_<KEY>_TOKENnonePer-source token; checked before the auth file
CORPUS_GIT_TOKENnoneShared fallback token for manifest sources. Never used for a repository a user chose.
GITHUB_API_BASEhttps://api.github.comGitHub API base; a test seam, and usable for GitHub Enterprise

CORPUS_REPO_URL and CORPUS_BRANCH are not read by this service. They configure the corpus checkout of the pipeline workers; see Pipeline.

From github_oauth.rs. The first three are all-or-nothing: set all of them or none, or startup fails.

VariableDefaultPurpose
GITHUB_OAUTH_CLIENT_IDnoneOAuth app client id
GITHUB_OAUTH_CLIENT_SECRETnoneOAuth app secret
GITHUB_TOKEN_ENC_KEYnoneBase64 key that encrypts the stored user token
GITHUB_OAUTH_SCOPESrepo read:orgRequested scopes
GITHUB_USER_TOKEN_REQUIREDfalse1 or true forces a personal token for traject writes, regardless of the feature flag
GITHUB_OAUTH_CALLBACK_BASEnoneFixed callback host for relay mode (preview deployments)
GITHUB_OAUTH_ALLOWED_ORIGIN_SUFFIXESnoneComma-separated host suffixes the relay may forward to. Required when GITHUB_OAUTH_CALLBACK_BASE is set.

Running locally

just editor-api # cargo run -p regelrecht-editor-api, no login just editor-sso # same, with a real Keycloak login from .env.sso-local

STATIC_DIR defaults to static, relative to packages/. The just recipes that run this API locally (editor-api, editor-sso, dev) set CORPUS_REGISTRY_PATH to the repository’s corpus-registry.yaml and STATIC_DIR to frontend/public, where favorites.json lives, so a local run loads the same sources and favorites as the image. For frontend work, just dev editor starts this API with a Vite dev server in front of it, logged in against the central Keycloak (it needs .env.sso-local). just dev all adds a local harvester-admin on port 8001 and points HARVEST_ADMIN_URL at it; without it the Corpusinwinning screens answer 503. See Editor.

Further reading

RegelRecht

An exploration into transparent, executable legislation, and one of the three projects in the starting selection of the Nederlandse Digitale Dienst.

Links

GitHub repository
How it works
Demo walkthrough
Stay informed
Roadmap (Dutch)
Documentation
Research
Basiswerk recht (Dutch)

Contact

regelrecht@minbzk.nl

Part of

Nederlandse Digitale Dienst
Ministry of Economic Affairs and Climate Policy