diff --git a/.env.example b/.env.example index 907c41b9c..533d85cfc 100644 --- a/.env.example +++ b/.env.example @@ -17,6 +17,13 @@ DATABASE_URL=postgres://openconditions:openconditions@localhost:5432/openconditi # OPENCONDITIONS_SECRETS_KEY_FILE may name a file holding it instead. OPENCONDITIONS_SECRETS_KEY= +# Instance id (REQUIRED): a lower-case DNS name, usually the instance's public +# host name, e.g. maps.example.org. Set it once, before the first start, to the +# same value on every OpenConditions service of the instance. The first ingest +# start seals it in the database, and every service refuses another id; it is +# part of every record id, so it never changes. +OPENCONDITIONS_INSTANCE_ID= + # HTTP server (optional; defaults shown) PORT=4100 HOST=0.0.0.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6b0555efa..5ebd35a92 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,8 +41,13 @@ Requirements: ```bash pnpm install -# Run the ingest service against a local PostGIS (any reachable PostGIS works): +# Run the ingest service against a local PostGIS (any reachable PostGIS works), +# with a secrets key kept in a file Git ignores and a development instance id; +# the database is sealed to both on the first start: +[ -f .secrets-key ] || (umask 077 && openssl rand -hex 32 > .secrets-key) DATABASE_URL=postgres://postgres:postgres@localhost:5432/openconditions \ +OPENCONDITIONS_SECRETS_KEY_FILE="$PWD/.secrets-key" \ +OPENCONDITIONS_INSTANCE_ID=dev.localhost \ pnpm --filter @openconditions/ingest dev # Work on the Python resolver: diff --git a/LICENSING.md b/LICENSING.md index 3fa6afc24..fb64a1498 100644 --- a/LICENSING.md +++ b/LICENSING.md @@ -18,6 +18,10 @@ default. Packages that carry a different license have their own `LICENSE` file and a matching `license` field in their `package.json` (or `pyproject.toml`); that per-package license takes precedence for that package. +The OpenMapX extension bundle (`extension.json`) installs only the ingest and +contributions services, so it declares their licence, AGPL-3.0-or-later, and +every service manifest declares the licence of the service it runs. + The third-party Docker images OpenConditions runs alongside (PostGIS, and — when self-hosting OpenMapX — Valhalla, Redis, …) run as **separate containers communicating over the network**. They are not linked into OpenConditions' code diff --git a/README.md b/README.md index 630b53c19..02f0a5991 100644 --- a/README.md +++ b/README.md @@ -127,10 +127,11 @@ pnpm build DATABASE_URL=postgres://postgres:postgres@localhost:5432/openconditions \ OPENCONDITIONS_SECRETS_KEY_FILE="$PWD/.secrets-key" \ +OPENCONDITIONS_INSTANCE_ID=dev.localhost \ pnpm --filter @openconditions/ingest dev ``` -The service applies its migrations, starts polling the enabled feeds, and serves on `:4100`. Keep `.secrets-key`: a start with another key refuses to read what the first one stored (see [secrets encrypted at rest](#secrets-encrypted-at-rest)). +The service applies its migrations, starts polling the enabled feeds, and serves on `:4100`. Keep `.secrets-key`: a start with another key refuses to read what the first one stored (see [secrets encrypted at rest](#secrets-encrypted-at-rest)). Keep the instance id too: the database is sealed to it (see [the instance id](#the-instance-id)). ### Public API @@ -143,7 +144,13 @@ also `minSeverity`, `horizonDays`, `subtype`, a time window `from`/`to` that inc TraFF is a [complete bounded feed](docs/traff.md), with no page controls or continuation header. `canonical=1` serves the canonical view: one feature per cluster of features several sources describe, and the fused reading of a property several sources or the crowd report. Everything is rate-limited; `GET /openapi.json` -describes it all, and [storage](docs/storage.md#read-api) says what each route reads. +describes it all, the routing, speed and status products (`/feeds/status`, `/valhalla/exclusions.json`, +`/segments.geojson`, `/segments/speed.csv`, `/segments/profiles.json`, `/segments/conditions.json`) +included, and [storage](docs/storage.md#read-api) says what each route reads. + +Paths never break. A path keeps its meaning, and its responses may gain members but never lose or +change one. A breaking change gets a new path, and the old path keeps serving its contract, so the +paths carry no version prefix. | Endpoint | Content | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ | @@ -199,6 +206,14 @@ charging layer, the webcam layer and the hazard overlays. A request carrying `Au public-scope. Reads with a bbox fetch stale on-demand feeds first, waiting at most `OPENCONDITIONS_ON_DEMAND_DEADLINE_MS` (default 3000). See [services/ingest/README.md](services/ingest/README.md). +## The instance id + +Every record an instance originates is named `oc:::`, federation peers know the instance by that id, and crowd votes are signed over record ids. The id therefore never changes once records exist. `OPENCONDITIONS_INSTANCE_ID` is required, with no default, on every OpenConditions service: the ingest service, the heavy-feeds ingest process, the contributions API and the federation service, all with the same value. It is a lower-case DNS name, labels of letters, digits and inner dashes up to 63 characters joined by single dots, at most 253 characters, for example the instance's public host name `maps.example.org`. + +After migrating, the first ingest process to start seals the id in `conditions.instance_identity`, once. Every service then refuses to start with another id, naming the sealed one, and the contributions and federation services wait at start until the row is there. A service also refuses to start without the variable or with a value that is not a DNS name. + +To use another id, for example after sealing a typo on the first start, start the OpenConditions data over: the stored records, the crowd's signed votes and every peer's copies carry the sealed id. Stop every OpenConditions service, drop the schema that holds all of it with `DROP SCHEMA conditions CASCADE` (as the ingest service's role, which owns it), set the new id on every service and start the ingest service first. Under OpenMapX the database is OpenMapX's own, so drop only the `conditions` schema, never the database. Deleting the one row of `conditions.instance_identity` instead is enough only while the ingest service is stopped and no record carries the old id yet: `feature`, `offer` and `situation` have no row with that `instance_id`. + ## Secrets encrypted at rest OpenConditions keeps three kinds of secret in its tables: the OAuth grants of feeds that need an account login (the access and refresh tokens, for example EUMETSAT's), the contributions API's token-issuer private keys, and the federation service's instance private keys. They are stored encrypted with AES-256-GCM under one key, `OPENCONDITIONS_SECRETS_KEY`. The OpenConditions tables never hold that key. Each value is bound to its table, column and row, so a value copied to another row does not decrypt. A dump of the OpenConditions tables therefore holds none of these secrets in clear. diff --git a/atlas/cameras.json b/atlas/cameras.json index fe3048e84..a2591b055 100644 --- a/atlas/cameras.json +++ b/atlas/cameras.json @@ -1565,7 +1565,7 @@ "overpass": { "url": { "title": "Overpass URL", - "description": "Base URL of the Overpass instance (http://overpass:80, https://overpass-api.de) or its full interpreter URL (http://overpass:80/api/interpreter), as OpenMapX's OVERPASS_URL accepts: queries go to the base URL plus /api/interpreter. Defaults to the public instance, which allows about 10,000 requests a day; point it at a self-hosted Overpass for heavier use. A private host also needs OPENCONDITIONS_EGRESS_ALLOWED_HOSTS.", + "description": "Base URL of the Overpass instance (http://openmapx-overpass:80, https://overpass-api.de) or its full interpreter URL (http://openmapx-overpass:80/api/interpreter), as OpenMapX's OVERPASS_URL accepts: queries go to the base URL plus /api/interpreter. Defaults to the public instance, which allows about 10,000 requests a day; point it at a self-hosted Overpass for heavier use. A private host also needs OPENCONDITIONS_EGRESS_ALLOWED_HOSTS.", "default": "https://overpass-api.de" } }, diff --git a/atlas/charging.json b/atlas/charging.json index 018c46b82..3c468b323 100644 --- a/atlas/charging.json +++ b/atlas/charging.json @@ -1639,7 +1639,7 @@ "overpass": { "url": { "title": "Overpass URL", - "description": "Base URL of the Overpass instance (http://overpass:80, https://overpass-api.de) or its full interpreter URL (http://overpass:80/api/interpreter), as OpenMapX's OVERPASS_URL accepts: queries go to the base URL plus /api/interpreter. Defaults to the public instance, which allows about 10,000 requests a day; point it at a self-hosted Overpass for heavier use. A private host also needs OPENCONDITIONS_EGRESS_ALLOWED_HOSTS.", + "description": "Base URL of the Overpass instance (http://openmapx-overpass:80, https://overpass-api.de) or its full interpreter URL (http://openmapx-overpass:80/api/interpreter), as OpenMapX's OVERPASS_URL accepts: queries go to the base URL plus /api/interpreter. Defaults to the public instance, which allows about 10,000 requests a day; point it at a self-hosted Overpass for heavier use. A private host also needs OPENCONDITIONS_EGRESS_ALLOWED_HOSTS.", "default": "https://overpass-api.de" } }, diff --git a/atlas/fuel.json b/atlas/fuel.json index 0b9158368..518c9ab3d 100644 --- a/atlas/fuel.json +++ b/atlas/fuel.json @@ -266,7 +266,7 @@ "overpass": { "url": { "title": "Overpass URL", - "description": "Base URL of the Overpass instance (http://overpass:80, https://overpass-api.de) or its full interpreter URL (http://overpass:80/api/interpreter), as OpenMapX's OVERPASS_URL accepts: queries go to the base URL plus /api/interpreter. Defaults to the public instance, which allows about 10,000 requests a day; point it at a self-hosted Overpass for heavier use. A private host also needs OPENCONDITIONS_EGRESS_ALLOWED_HOSTS.", + "description": "Base URL of the Overpass instance (http://openmapx-overpass:80, https://overpass-api.de) or its full interpreter URL (http://openmapx-overpass:80/api/interpreter), as OpenMapX's OVERPASS_URL accepts: queries go to the base URL plus /api/interpreter. Defaults to the public instance, which allows about 10,000 requests a day; point it at a self-hosted Overpass for heavier use. A private host also needs OPENCONDITIONS_EGRESS_ALLOWED_HOSTS.", "default": "https://overpass-api.de" } } diff --git a/atlas/parking.json b/atlas/parking.json index f9d69c077..991cb2078 100644 --- a/atlas/parking.json +++ b/atlas/parking.json @@ -1664,7 +1664,7 @@ "overpass": { "url": { "title": "Overpass URL", - "description": "Base URL of the Overpass instance (http://overpass:80, https://overpass-api.de) or its full interpreter URL (http://overpass:80/api/interpreter), as OpenMapX's OVERPASS_URL accepts: queries go to the base URL plus /api/interpreter. Defaults to the public instance, which allows about 10,000 requests a day; point it at a self-hosted Overpass for heavier use. A private host also needs OPENCONDITIONS_EGRESS_ALLOWED_HOSTS.", + "description": "Base URL of the Overpass instance (http://openmapx-overpass:80, https://overpass-api.de) or its full interpreter URL (http://openmapx-overpass:80/api/interpreter), as OpenMapX's OVERPASS_URL accepts: queries go to the base URL plus /api/interpreter. Defaults to the public instance, which allows about 10,000 requests a day; point it at a self-hosted Overpass for heavier use. A private host also needs OPENCONDITIONS_EGRESS_ALLOWED_HOSTS.", "default": "https://overpass-api.de" } } diff --git a/docs/container-qualification.md b/docs/container-qualification.md index 88c9474e7..9ac79ef9e 100644 --- a/docs/container-qualification.md +++ b/docs/container-qualification.md @@ -15,9 +15,9 @@ There is no registry login, push, package write, OIDC or privileged artifact con ## What must execute -`scripts/qualify-container-images.py qualify` builds the selected fixed recipe into an untagged OCI archive. The image must run as a non-root user, become healthy using its actual image healthcheck, and pass runtime/native probes on a fresh internal Docker network and owned PG16 database. No host port is published, no operator database or credentials are used, and provider egress is unavailable. Test-only grant/reviewer credentials and a random secrets key (`OPENCONDITIONS_SECRETS_KEY`) are freshly generated for every image. Database readiness uses a real TCP query to the fixture database, rather than accepting the image's temporary bootstrap server. +`scripts/qualify-container-images.py qualify` builds the selected fixed recipe into an untagged OCI archive. The image must run as a non-root user, become healthy using its actual image healthcheck, and pass runtime/native probes on a fresh internal Docker network and owned PG16 database. No host port is published, no operator database or credentials are used, and provider egress is unavailable. Test-only grant/reviewer credentials and a random secrets key (`OPENCONDITIONS_SECRETS_KEY`) are freshly generated for every image, and every service runs with the fixed instance id `qualification.example.org` (`OPENCONDITIONS_INSTANCE_ID`). Database readiness uses a real TCP query to the fixture database, rather than accepting the image's temporary bootstrap server. -- Ingest applies its bundled migrations. For contributions-api and federation, which apply none and wait at boot for the schema version, the script first applies the source's migrations to the fixture database and records them as the ingest service does. For contributions-api, which also waits for the secrets key check, the script then seals that check row with the throwaway key, as the ingest service does, from a small Node script run inside the image; the service verifies the row with its own code at start, so a seal that drifted from the service's format fails qualification. Every Node service returns its status document and exercises native WebCrypto. Federation's default-disabled status is recorded; this does not prove enabled peer or public-host behavior. Independent federation interoperability remains a separate CI gate. +- Ingest applies its bundled migrations. For contributions-api and federation, which apply none and wait at boot for the schema version, the script first applies the source's migrations to the fixture database and records them as the ingest service does. For contributions-api, which also waits for the secrets key check, the script then seals that check row with the throwaway key, as the ingest service does, from a small Node script run inside the image; the service verifies the row with its own code at start, so a seal that drifted from the service's format fails qualification. Ingest seals the instance id itself after migrating. For contributions-api and federation, which wait at boot for that row and refuse another id, the script seals it first the same way, inside the image. After health, the script checks that `conditions.instance_identity` holds the fixture's id. Every Node service returns its status document and exercises native WebCrypto. Federation's default-disabled status is recorded; this does not prove enabled peer or public-host behavior. Independent federation interoperability remains a separate CI gate. - Ingest additionally exercises its compiled osmium binary on a real OSM fixture, verifies baked feed credentials and migration metadata, and makes an Impit native request to its own health endpoint. Polling is explicitly excluded and the remote feed layer stays off. diff --git a/docs/database-migrations.md b/docs/database-migrations.md index 91aa33077..5b6a0a82a 100644 --- a/docs/database-migrations.md +++ b/docs/database-migrations.md @@ -13,7 +13,7 @@ The contributions and federation services apply no migrations. At start they cal Each OpenConditions service connects as a dedicated role, never as the PostgreSQL superuser; the heavy-feeds process and the federation service share the ingest service's (below). After every migrate, `runMigrations()` calls `conditions.grant_consumer_roles()`, a function of the custom migration that grants two roles by name exactly what they use, each only if it exists. It runs with its caller's rights and no role but its owner (the ingest service's role) may call it: - `openmapx_tiles_owner` is OpenMapX's role for its traffic tile. OpenMapX's PostGIS service creates it at every start; it cannot log in and owns the function in OpenMapX's `tiles` schema that the tile server calls, which calls `conditions.segment_flow`. It gets `USAGE` on `conditions`, `SELECT` on `road_segment`, `segment_speed`, `source` and `public_license_policy`, and `EXECUTE` on `segment_flow`, `flow_public_licenses` and `flow_osm_credit`: what the tile reads, so credentials, crowd data and every other table stay unreadable to it. -- `openconditions_contributions` is the contributions service's login, which the operator creates as OpenMapX's community extensions guide describes. It gets `USAGE` on `conditions`, `SELECT` on `conditions.__drizzle_migrations` for the schema version and on `conditions.secrets_key_check` to verify its secrets key, and the table privileges its queries use (the identity columns it inserts into need no grant on their sequences): reporters, block list, reports, votes and evidence, the issuer's keys and tokens, the situations and latest readings reports land on, the fused readings they refresh and the feed readings they are checked against. The federation capture triggers run with its rights when it writes a situation or a latest reading, so it also reads the subscriptions and journals into the outbox. It deletes no reporter: the ingest service's sweep does, as the owner, and the reporter strip trigger runs with the deleting role's rights. +- `openconditions_contributions` is the contributions service's login, which the operator creates as OpenMapX's community extensions guide describes. It gets `USAGE` on `conditions`, `SELECT` on `conditions.__drizzle_migrations` for the schema version, on `conditions.secrets_key_check` to verify its secrets key and on `conditions.instance_identity` to verify its instance id, and the table privileges its queries use (the identity columns it inserts into need no grant on their sequences): reporters, block list, reports, votes and evidence, the issuer's keys and tokens, the situations and latest readings reports land on, the fused readings they refresh and the feed readings they are checked against. The federation capture triggers run with its rights when it writes a situation or a latest reading, so it also reads the subscriptions and journals into the outbox. It deletes no reporter: the ingest service's sweep does, as the owner, and the reporter strip trigger runs with the deleting role's rights. The ingest service's role (`openconditions_ingest` under OpenMapX) owns `conditions` and needs no grant. The heavy-feeds process connects as the same role, since it migrates, grants and may seal the secrets key check like the primary; a role of its own would fail at `CREATE SCHEMA`, at the migration or at the grant step. The federation service connects as the same role too: at every start it creates and drops partitions of `observation`, which only the table's owner may do. diff --git a/docs/federation-onboarding.md b/docs/federation-onboarding.md index 75803da16..7844f8016 100644 --- a/docs/federation-onboarding.md +++ b/docs/federation-onboarding.md @@ -304,7 +304,7 @@ these not being right: | Variable | Meaning | | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `OPENCONDITIONS_INSTANCE_ID` | This instance's id, the one the ingest and contributions services stamp on every record. It must equal the actor's `instanceId`: a peer admits only records of the instance it pinned. | +| `OPENCONDITIONS_INSTANCE_ID` | This instance's id, the one the ingest and contributions services stamp on every record and the ingest service sealed in the database. Required whether or not federation is enabled. It must equal the actor's `instanceId`: a peer admits only records of the instance it pinned. | | `OPENCONDITIONS_FEDERATION_ACTOR` | The actor config (inline JSON or a path): `instanceId`, `baseUrl` (the public origin peers reach the service at), operator, coverage, licence, tier, and the capabilities the operator states: `protocolVersion` (optionally `protocolVersions`) and `convergenceBound`. The schema versions, wire format, delivery modes and filter keys are advertised from the running build, and configuring them, `maxEventRate` or an actor-wide `mtlsRequired` fails the boot. | | `OPENCONDITIONS_FEDERATION_PEERS` | The peers config (inline JSON array or a path): one record per peer with its `instanceId`, `actorUrl`, `trustTier` and `pinnedKeys` (§3), and none naming this instance. | | `OPENCONDITIONS_FEDERATION_ARCHIVE_URL` | Where peers fetch the static archive (default `/archive`, which the operator serves; see [archive.md](./archive.md)). | @@ -500,13 +500,14 @@ public paths of the actor's `baseUrl` to it and to the archive: The service signs and verifies against its configured `baseUrl`, not the request's host, so the proxy may rewrite the host but not the path. The stream (`/peer/stream`) is server-sent events: the proxy must not buffer it. -With an OpenMapX install, a compose file beside it adds the service to the -same network: +With an OpenMapX install, a compose file beside it, in a Compose project of +its own, adds the service to OpenMapX's network: ```yaml services: openconditions-federation: - image: ghcr.io/openconditions/federation:latest + # The release of the installed extension's services; never a moving tag. + image: ghcr.io/openconditions/federation:0.8.1 restart: unless-stopped environment: # The ingest service's own role, never the PostgreSQL superuser. @@ -526,7 +527,8 @@ services: networks: [openmapx] openconditions-archive: - image: caddy:2-alpine + # A fixed Caddy release, pinned by digest. + image: caddy:2.10.2-alpine@sha256:4c6e91c6ed0e2fa03efd5b44747b625fec79bc9cd06ac5235a779726618e530d restart: unless-stopped command: caddy file-server --root /data/archive --listen :8080 volumes: @@ -535,6 +537,8 @@ services: networks: openmapx: + # OpenMapX's platform network: Compose project openmapx, network openmapx. + name: openmapx_openmapx external: true secrets: @@ -543,10 +547,14 @@ secrets: volumes: openmapx-openconditions-ingest-data: + # The ingest service's volume, with the openmapx project prefix. + name: openmapx_openmapx-openconditions-ingest-data external: true openconditions-federation-data: ``` +These two containers join OpenMapX's platform network, which OpenMapX otherwise reserves for its built-in services: a community service OpenMapX runs gets a network of its own and reaches only the services it is granted. Started this way, outside OpenMapX, they can reach every service on that network, so run only these two pinned images. Pin the federation image to the release of the installed extension (`0.8.1` above; take the `tag` of `services/federation/service.json` at that release), and keep the archive server on a fixed Caddy release pinned by digest. + The file `federation-secrets/secrets-key` holds the same value that was entered as the Secrets key of `openconditions-ingest` in OpenMapX's admin services panel, taken from the recovery set. It must be readable by the container's user, and it stays out of the `federation` config folder and out of backups. The service refuses to start with any other key; see [secrets encrypted at rest](../README.md#secrets-encrypted-at-rest). and the public reverse proxy routes the paths, for example with Caddy: @@ -567,8 +575,9 @@ maps.example.org { } ``` -Use the network and volume names of the install (`docker network ls`, -`docker volume ls`), and set the same `OPENCONDITIONS_INSTANCE_ID` on the +The network and volume names above are those of an OpenMapX install under its +Compose project `openmapx`; check them with `docker network ls` and +`docker volume ls`. Set the same `OPENCONDITIONS_INSTANCE_ID` as on the ingest and contributions services. Its signing keys live in the database; its volume holds the registry's verified metadata and a peer's archive files while they land, up to 32 GiB a file. diff --git a/docs/model.md b/docs/model.md index 8702442a7..f6853c2c5 100644 --- a/docs/model.md +++ b/docs/model.md @@ -719,7 +719,9 @@ kind or a property with crowd rules takes reports, anything else does not. value now: a property, a feature (and component) or a place, the result as the property's observations carry it, and where the reporter stood. A sub-claim confirms, negates or flags any record, named by class, id and, - for a feature, component key. + for a feature, component key. Every claim and sub-claim carries the claim + format version as its top-level member `v` (now `1`), inside the signed + bytes; one without it or of another version is refused. - Landing turns a claim into a crowd record. The record's id hashes the reporter's key with the claim's nonce, so a replay lands the same id and the id never reveals the key; the key itself stays in `provenance.reporter` diff --git a/docs/release-notes/pre-launch-contracts.md b/docs/release-notes/pre-launch-contracts.md new file mode 100644 index 000000000..0d5c15118 --- /dev/null +++ b/docs/release-notes/pre-launch-contracts.md @@ -0,0 +1,16 @@ +# Instance id, relay trust, claim version and manifest rules + +Affected versions: The first product release containing this change and every later one. No product version is assigned by this change. + +Action: Set `OPENCONDITIONS_INSTANCE_ID` before the first start, on every OpenConditions service of the instance: the ingest service, the heavy-feeds ingest process, the contributions API and the federation service, all to the same value. It has no default any more (it was `local`). Use a lower-case DNS name, usually the instance's public host name, for example `maps.example.org`. A service without it, or with a value that is not a DNS name, stops at start. The first ingest process to start seals the id in the new table `conditions.instance_identity`, and every service then refuses to start with another id. The id cannot change later. To use another one, stop the OpenConditions services and drop the `conditions` schema (under OpenMapX only that schema, never the shared database), then start again with the new id. See [the instance id](../../README.md#the-instance-id). + +Under OpenMapX, set `OPENCONDITIONS_RELAY_TOKEN` on `openconditions-contributions-api` (a vault secret, at least 32 characters, `openssl rand -hex 32`) to the same value as OpenMapX's own `OPENCONDITIONS_RELAY_TOKEN`. OpenMapX relays every user's crowd requests from its own address; with the token, those requests share one relay enrollment limit, `OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE` (default 600), instead of the 10 enrollments a minute one address gets. A set token shorter than 32 characters stops the service at start. See [behind a relay](../../services/contributions-api/README.md#behind-a-relay). + +Compatibility: + +- Crowd protocol: every signed report claim and sub-claim body carries the top-level member `"v": 1` inside its signed bytes. The contributions API refuses a report or vote without it, or with another version, with `400` and `code: "CLAIM_VERSION_UNSUPPORTED"`. Clients must sign the new member; signatures made without it no longer verify. Claims name no target instance, deliberately; see [the wire contract](../../packages/contrib-core/README.md#claim-version). +- Instance ids: a configured instance id must be a DNS name (labels of letters, digits and inner dashes joined by single dots, at most 253 characters). Ids such as `a..b` or `a-.b`, which the earlier check let through, are refused. +- Database: the baseline is regenerated with the table `conditions.instance_identity` (one row, `instance_id` checked as a DNS name). The contributions role may read it. A database created by an earlier build is not upgraded, as for the earlier baseline. +- Manifests: every service manifest declares `"platform": "1.0"` and `"quality": "community"` (`community-verified` is gone). The extension declares `AGPL-3.0-or-later`, the licence of the services it installs; it declared `Apache-2.0`. Each service manifest lists what the service cannot start without in `configSchema.required`: the database URL, the secrets key and the instance id on the ingest services (and the feeds it polls on the heavy-feeds process), the grant secret and reviewer token too on the contributions API, and the database URL and instance id on the federation service. OpenMapX applies a configuration only once every enabled service has a value or a stored secret for each, and names the missing ones. +- Federation guide: the compose example names OpenMapX's network `openmapx_openmapx` and the ingest volume `openmapx_openmapx-openconditions-ingest-data`, and pins the image to the release tag. +- API: the ingest OpenAPI document describes the routing, speed and status routes (`/feeds/status`, `/valhalla/exclusions.json`, `/segments.geojson`, `/segments/speed.csv`, `/segments/profiles.json`, `/segments/conditions.json`). Paths never break; a breaking change gets a new path. diff --git a/extension.json b/extension.json index c7df85bce..b7d0abe27 100644 --- a/extension.json +++ b/extension.json @@ -4,7 +4,7 @@ "version": "0.8.1", "platform": "1.0", "description": "Live road and traffic conditions as data (DATEX II / OpenLR / Open511 / WZDx) ingested into PostGIS and rendered as a map overlay, with Valhalla road-closure avoidance. Ships the ingestion service and the contributions API, serving the roads, fuel, parking, charging, cameras, hazards, weather, vehicles and border domains; OpenMapX reads all but weather, vehicles and border through its built-in OpenConditions integration and renders the overlay UI.", - "license": "Apache-2.0", + "license": "AGPL-3.0-or-later", "homepage": "https://github.com/OpenConditions/openconditions", "services": [ { diff --git a/packages/contrib-core/README.md b/packages/contrib-core/README.md index 42f8125be..460a3ce0e 100644 --- a/packages/contrib-core/README.md +++ b/packages/contrib-core/README.md @@ -14,21 +14,47 @@ and Node 24+. ## Wire contract - `ReportClaim` — the signable report content, a `SituationClaim` - (`claimClass: "situation"`, `kind`, `type`, `subtype?`, `geometry`, + (`v: 1`, `claimClass: "situation"`, `kind`, `type`, `subtype?`, `geometry`, `fuzziness`, `severityLevel?`, `effects?`, `details?`, `text?`, `reportedAt`, - `nonce`) or an `ObservationClaim` (`claimClass: "observation"`, the subject, - `property`, `qualifiers?`, `result`, the reporter's position, `reportedAt`, - `nonce`). The ES256 signature covers exactly `canonicalize(claim)` (RFC 8785) - encoded as UTF-8. + `nonce`) or an `ObservationClaim` (`v: 1`, `claimClass: "observation"`, the + subject, `property`, `qualifiers?`, `result`, the reporter's position, + `reportedAt`, `nonce`). The ES256 signature covers exactly + `canonicalize(claim)` (RFC 8785) encoded as UTF-8. - `SignedReport` — claim + detached envelope (`alg: "ES256"`, `keyId`, optional `pubJwk`, `signature` as base64url raw 64-byte `r||s`). `pubJwk` is embedded on first submission; servers cache it and verify subsequent envelopes against the cached key (`knownJwk` takes precedence and must match any embedded key). - `SubClaimBody` / `SignedSubClaim` — confirm/negate/flag reactions to a - stored record, named by its `RecordRef` (`{class, id, componentKey?}`). The - signature covers only the body, never the envelope fields; the `keyId` is - bound instead by the RFC 7638 thumbprint check at verification. + stored record (`v: 1`, `subject`, `claimType`, `reason?`, `geometry?`, + `reportedAt`, `nonce`), named by its `RecordRef` + (`{class, id, componentKey?}`). The signature covers only the body, never + the envelope fields; the `keyId` is bound instead by the RFC 7638 + thumbprint check at verification. + +### Claim version + +Every signed body, a report claim and a sub-claim body alike, carries the +top-level member `v`, the claim format version (`CLAIM_VERSION`, now `1`). +It is part of the signed bytes, so it cannot be changed without invalidating +the signature. Signing and verification refuse a body without `v` or with +any other value; the contributions API answers such a request with `400` and +`code: "CLAIM_VERSION_UNSUPPORTED"` before it checks the signature. A change +to what a claim's members mean, or to which members it has, takes a new +version; clients then sign the new one and servers state which versions they +verify. + +### No instance binding + +A claim names no target instance or audience, deliberately. A claim is the +reporter's statement about the world, and the instance that lands it adds +its own id to the record it creates (`oc:::`, +the local id derived from the reporter's key and the claim's nonce). A claim +copied to another instance verifies there too; it lands there as that +instance's record of the same statement, and replays on any one instance land +the same record. Each instance admits only reporters it enrolled (a report or +vote needs that instance's reporting grant for the key), so a copied claim +reaches an instance only through a reporter enrolled there. `signReport(registry, claim, key)` and `verifyReport(registry, report, knownJwk?)` validate the claim against the registry the caller runs diff --git a/packages/contrib-core/src/__tests__/cross-repo-conformance.test.ts b/packages/contrib-core/src/__tests__/cross-repo-conformance.test.ts index cc59c857d..a76daf87a 100644 --- a/packages/contrib-core/src/__tests__/cross-repo-conformance.test.ts +++ b/packages/contrib-core/src/__tests__/cross-repo-conformance.test.ts @@ -23,6 +23,7 @@ const PINNED_KEY_ID = "GlQczzclqGJy6D0X9dNq8pSYKRfkCqszpEp5g3ZGlwY"; // A FIXED situation claim exercising a subtype, a severity level, an effect, // non-ASCII text and nested objects and arrays. const FIXED_CLAIM: ReportClaim = { + v: 1, claimClass: "situation", kind: "incident", type: "obstruction", @@ -50,7 +51,7 @@ const FIXED_CLAIM: ReportClaim = { // Pinned hex of canonicalClaimBytes(FIXED_CLAIM). const PINNED_CLAIM_HEX = - "7b22636c61696d436c617373223a22736974756174696f6e222c2265666665637473223a5b7b226170706c69636162696c697479223a7b226b696e64223a22616c6c227d2c22636f6d706c69616e6365223a226d616e6461746f7279222c226964223a226c616e6573222c226b696e64223a226c616e655f7265737472696374696f6e222c226c616e6573436c6f736564223a312c226c616e6573546f74616c223a322c226e6f726d616c697a6174696f6e223a22636f6d706c657465222c2276223a312c2276656869636c65496d70616374223a22736f6d655f6c616e65735f636c6f736564227d5d2c2266757a7a696e657373223a226578616374222c2267656f6d65747279223a7b22636f6f7264696e61746573223a5b372e303938322c35302e373337345d2c2274797065223a22506f696e74227d2c226b696e64223a22696e636964656e74222c226e6f6e6365223a22636f6e666f726d616e63652d6e6f6e63652d30303031222c227265706f727465644174223a22323032362d30372d31315431323a33343a35362e3738395a222c2273657665726974794c6576656c223a332c2273756274797065223a227370696c6c222c2274657874223a5b7b226c616e67223a226465222c2274657874223a22466168726261686e207665727363686d75747a7420e2809420c3966c227d5d2c2274797065223a226f62737472756374696f6e227d"; + "7b22636c61696d436c617373223a22736974756174696f6e222c2265666665637473223a5b7b226170706c69636162696c697479223a7b226b696e64223a22616c6c227d2c22636f6d706c69616e6365223a226d616e6461746f7279222c226964223a226c616e6573222c226b696e64223a226c616e655f7265737472696374696f6e222c226c616e6573436c6f736564223a312c226c616e6573546f74616c223a322c226e6f726d616c697a6174696f6e223a22636f6d706c657465222c2276223a312c2276656869636c65496d70616374223a22736f6d655f6c616e65735f636c6f736564227d5d2c2266757a7a696e657373223a226578616374222c2267656f6d65747279223a7b22636f6f7264696e61746573223a5b372e303938322c35302e373337345d2c2274797065223a22506f696e74227d2c226b696e64223a22696e636964656e74222c226e6f6e6365223a22636f6e666f726d616e63652d6e6f6e63652d30303031222c227265706f727465644174223a22323032362d30372d31315431323a33343a35362e3738395a222c2273657665726974794c6576656c223a332c2273756274797065223a227370696c6c222c2274657874223a5b7b226c616e67223a226465222c2274657874223a22466168726261686e207665727363686d75747a7420e2809420c3966c227d5d2c2274797065223a226f62737472756374696f6e222c2276223a317d"; function toHex(bytes: Uint8Array): string { return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); diff --git a/packages/contrib-core/src/__tests__/lowS.test.ts b/packages/contrib-core/src/__tests__/lowS.test.ts index 13af85cbe..1b3f9e66e 100644 --- a/packages/contrib-core/src/__tests__/lowS.test.ts +++ b/packages/contrib-core/src/__tests__/lowS.test.ts @@ -39,6 +39,7 @@ function rawSignature(r: bigint, s: bigint): Uint8Array { function makeClaim(): ReportClaim { return { + v: 1, claimClass: "situation", kind: "incident", type: "obstruction", diff --git a/packages/contrib-core/src/__tests__/report.test.ts b/packages/contrib-core/src/__tests__/report.test.ts index a63589654..e69b9d15a 100644 --- a/packages/contrib-core/src/__tests__/report.test.ts +++ b/packages/contrib-core/src/__tests__/report.test.ts @@ -16,6 +16,7 @@ const registry = productionRegistry(); function makeClaim(overrides: Record = {}): ReportClaim { return { + v: 1, claimClass: "situation", kind: "incident", type: "obstruction", @@ -78,6 +79,23 @@ describe("signReport / verifyReport", () => { await expect(verify(report)).resolves.toStrictEqual({ ok: true, keyId: key.keyId }); }); + it("signs the claim version inside the signed bytes and refuses a claim without it or of another", async () => { + const key = await generateReporterKey(); + const claim = makeClaim(); + expect(new TextDecoder().decode(canonicalClaimBytes(claim))).toContain('"v":1'); + const { v: _v, ...unversioned } = claim; + await expect(sign(unversioned as unknown as ReportClaim, key)).rejects.toThrow(/claim\.v/); + await expect(sign(makeClaim({ v: 2 }), key)).rejects.toThrow(/claim\.v/); + // A signed claim whose version is changed afterwards fails the schema before the signature. + const report = await sign(claim, key); + const bumped = await verify({ + ...report, + claim: { ...report.claim, v: 2 } as unknown as ReportClaim, + }); + expect(bumped.ok).toBe(false); + expect(bumped.error).toMatch(/claim\.v/); + }); + it("verifies with a server-cached knownJwk when pubJwk is absent", async () => { const key = await generateReporterKey(); const report = await sign(makeClaim(), key); diff --git a/packages/contrib-core/src/__tests__/subclaim.test.ts b/packages/contrib-core/src/__tests__/subclaim.test.ts index a760929d1..b4f6d807b 100644 --- a/packages/contrib-core/src/__tests__/subclaim.test.ts +++ b/packages/contrib-core/src/__tests__/subclaim.test.ts @@ -11,6 +11,7 @@ import { P256_ORDER } from "../lowS.js"; function makeBody(overrides: Record = {}): SubClaimBody { return { + v: 1, subject: { class: "situation", id: "oc:situation:example:a46" }, claimType: "confirm", reportedAt: "2026-07-11T12:05:00Z", @@ -28,6 +29,19 @@ describe("signSubClaim / verifySubClaim", () => { await expect(verifySubClaim(sub)).resolves.toStrictEqual({ ok: true, keyId: key.keyId }); }); + it("signs the claim version and refuses a body without it or of another", async () => { + const key = await generateReporterKey(); + const { v: _v, ...unversioned } = makeBody(); + await expect(signSubClaim(unversioned as unknown as SubClaimBody, key)).rejects.toThrow( + /subClaim\.v/, + ); + await expect(signSubClaim(makeBody({ v: 2 }), key)).rejects.toThrow(/subClaim\.v/); + const sub = await signSubClaim(makeBody(), key); + const bumped = await verifySubClaim({ ...sub, v: 2 } as unknown as SignedSubClaim); + expect(bumped.ok).toBe(false); + expect(bumped.error).toMatch(/subClaim\.v/); + }); + it("verifies with a knownJwk when pubJwk is absent", async () => { const key = await generateReporterKey(); const sub = await signSubClaim(makeBody({ claimType: "negate" }), key); diff --git a/packages/contrib-core/src/index.ts b/packages/contrib-core/src/index.ts index 650e8e5a1..f23c96220 100644 --- a/packages/contrib-core/src/index.ts +++ b/packages/contrib-core/src/index.ts @@ -22,3 +22,4 @@ export type { SubClaimType, VerifyResult, } from "./types.js"; +export { CLAIM_VERSION } from "./types.js"; diff --git a/packages/contrib-core/src/types.ts b/packages/contrib-core/src/types.ts index 702cf9f13..28fe97fff 100644 --- a/packages/contrib-core/src/types.ts +++ b/packages/contrib-core/src/types.ts @@ -7,6 +7,7 @@ export type { SituationClaim, SubClaimBody, } from "@openconditions/model"; +export { CLAIM_VERSION } from "@openconditions/model"; /** * A report claim plus its detached signature envelope. The envelope fields diff --git a/packages/core/drizzle/0000_baseline.sql b/packages/core/drizzle/0000_baseline.sql index e7c0411de..1f1f2513b 100644 --- a/packages/core/drizzle/0000_baseline.sql +++ b/packages/core/drizzle/0000_baseline.sql @@ -598,6 +598,14 @@ CREATE TABLE "conditions"."geonet_coverage" ( CONSTRAINT "geonet_coverage_order_check" CHECK ("conditions"."geonet_coverage"."covered_from" < "conditions"."geonet_coverage"."covered_until") ); --> statement-breakpoint +CREATE TABLE "conditions"."instance_identity" ( + "id" smallint PRIMARY KEY DEFAULT 1 NOT NULL, + "instance_id" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "instance_identity_id_check" CHECK ("conditions"."instance_identity"."id" = 1), + CONSTRAINT "instance_identity_instance_id_check" CHECK (length("instance_id") <= 253 AND "instance_id" ~ '^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$') +); +--> statement-breakpoint CREATE TABLE "conditions"."issuer_key" ( "key_id" text PRIMARY KEY NOT NULL, "public_key" "bytea" NOT NULL, diff --git a/packages/core/drizzle/0001_database_objects.sql b/packages/core/drizzle/0001_database_objects.sql index b0bc14748..2ffe04bcd 100644 --- a/packages/core/drizzle/0001_database_objects.sql +++ b/packages/core/drizzle/0001_database_objects.sql @@ -588,9 +588,10 @@ BEGIN END IF; -- The contributions service's own role gets what its queries use. It reads -- the migration history to wait for the schema version, and the stored - -- codes and the secrets key check at start. It keeps the crowd's - -- reporters, block list, reports, votes and evidence, the issuer's keys and - -- the tokens it issues and redeems. A report lands as a situation, with its + -- codes, the secrets key check and the sealed instance id at start. It + -- keeps the crowd's reporters, block list, reports, votes and evidence, + -- the issuer's keys and the tokens it issues and redeems. A report lands + -- as a situation, with its -- effects, revision and graph binding, or as a latest reading of a feed's -- feature; its evidence refreshes the fused readings, and a cross-check -- reads the feeds' readings and their history. Its writes to situations and @@ -606,7 +607,8 @@ BEGIN "conditions"."feature_canonical", "conditions"."observation", "conditions"."observation_rollup_progress", "conditions"."source_status", "conditions"."source_poll_attempt", "conditions"."federation_subscription", - "conditions"."secrets_key_check" TO openconditions_contributions; + "conditions"."secrets_key_check", "conditions"."instance_identity" + TO openconditions_contributions; GRANT INSERT ON "conditions"."situation_revision" TO openconditions_contributions; GRANT SELECT, INSERT ON "conditions"."issuer_key", "conditions"."spent_token", "conditions"."report_evidence", "conditions"."sub_claim", "conditions"."contributor_receipt", diff --git a/packages/core/drizzle/meta/0000_snapshot.json b/packages/core/drizzle/meta/0000_snapshot.json index e16a3d5e2..6c11ac50f 100644 --- a/packages/core/drizzle/meta/0000_snapshot.json +++ b/packages/core/drizzle/meta/0000_snapshot.json @@ -1,5 +1,5 @@ { - "id": "07985733-6696-46d3-9be2-7d3a6a1af430", + "id": "85c04e68-b70a-47cc-b014-5c7f9ae1e1af", "prevId": "00000000-0000-0000-0000-000000000000", "version": "7", "dialect": "postgresql", @@ -4833,6 +4833,48 @@ }, "isRLSEnabled": false }, + "conditions.instance_identity": { + "name": "instance_identity", + "schema": "conditions", + "columns": { + "id": { + "name": "id", + "type": "smallint", + "primaryKey": true, + "notNull": true, + "default": 1 + }, + "instance_id": { + "name": "instance_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "instance_identity_id_check": { + "name": "instance_identity_id_check", + "value": "\"conditions\".\"instance_identity\".\"id\" = 1" + }, + "instance_identity_instance_id_check": { + "name": "instance_identity_instance_id_check", + "value": "length(\"instance_id\") <= 253 AND \"instance_id\" ~ '^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$'" + } + }, + "isRLSEnabled": false + }, "conditions.issuer_key": { "name": "issuer_key", "schema": "conditions", diff --git a/packages/core/drizzle/meta/0001_snapshot.json b/packages/core/drizzle/meta/0001_snapshot.json index 79d4a4c0d..0a0fae7b0 100644 --- a/packages/core/drizzle/meta/0001_snapshot.json +++ b/packages/core/drizzle/meta/0001_snapshot.json @@ -1,6 +1,6 @@ { - "id": "686d6a03-471a-4475-a344-a30763e1f6fb", - "prevId": "07985733-6696-46d3-9be2-7d3a6a1af430", + "id": "42d81165-d38c-46f4-8ecc-7baf193d3492", + "prevId": "85c04e68-b70a-47cc-b014-5c7f9ae1e1af", "version": "7", "dialect": "postgresql", "tables": { @@ -4833,6 +4833,48 @@ }, "isRLSEnabled": false }, + "conditions.instance_identity": { + "name": "instance_identity", + "schema": "conditions", + "columns": { + "id": { + "name": "id", + "type": "smallint", + "primaryKey": true, + "notNull": true, + "default": 1 + }, + "instance_id": { + "name": "instance_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "instance_identity_id_check": { + "name": "instance_identity_id_check", + "value": "\"conditions\".\"instance_identity\".\"id\" = 1" + }, + "instance_identity_instance_id_check": { + "name": "instance_identity_instance_id_check", + "value": "length(\"instance_id\") <= 253 AND \"instance_id\" ~ '^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$'" + } + }, + "isRLSEnabled": false + }, "conditions.issuer_key": { "name": "issuer_key", "schema": "conditions", diff --git a/packages/core/drizzle/meta/_journal.json b/packages/core/drizzle/meta/_journal.json index 44932de0c..753601c7b 100644 --- a/packages/core/drizzle/meta/_journal.json +++ b/packages/core/drizzle/meta/_journal.json @@ -5,14 +5,14 @@ { "idx": 0, "version": "7", - "when": 1795502606552, + "when": 1795534164874, "tag": "0000_baseline", "breakpoints": true }, { "idx": 1, "version": "7", - "when": 1795502607057, + "when": 1795534168051, "tag": "0001_database_objects", "breakpoints": true } diff --git a/packages/core/src/__tests__/instance-identity.integration.test.ts b/packages/core/src/__tests__/instance-identity.integration.test.ts new file mode 100644 index 000000000..e8eafef2e --- /dev/null +++ b/packages/core/src/__tests__/instance-identity.integration.test.ts @@ -0,0 +1,101 @@ +import { createTestDatabase, type TestDatabase } from "@openconditions/test-database"; +import postgres from "postgres"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { + InstanceIdMismatchError, + sealInstanceId, + verifyInstanceId, + waitForInstanceId, +} from "../instance-identity.js"; + +/** + * The sealed instance id: the first ingest process writes it once, and every + * service refuses to start with another id. + */ + +const mismatch = + /OPENCONDITIONS_INSTANCE_ID "other\.example\.org" differs from "maps\.example\.org"/; + +let db: TestDatabase; +let sql: postgres.Sql; +/** A second pool, as a second process holds. */ +let other: postgres.Sql; + +beforeAll(async () => { + db = await createTestDatabase(); + sql = db.sql; + other = postgres(db.url, { max: 2, onnotice: () => {} }); +}, 120_000); + +afterAll(async () => { + await other?.end(); + await db?.close(); +}, 30_000); + +beforeEach(async () => { + await sql`TRUNCATE conditions.instance_identity`; +}); + +describe("conditions.instance_identity", () => { + it("is absent until the ingest service seals it, then matches the same id", async () => { + expect(await verifyInstanceId(sql, "maps.example.org")).toBe("absent"); + await sealInstanceId(sql, "maps.example.org"); + expect(await verifyInstanceId(sql, "maps.example.org")).toBe("match"); + // A restart seals nothing new and still matches. + await sealInstanceId(sql, "maps.example.org"); + expect(await sql`SELECT instance_id FROM conditions.instance_identity`).toEqual([ + { instance_id: "maps.example.org" }, + ]); + }); + + it("refuses another id, naming both and the one to set", async () => { + await sealInstanceId(sql, "maps.example.org"); + await expect(verifyInstanceId(sql, "other.example.org")).rejects.toBeInstanceOf( + InstanceIdMismatchError, + ); + await expect(verifyInstanceId(sql, "other.example.org")).rejects.toThrow(mismatch); + await expect(sealInstanceId(sql, "other.example.org")).rejects.toThrow(mismatch); + }); + + it("keeps one row when two processes start together, refusing the one with another id", async () => { + const differing = await Promise.allSettled([ + sealInstanceId(sql, "maps.example.org"), + sealInstanceId(other, "other.example.org"), + ]); + expect(differing.filter((r) => r.status === "fulfilled")).toHaveLength(1); + expect(differing.filter((r) => r.status === "rejected")).toHaveLength(1); + expect(await sql`SELECT id FROM conditions.instance_identity`).toHaveLength(1); + }); + + it("is waited for by a service that starts before the ingest service sealed it", async () => { + const waiting = waitForInstanceId(other, "maps.example.org", { timeoutMs: 10_000, pollMs: 50 }); + await new Promise((resolve) => setTimeout(resolve, 200)); + await sealInstanceId(sql, "maps.example.org"); + await expect(waiting).resolves.toBeUndefined(); + await expect( + waitForInstanceId(other, "other.example.org", { timeoutMs: 10_000, pollMs: 50 }), + ).rejects.toThrow(mismatch); + }); + + it("stops waiting after the timeout, saying the ingest service has not sealed it", async () => { + await expect( + waitForInstanceId(sql, "maps.example.org", { timeoutMs: 150, pollMs: 50 }), + ).rejects.toThrow( + /the ingest service did not seal conditions\.instance_identity within 150 ms/, + ); + }); + + it("holds one row only, and only a DNS-name id", async () => { + await sealInstanceId(sql, "maps.example.org"); + await expect( + sql`INSERT INTO conditions.instance_identity (id, instance_id) VALUES (2, 'b.example.org')`, + ).rejects.toThrow(/instance_identity_id_check/); + await sql`TRUNCATE conditions.instance_identity`; + for (const bad of ["local:x", "Maps.example.org", "a..b", "-a", `${"a".repeat(64)}.org`]) { + await expect( + sql`INSERT INTO conditions.instance_identity (instance_id) VALUES (${bad})`, + bad, + ).rejects.toThrow(/instance_identity_instance_id_check/); + } + }); +}); diff --git a/packages/core/src/__tests__/instance.test.ts b/packages/core/src/__tests__/instance.test.ts index 7cf386f01..e4a984ec4 100644 --- a/packages/core/src/__tests__/instance.test.ts +++ b/packages/core/src/__tests__/instance.test.ts @@ -6,23 +6,21 @@ describe("resolveInstanceId", () => { expect(resolveInstanceId({ OPENCONDITIONS_INSTANCE_ID: " node-a " })).toBe("node-a"); }); - it("falls back to 'local' when unset", () => { - expect(resolveInstanceId({})).toBe("local"); - }); - - it("falls back to 'local' for a whitespace-only value", () => { - expect(resolveInstanceId({ OPENCONDITIONS_INSTANCE_ID: " " })).toBe("local"); - }); - - it("falls back to 'local' for an empty value (Compose ${VAR:-} injection)", () => { - expect(resolveInstanceId({ OPENCONDITIONS_INSTANCE_ID: "" })).toBe("local"); + it("refuses a missing, empty or whitespace-only value instead of defaulting", () => { + for (const env of [ + {}, + { OPENCONDITIONS_INSTANCE_ID: "" }, + { OPENCONDITIONS_INSTANCE_ID: " " }, + ]) { + expect(() => resolveInstanceId(env)).toThrow(/OPENCONDITIONS_INSTANCE_ID is required/); + } }); - it("accepts a hostname and rejects ids that cannot be a record-id namespace", () => { + it("accepts a DNS name and rejects anything else", () => { expect(resolveInstanceId({ OPENCONDITIONS_INSTANCE_ID: "maps.example.org" })).toBe( "maps.example.org", ); - for (const bad of ["a:b", "Maps.example.org", "node_a", "-node", "node-"]) { + for (const bad of ["a:b", "Maps.example.org", "node_a", "-node", "node-", "a..b", "a-.b"]) { expect(() => resolveInstanceId({ OPENCONDITIONS_INSTANCE_ID: bad })).toThrow( /not a valid instance id/, ); diff --git a/packages/core/src/db/schema.ts b/packages/core/src/db/schema.ts index 7cdffe789..9eee93e62 100644 --- a/packages/core/src/db/schema.ts +++ b/packages/core/src/db/schema.ts @@ -1,4 +1,10 @@ -import { enumCheckSql, RECORD_CLASSES, TOMBSTONE_REASONS } from "@openconditions/model"; +import { + CONFIGURED_INSTANCE_ID_PATTERN, + enumCheckSql, + MAX_INSTANCE_ID_LENGTH, + RECORD_CLASSES, + TOMBSTONE_REASONS, +} from "@openconditions/model"; import { sql } from "drizzle-orm"; import { bigint, @@ -725,6 +731,29 @@ export const secretsKeyCheck = conditionsSchema.table( ], ); +/** + * One row: the instance id, which the first ingest process to start writes + * once. Every record id this instance originates, and every crowd signature + * over one, carries it, so every service refuses to start with another id. + */ +export const instanceIdentity = conditionsSchema.table( + "instance_identity", + { + id: smallint("id").primaryKey().default(1), + instanceId: text("instance_id").notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + }, + (t) => [ + check("instance_identity_id_check", sql`${t.id} = 1`), + check( + "instance_identity_instance_id_check", + sql.raw( + `length("instance_id") <= ${MAX_INSTANCE_ID_LENGTH} AND "instance_id" ~ '${CONFIGURED_INSTANCE_ID_PATTERN.source}'`, + ), + ), + ], +); + /** * This instance's rotating token-issuer keypairs, each valid across a * [not_before, not_after) window. The private key (PKCS#8) is stored sealed diff --git a/packages/core/src/instance-identity.ts b/packages/core/src/instance-identity.ts new file mode 100644 index 000000000..b8d8b7600 --- /dev/null +++ b/packages/core/src/instance-identity.ts @@ -0,0 +1,86 @@ +import { setTimeout as sleep } from "node:timers/promises"; +import type postgres from "postgres"; +import { INSTANCE_ID_VARIABLE } from "./instance.js"; + +const DEFAULT_POLL_MS = 2_000; + +/** This service's instance id is not the one the ingest service sealed. */ +export class InstanceIdMismatchError extends Error { + override name = "InstanceIdMismatchError"; +} + +const mismatch = (configured: string, sealed: string) => + new InstanceIdMismatchError( + `${INSTANCE_ID_VARIABLE} "${configured}" differs from "${sealed}", the instance id sealed in conditions.instance_identity: every record id of this instance carries the sealed one, so set ${INSTANCE_ID_VARIABLE} to "${sealed}" on this service`, + ); + +/** + * Compares `instanceId` with the sealed row: "match" when they are equal, + * "absent" before the ingest service wrote it. Throws an + * {@link InstanceIdMismatchError} when they differ. + */ +export async function verifyInstanceId( + sql: postgres.Sql, + instanceId: string, +): Promise<"match" | "absent"> { + const [row] = await sql<{ instance_id: string }[]>` + SELECT instance_id FROM conditions.instance_identity WHERE id = 1`; + if (row === undefined) return "absent"; + if (row.instance_id !== instanceId) throw mismatch(instanceId, row.instance_id); + return "match"; +} + +/** + * The ingest service's step at start, after the migrations: seals + * `instanceId` unless a row is there already, then verifies the stored row. + * Two processes starting together write one row; the one whose id differs + * fails with an {@link InstanceIdMismatchError}. + */ +export async function sealInstanceId(sql: postgres.Sql, instanceId: string): Promise { + await sql` + INSERT INTO conditions.instance_identity (id, instance_id) VALUES (1, ${instanceId}) + ON CONFLICT (id) DO NOTHING`; + if ((await verifyInstanceId(sql, instanceId)) !== "match") { + throw new Error("conditions.instance_identity is empty after it was written"); + } +} + +export interface WaitForInstanceIdOptions { + /** How long to wait for the ingest service to write the row. */ + timeoutMs: number; + pollMs?: number; + /** Called once when the row is not there yet. */ + onWait?: () => void; +} + +/** + * The start of a service that does not migrate, after + * `waitForSchemaVersion`: waits until the ingest service has sealed the + * instance id, then compares `instanceId` with it. Throws an + * {@link InstanceIdMismatchError} on another id, and a clear error when the + * row does not appear within `timeoutMs`. + */ +export async function waitForInstanceId( + sql: postgres.Sql, + instanceId: string, + options: WaitForInstanceIdOptions, +): Promise { + const pollMs = options.pollMs ?? DEFAULT_POLL_MS; + const deadline = Date.now() + options.timeoutMs; + let told = false; + for (;;) { + if ((await verifyInstanceId(sql, instanceId)) === "match") return; + const left = deadline - Date.now(); + if (left <= 0) { + throw new Error( + `the ingest service did not seal conditions.instance_identity within ${options.timeoutMs} ms: ` + + `start the ingest service with ${INSTANCE_ID_VARIABLE} first`, + ); + } + if (!told) { + options.onWait?.(); + told = true; + } + await sleep(Math.min(pollMs, left)); + } +} diff --git a/packages/core/src/instance.ts b/packages/core/src/instance.ts index 768eed44b..251761dd9 100644 --- a/packages/core/src/instance.ts +++ b/packages/core/src/instance.ts @@ -1,19 +1,27 @@ import { isInstanceId } from "@openconditions/model"; +/** The variable every service reads its instance id from. */ +export const INSTANCE_ID_VARIABLE = "OPENCONDITIONS_INSTANCE_ID"; + /** - * Resolves this instance's stable id from the environment. Federation makes a - * real, unique instance id operationally required; `"local"` keeps a - * single-instance deployment zero-config. The id is the record-id namespace - * of everything this instance originates (`oc:::`), - * so it must never contain ":" — a hostname works. Services call this at - * startup, so a bad value stops the service instead of the first write. + * Resolves this instance's stable id from the environment. The id is the + * record-id namespace of everything this instance originates + * (`oc:::`) and its name to federation peers, and + * crowd votes are signed over record ids, so it can never change once + * records exist. It is therefore required, with no default: a lower-case DNS + * name such as `maps.example.org`. Services call this at startup, so a + * missing or bad value stops the service before it touches the database. */ export function resolveInstanceId(env: NodeJS.ProcessEnv = process.env): string { - const raw = env["OPENCONDITIONS_INSTANCE_ID"]?.trim(); - const id = raw ? raw : "local"; + const id = env[INSTANCE_ID_VARIABLE]?.trim() ?? ""; + if (id === "") { + throw new Error( + `${INSTANCE_ID_VARIABLE} is required: set it to this instance's own DNS name (e.g. maps.example.org), the same value on every OpenConditions service of the instance`, + ); + } if (!isInstanceId(id)) { throw new Error( - `OPENCONDITIONS_INSTANCE_ID "${id}" is not a valid instance id: use lower-case letters, digits, dots and dashes, starting and ending with a letter or digit (e.g. maps.example.org)`, + `${INSTANCE_ID_VARIABLE} "${id}" is not a valid instance id: use a lower-case DNS name, labels of letters, digits and inner dashes joined by single dots, at most 253 characters (e.g. maps.example.org)`, ); } return id; diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index bf2aa0791..a495bee9f 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -12,3 +12,4 @@ export * from "./crypto/secrets-key-check.js"; export * from "./crypto/stored-secrets.js"; export * from "./db/index.js"; export * from "./instance.js"; +export * from "./instance-identity.js"; diff --git a/packages/federation/src/__tests__/record-fixtures.integration.ts b/packages/federation/src/__tests__/record-fixtures.integration.ts index 685a02700..e071ed20b 100644 --- a/packages/federation/src/__tests__/record-fixtures.integration.ts +++ b/packages/federation/src/__tests__/record-fixtures.integration.ts @@ -266,6 +266,7 @@ export function crowdReportDraft(nonce: string, now = WRITTEN_AT): Rec { registry, { claim: { + v: 1, claimClass: "situation", kind: "incident", type: "accident", diff --git a/packages/federation/src/__tests__/records.test.ts b/packages/federation/src/__tests__/records.test.ts index 62258fb7b..619e5dcd9 100644 --- a/packages/federation/src/__tests__/records.test.ts +++ b/packages/federation/src/__tests__/records.test.ts @@ -68,6 +68,7 @@ function crowdAccident(evidence?: string) { registry, { claim: { + v: 1, claimClass: "situation", kind: "incident", type: "accident", diff --git a/packages/federation/src/actor.ts b/packages/federation/src/actor.ts index a274abe54..a909f8254 100644 --- a/packages/federation/src/actor.ts +++ b/packages/federation/src/actor.ts @@ -15,6 +15,7 @@ * its subscriptions accept. The operator configures only the protocol * versions it offers and the convergence bound it promises. */ +import { isInstanceId } from "@openconditions/model"; import type { KeyEndorsement, PublicInstanceKey } from "./keys.js"; import { RECORD_FILTER_KEYS } from "./record-filter.js"; import { DELIVERY_MODES } from "./subscriptions.js"; @@ -217,6 +218,9 @@ export function parseActorConfig(source: string | unknown): ActorConfig { fail(field, "must be a non-empty string"); } } + if (!isInstanceId(cfg["instanceId"] as string)) { + fail("instanceId", "must be an instance id, a lower-case DNS name"); + } if (!isHttpUrl(cfg["baseUrl"])) fail("baseUrl", "must be an http(s) URL"); if (cfg["trustTier"] !== 0 && cfg["trustTier"] !== 1 && cfg["trustTier"] !== 2) { fail("trustTier", "must be 0, 1, or 2"); diff --git a/packages/federation/src/peers.ts b/packages/federation/src/peers.ts index 334982cdb..80bbed0f0 100644 --- a/packages/federation/src/peers.ts +++ b/packages/federation/src/peers.ts @@ -9,6 +9,7 @@ * a rolled-back document serving only retired unpinned keys, or a document * served from a different actor URL is rejected. */ +import { isInstanceId } from "@openconditions/model"; import type { ActorCoverage, ActorDocument } from "./actor.js"; import { rawEd25519FromMultibase } from "./multibase.js"; import type { PeerPull, PeerSubscribe } from "./peer-subscribe.js"; @@ -103,8 +104,8 @@ export function loadPeers(source: string | unknown): PeerRecord[] { const record = entry as Record; const instanceId = record["instanceId"]; - if (typeof instanceId !== "string" || instanceId.length === 0) { - fail(index, "instanceId must be a non-empty string"); + if (typeof instanceId !== "string" || !isInstanceId(instanceId)) { + fail(index, "instanceId must be an instance id, a lower-case DNS name"); } if (seen.has(instanceId)) fail(index, `duplicate instanceId "${instanceId}"`); seen.add(instanceId); diff --git a/packages/model-registry/src/__tests__/crowd-fit.test.ts b/packages/model-registry/src/__tests__/crowd-fit.test.ts index a793ea1a4..d9c19fd15 100644 --- a/packages/model-registry/src/__tests__/crowd-fit.test.ts +++ b/packages/model-registry/src/__tests__/crowd-fit.test.ts @@ -157,6 +157,7 @@ describe("what drivers report", () => { registry, { claim: { + v: 1, claimClass: "situation", ...classification, geometry: here, @@ -203,6 +204,7 @@ describe("what drivers report", () => { registry, { claim: { + v: 1, claimClass: "situation", kind: "transit_disruption", type: "disruption", @@ -275,6 +277,7 @@ describe("a closure the motorway operator publishes", () => { registry, { claim: { + v: 1, claimClass: "situation", kind: "closure", type: "closure", @@ -303,6 +306,7 @@ describe("a closure the motorway operator publishes", () => { registry, { claim: { + v: 1, claimClass: "situation", kind: "closure", type: "closure", @@ -415,6 +419,7 @@ describe("a charge point two sources describe", () => { registry, { claim: { + v: 1, claimClass: "observation", subject: { featureId: live.feature["id"] as string, componentKey: charging }, property: "charging.evse_status", @@ -446,6 +451,7 @@ describe("a charge point two sources describe", () => { registry, { claim: { + v: 1, claimClass: "observation", subject: { featureId: live.feature["id"] as string, componentKey: charging }, property: "charging.evse_status", @@ -467,6 +473,7 @@ describe("a charge point two sources describe", () => { registry, { claim: { + v: 1, claimClass: "observation", subject: { featureId: live.feature["id"] as string, componentKey: "no-such-point" }, property: "charging.evse_status", @@ -558,6 +565,7 @@ describe("a charge point the operator reports out of order", () => { registry, { claim: { + v: 1, claimClass: "observation", subject: { featureId: feature["id"] as string, componentKey: lorenz.evses[0]!.uid }, property: "charging.evse_status", @@ -619,6 +627,7 @@ describe("a fuel price a driver reads off the pole", () => { registry, { claim: { + v: 1, claimClass: "observation", subject: { featureId: id, componentKey: "e5" }, property: "fuel.price", diff --git a/packages/model/src/__tests__/claim.test.ts b/packages/model/src/__tests__/claim.test.ts index 383f7883e..42a5bed91 100644 --- a/packages/model/src/__tests__/claim.test.ts +++ b/packages/model/src/__tests__/claim.test.ts @@ -6,6 +6,7 @@ const messages = (r: ReturnType) => r.ok ? [] : r.issues.map((i) => `${i.path.join(".")}: ${i.message}`); const priceClaim = (overrides: Record = {}) => ({ + v: 1, claimClass: "observation", subject: { featureId: "oc:feature:es-minetur:4375", componentKey: "e5" }, property: "fuel.price", @@ -84,6 +85,17 @@ describe("report claims", () => { expect(validateClaim(crowdRegistry, accidentClaim({ nonce: "short" })).ok).toBe(false); }); + it("takes only the claim version 1, as its top-level member v", () => { + const { v: _v, ...unversioned } = accidentClaim(); + expect(messages(validateClaim(crowdRegistry, unversioned))).toEqual([ + expect.stringMatching(/^v: /), + ]); + expect(messages(validateClaim(crowdRegistry, accidentClaim({ v: 2 })))).toEqual([ + expect.stringMatching(/^v: /), + ]); + expect(validateClaim(crowdRegistry, priceClaim({ v: "1" })).ok).toBe(false); + }); + it("validates an observation claim's result and qualifiers as its property's observations", () => { expect(messages(validateClaim(crowdRegistry, priceClaim()))).toEqual([]); expect( @@ -141,6 +153,7 @@ describe("report claims", () => { describe("sub-claims", () => { const body = { + v: 1, subject: { class: "observation", id: "oc:observation:oc.example.org:abc" }, claimType: "negate", reportedAt: "2026-10-01T11:58:00Z", @@ -164,6 +177,9 @@ describe("sub-claims", () => { false, ); expect(validateSubClaim({ ...body, claimType: "like" }).ok).toBe(false); + const { v: _v, ...unversioned } = body; + expect(validateSubClaim(unversioned).ok).toBe(false); + expect(validateSubClaim({ ...body, v: 2 }).ok).toBe(false); expect( validateSubClaim({ ...body, diff --git a/packages/model/src/__tests__/crowd-fixtures.ts b/packages/model/src/__tests__/crowd-fixtures.ts index c25fe7057..7a30303dc 100644 --- a/packages/model/src/__tests__/crowd-fixtures.ts +++ b/packages/model/src/__tests__/crowd-fixtures.ts @@ -130,6 +130,7 @@ export const crowdAttribution = { provider: "oc.example.org", license: "CC0-1.0" export function accidentClaim(overrides: Record = {}) { return { + v: 1, claimClass: "situation", kind: "incident", type: "accident", diff --git a/packages/model/src/__tests__/identity.test.ts b/packages/model/src/__tests__/identity.test.ts index c3448eb0b..eaf555685 100644 --- a/packages/model/src/__tests__/identity.test.ts +++ b/packages/model/src/__tests__/identity.test.ts @@ -42,6 +42,28 @@ describe("record ids", () => { expect(isInstanceId("-local")).toBe(false); }); + it("takes a configured instance id only as a lower-case DNS name", () => { + expect(isInstanceId("openmapx.com")).toBe(true); + expect(isInstanceId("node-a")).toBe(true); + expect(isInstanceId(`${"a".repeat(63)}.example.org`)).toBe(true); + for (const bad of [ + "", + "a..b", + "a-.b", + "a.-b", + ".a", + "a.", + "a_b", + "a:b", + `${"a".repeat(64)}.org`, + ]) { + expect(isInstanceId(bad), bad).toBe(false); + } + const long = Array.from({ length: 64 }, () => "abc").join("."); + expect(long.length).toBeGreaterThan(253); + expect(isInstanceId(long)).toBe(false); + }); + it("keeps canonicalId = sha256([namespace, localId]) with the namespace normalised", () => { expect(canonicalIdOf(" DE-NDW ", "x")).toBe(canonicalIdOf("de-ndw", "x")); expect(canonicalIdOf("a:b", "c")).not.toBe(canonicalIdOf("a", "b:c")); diff --git a/packages/model/src/__tests__/land.test.ts b/packages/model/src/__tests__/land.test.ts index c4609b3dc..fcca6cfc0 100644 --- a/packages/model/src/__tests__/land.test.ts +++ b/packages/model/src/__tests__/land.test.ts @@ -22,6 +22,7 @@ const ctx: LandingContext = { }; const priceClaim = (overrides: Record = {}) => ({ + v: 1, claimClass: "observation", subject: { featureId: "oc:feature:es-minetur:4375", componentKey: "e5" }, property: "fuel.price", diff --git a/packages/model/src/crowd/claim.ts b/packages/model/src/crowd/claim.ts index 621521b8b..87cb0baf4 100644 --- a/packages/model/src/crowd/claim.ts +++ b/packages/model/src/crowd/claim.ts @@ -14,6 +14,14 @@ import { majorOf } from "../registry/define.js"; * is plain JSON. */ export const CLAIM_CLASSES = ["situation", "observation"] as const; + +/** + * The signed-claim format version: every report claim and sub-claim body + * carries it as its top-level member `v`, inside the signed bytes, and a + * claim of another version is refused. A change to what a claim's bytes mean + * takes a new version. + */ +export const CLAIM_VERSION = 1; export const SUB_CLAIM_TYPES = ["confirm", "negate", "flag"] as const; /** Anti-replay token: 16–64 characters of [A-Za-z0-9_-]. */ @@ -27,6 +35,7 @@ type Text = { lang: string; text: string; machine?: true }[]; /** "Something is happening here": a situation the reporter sees. */ export interface SituationClaim { + v: typeof CLAIM_VERSION; claimClass: "situation"; kind: string; type: string; @@ -44,6 +53,7 @@ export interface SituationClaim { /** "This is the value now": a reading of a property of a feature or a place. */ export interface ObservationClaim { + v: typeof CLAIM_VERSION; claimClass: "observation"; subject: { featureId: string; componentKey?: string } | { location: LocationRef }; property: string; @@ -65,6 +75,7 @@ export type ReportClaim = SituationClaim | ObservationClaim; /** A reporter's reaction to any record: it is still there, it is gone, or it is wrong. */ export interface SubClaimBody { + v: typeof CLAIM_VERSION; subject: RecordRef; claimType: (typeof SUB_CLAIM_TYPES)[number]; /** Why a record is flagged. */ @@ -95,6 +106,7 @@ export function claimSchema(registry: Registry): z.ZodType { const situation = z .strictObject({ + v: z.literal(CLAIM_VERSION), claimClass: z.literal("situation"), kind: enumOrNever(crowdKinds.map((e) => e.code)), type: z.string().min(1), @@ -145,6 +157,7 @@ export function claimSchema(registry: Registry): z.ZodType { const observation = z .strictObject({ + v: z.literal(CLAIM_VERSION), claimClass: z.literal("observation"), subject: z.union([ z.strictObject({ @@ -208,6 +221,7 @@ export function validateClaim(registry: Registry, claim: unknown): ValidationRes } export const SubClaimBodySchema = z.strictObject({ + v: z.literal(CLAIM_VERSION), subject: z .strictObject({ class: z.enum(["feature", "situation", "observation", "offer"]), diff --git a/packages/model/src/kernel/identity.ts b/packages/model/src/kernel/identity.ts index a4ecd0598..1360aa66a 100644 --- a/packages/model/src/kernel/identity.ts +++ b/packages/model/src/kernel/identity.ts @@ -11,8 +11,26 @@ export function isSourceId(value: string): boolean { return SOURCE_ID_PATTERN.test(value); } +const DNS_LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"; + +/** + * An instance's own id, as an operator configures it: a lower-case DNS name, + * labels of letters, digits and inner dashes up to 63 characters, joined by + * single dots, 253 characters at most. Every such id is also a record-id + * namespace ({@link INSTANCE_ID_PATTERN}). That looser pattern stays the one + * record ids and provenance are parsed with, on purpose: a namespace is also + * a source id (`oc:situation:nl-ndw-events:…`), and a stored record's source + * identity is not a configured instance id. Wherever an instance names + * itself or a peer (the service's environment, the actor and peers configs, + * the registry), this grammar applies. + */ +export const CONFIGURED_INSTANCE_ID_PATTERN = new RegExp(`^${DNS_LABEL}(?:\\.${DNS_LABEL})*$`); + +/** The longest instance id: a DNS name's limit. */ +export const MAX_INSTANCE_ID_LENGTH = 253; + export function isInstanceId(value: string): boolean { - return INSTANCE_ID_PATTERN.test(value); + return value.length <= MAX_INSTANCE_ID_LENGTH && CONFIGURED_INSTANCE_ID_PATTERN.test(value); } export interface RecordIdParts { diff --git a/packages/storage/src/__tests__/canonical-golden.integration.test.ts b/packages/storage/src/__tests__/canonical-golden.integration.test.ts index 47aadebdf..45499cd7e 100644 --- a/packages/storage/src/__tests__/canonical-golden.integration.test.ts +++ b/packages/storage/src/__tests__/canonical-golden.integration.test.ts @@ -433,6 +433,7 @@ describe("a crowd reading on a component whose canonical key changes", () => { registry, { claim: { + v: 1, claimClass: "observation", subject: { featureId: before.canonical_feature_id, componentKey: reportedKey }, property: "fuel.price", diff --git a/packages/storage/src/__tests__/canonical-karlsruhe.integration.test.ts b/packages/storage/src/__tests__/canonical-karlsruhe.integration.test.ts index 1725164eb..952e655a6 100644 --- a/packages/storage/src/__tests__/canonical-karlsruhe.integration.test.ts +++ b/packages/storage/src/__tests__/canonical-karlsruhe.integration.test.ts @@ -208,6 +208,7 @@ describe("a crowd reading on the canonical car park", () => { registry, { claim: { + v: 1, claimClass: "observation", subject: { featureId: canonical.canonical_feature_id, componentKey }, property: "charging.evse_status", diff --git a/packages/storage/src/__tests__/fused-rows.integration.test.ts b/packages/storage/src/__tests__/fused-rows.integration.test.ts index 3b7c79dfc..4de752e31 100644 --- a/packages/storage/src/__tests__/fused-rows.integration.test.ts +++ b/packages/storage/src/__tests__/fused-rows.integration.test.ts @@ -694,6 +694,7 @@ describe("where a crowd-won public fusion sits", () => { registry, { claim: { + v: 1, claimClass: "observation", subject: { featureId: canonical, componentKey: e10Key }, property: "fuel.price", @@ -927,6 +928,7 @@ describe("property scopes in fusion reads", () => { registry, { claim: { + v: 1, claimClass: "observation", subject: { featureId: canonical, componentKey }, property: "fuel.price", diff --git a/scripts/__tests__/container-images.test.ts b/scripts/__tests__/container-images.test.ts index e27ec12e4..6a9a8c17e 100644 --- a/scripts/__tests__/container-images.test.ts +++ b/scripts/__tests__/container-images.test.ts @@ -134,6 +134,7 @@ function reports(image = "contributions-api") { : `openconditions-${image}`, }, migratedTables: 58, + sealedInstanceId: "qualification.example.org", ...(image === "ingest" ? { osmiumVersion: "osmium version 1.19.1", @@ -325,6 +326,8 @@ describe("complete image matrix evidence", () => { "duplicate-cleanup", "wrong-runtime-image", "zero-migrations", + "missing-seal", + "wrong-seal", "failed-cleanup", "stale-db", "empty-coverage", @@ -353,6 +356,8 @@ describe("complete image matrix evidence", () => { if (kind === "wrong-runtime-image") d["runtime.json"].dockerRuntimeImageId = "sha256:" + "f".repeat(64); if (kind === "zero-migrations") d["runtime.json"].checks.migratedTables = 0; + if (kind === "missing-seal") delete d["runtime.json"].checks.sealedInstanceId; + if (kind === "wrong-seal") d["runtime.json"].checks.sealedInstanceId = "other.example.org"; if (kind === "failed-cleanup") d["runtime.json"].cleanup[0].absent = false; if (kind === "stale-db") d["scanner-db.json"].NextUpdate = "2026-10-26T20:00:00Z"; if (kind === "empty-coverage") d["scan.json"].Results = []; diff --git a/scripts/__tests__/service-manifests.test.ts b/scripts/__tests__/service-manifests.test.ts index 522212b01..a35b08e0e 100644 --- a/scripts/__tests__/service-manifests.test.ts +++ b/scripts/__tests__/service-manifests.test.ts @@ -150,13 +150,6 @@ describe("service manifests on OpenMapX's config model", () => { } }); - test.each(manifests)( - "%s: no JSON Schema `required` (OpenMapX validates it against the non-secret values only)", - (_dir, m) => { - expect(m.configSchema?.required).toBeUndefined(); - }, - ); - test.each(manifests)("%s: OpenMapX accepts it as a community service", (_dir, m) => { expect(m.configSchema?.type).toBe("object"); // A third-party volume is namespaced by the service id; no platform proxy route. @@ -194,7 +187,7 @@ describe("service manifests on OpenMapX's config model", () => { * contributions API fetches nothing through the egress guard or the * downloader, writes single records rather than a feed's poll, and runs no * rollups. The federation service bundles the contributions API for its - * inbox only: it issues no grants, serves no reviewer, lands no crowd + * inbox only: it issues no grants, serves no reviewer, trusts no relay, lands no crowd * report of its own and runs no sweep, and downloads no feed. */ const unreached: Record = { @@ -227,6 +220,8 @@ describe("service manifests on OpenMapX's config model", () => { "OPENCONDITIONS_LATEST_CACHE_MB", "OPENCONDITIONS_MAX_FEED_BYTES", "OPENCONDITIONS_MAX_OBSERVATIONS_PER_POLL", + "OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE", + "OPENCONDITIONS_RELAY_TOKEN", "OPENCONDITIONS_REVIEWER_TOKEN", "OPENCONDITIONS_ROLLUP_DAILY_DAYS", "OPENCONDITIONS_ROLLUP_HOURLY_DAYS", @@ -339,17 +334,19 @@ describe("service manifests on OpenMapX's config model", () => { } }); - test("contributions-api: its database URL, secrets key, grant secret and reviewer token are vault secrets", () => { + test("contributions-api: its database URL, secrets key, grant secret, reviewer token and relay token are vault secrets", () => { const m = manifest("contributions-api"); expect(m.container.environment).toEqual({ PORT: "4200", HOST: "0.0.0.0" }); expect(secrets(m).sort()).toEqual([ "DATABASE_URL", "OPENCONDITIONS_GRANT_SECRET", + "OPENCONDITIONS_RELAY_TOKEN", "OPENCONDITIONS_REVIEWER_TOKEN", "OPENCONDITIONS_SECRETS_KEY", ]); const expected = { OPENCONDITIONS_INSTANCE_ID: "", + OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE: "", OPENCONDITIONS_SCHEMA_WAIT_TIMEOUT_MS: "", OPENCONDITIONS_ISSUER_NAME: "", OPENCONDITIONS_CROSS_VALIDATE_SWEEP: "", @@ -385,3 +382,95 @@ describe("service manifests on OpenMapX's config model", () => { expect(extension.services.map((s) => s.service)).not.toContain(manifest("federation").id); }); }); + +describe("OpenMapX's community manifest rules", () => { + const extension = JSON.parse(readFileSync(new URL("extension.json", repo), "utf8")) as Record< + string, + unknown + > & { services: { service: string }[] }; + const ID = /^[a-z0-9]+(-[a-z0-9]+)*$/; + const SEMVER = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; + const all = (): [string, Record][] => [ + ["extension.json", extension], + ...manifests.map( + ([dir, m]) => + [`services/${dir}/service.json`, m as unknown as Record] as [ + string, + Record, + ], + ), + ]; + + test.each(all())("%s declares platform 1.0, a semver version and a valid id", (_path, m) => { + expect(m["platform"]).toBe("1.0"); + expect(m["version"]).toMatch(SEMVER); + expect(m["id"]).toMatch(ID); + expect((m["id"] as string).length).toBeLessThanOrEqual(48); + }); + + test.each(manifests)("services/%s/service.json is labelled community", (_dir, m) => { + expect((m as unknown as { quality: string }).quality).toBe("community"); + }); + + test.each(manifests)( + "services/%s/service.json names its capabilities and data types under the openconditions vendor", + (_dir, m) => { + const raw = m as unknown as { + provides?: (string | { capability: string })[]; + produces?: { type: string }[]; + consumes?: { type: string }[]; + }; + const names = [ + ...(raw.provides ?? []).map((p) => (typeof p === "string" ? p : p.capability)), + ...(raw.produces ?? []).map((p) => p.type), + ...(raw.consumes ?? []).map((c) => c.type), + ]; + for (const name of names) expect(name).toMatch(/^openconditions\/[a-z0-9]+(-[a-z0-9]+)*$/); + }, + ); + + test("the extension's licence is the licence of every service it installs", () => { + for (const { service } of extension.services) { + const found = manifests.find(([, m]) => m.id === service); + expect(found, service).toBeDefined(); + expect((found![1] as unknown as { license: string }).license).toBe(extension["license"]); + } + expect(extension["license"]).toBe("AGPL-3.0-or-later"); + }); + + // OpenMapX applies a configuration only once every enabled service has a + // value or a stored secret for each key its schema requires, and names the + // missing ones; a service not enabled is not held to them. Each list is + // exactly what the service refuses to start without. + const required: Record = { + ingest: ["DATABASE_URL", "OPENCONDITIONS_SECRETS_KEY", "OPENCONDITIONS_INSTANCE_ID"], + "ingest-heavy": [ + "DATABASE_URL", + "OPENCONDITIONS_SECRETS_KEY", + "OPENCONDITIONS_INSTANCE_ID", + "OPENCONDITIONS_INGEST_FEEDS", + ], + "contributions-api": [ + "DATABASE_URL", + "OPENCONDITIONS_SECRETS_KEY", + "OPENCONDITIONS_GRANT_SECRET", + "OPENCONDITIONS_REVIEWER_TOKEN", + "OPENCONDITIONS_INSTANCE_ID", + ], + // The secrets key is needed only when federation is enabled. + federation: ["DATABASE_URL", "OPENCONDITIONS_INSTANCE_ID"], + }; + + test.each(manifests)( + "services/%s/service.json requires exactly the settings the service cannot start without", + (dir, m) => { + expect(m.configSchema?.required).toEqual(required[dir]); + for (const key of required[dir] ?? []) expect(properties(m), key).toHaveProperty(key); + }, + ); + + test("every OpenConditions service manifest is covered", () => { + expect(manifests.map(([dir]) => dir).sort()).toEqual(Object.keys(required).sort()); + }); +}); diff --git a/scripts/__tests__/test_trusted_main_images.py b/scripts/__tests__/test_trusted_main_images.py index 80c4c8450..d5c604e3e 100644 --- a/scripts/__tests__/test_trusted_main_images.py +++ b/scripts/__tests__/test_trusted_main_images.py @@ -123,6 +123,7 @@ def blob(value): else "openconditions-" + role, }, "migratedTables": 58, + "sealedInstanceId": "qualification.example.org", } if role == "ingest": checks.update( diff --git a/scripts/check-docker-contexts.mjs b/scripts/check-docker-contexts.mjs index 7ef49a0e8..dbea33f0d 100644 --- a/scripts/check-docker-contexts.mjs +++ b/scripts/check-docker-contexts.mjs @@ -157,7 +157,7 @@ function producer(root) { // A changed Python producer needs a fresh review of these context/recipe facts. if ( sha256(regular(join(root, "scripts/qualify-container-images.py")).bytes) !== - "b70bff6295c2bc190139b89e5b78279b07c1d3fac4d8ff709c6bcacb35eebfd8" || + "bda8850b252693fdd12a8510dcabe5ad129d09c6f6e5a709fc257f0239435ede" || JSON.stringify(job?.strategy?.matrix) !== JSON.stringify({ image: images.map((i) => i.image) }) || step?.length !== 1 || diff --git a/scripts/fixtures/openmapx-contract-consumer/application-lock.yaml b/scripts/fixtures/openmapx-contract-consumer/application-lock.yaml index 9760de921..ae81a4c18 100644 --- a/scripts/fixtures/openmapx-contract-consumer/application-lock.yaml +++ b/scripts/fixtures/openmapx-contract-consumer/application-lock.yaml @@ -16,7 +16,7 @@ packages: "@openmapx/extension-cli@file:portable.tgz": resolution: { - integrity: sha512-cQoHGIH33TBuBgOJKo5MJfF6f3rzhWUtIJof+GQsJyeKN3eyxVF7Q/tXTYRnL8QTid3OMJ48nXfVSfjSwF1tYQ==, + integrity: sha512-lLBjn1UvAcBGmnXHJ1x1IpRVJ/NpMM72TqNPWrg+fxwetqfzICJSul2pmEpj8kibyj+REkiCJrVKyOYZOc8LIA==, tarball: file:portable.tgz, } version: 0.1.0 diff --git a/scripts/gen-credentials.ts b/scripts/gen-credentials.ts index 01f7a2633..19d8a1c86 100644 --- a/scripts/gen-credentials.ts +++ b/scripts/gen-credentials.ts @@ -8,6 +8,8 @@ import { credentialsDocFor, envExampleFor, FEEDS_PROCESS_DESCRIPTIONS, + FEEDS_PROCESS_REQUIRED_FIELDS, + REQUIRED_SERVICE_FIELDS, } from "./lib/gen-credentials-lib.js"; export interface GenPaths { @@ -34,9 +36,13 @@ interface ServiceJson { function nextServiceJson( svc: ServiceJson, catalog: CredentialCatalog, + required: readonly string[], descriptions: Readonly> = {}, ): string { const properties = configSchemaPropertiesFor(catalog); + for (const key of required) { + if (properties[key] === undefined) throw new Error(`no config field ${key} to require`); + } for (const [key, description] of Object.entries(descriptions)) { const field = properties[key] as Record | undefined; if (field === undefined) throw new Error(`no config field ${key} to describe`); @@ -51,7 +57,7 @@ function nextServiceJson( } const next = { ...svc, - configSchema: { type: "object", ...(svc.configSchema ?? {}), properties }, + configSchema: { type: "object", ...(svc.configSchema ?? {}), required, properties }, }; return `${JSON.stringify(next, null, 2)}\n`; } @@ -78,6 +84,13 @@ DATABASE_URL=postgres://openconditions:openconditions@localhost:5432/openconditi # OPENCONDITIONS_SECRETS_KEY_FILE may name a file holding it instead. OPENCONDITIONS_SECRETS_KEY= +# Instance id (REQUIRED): a lower-case DNS name, usually the instance's public +# host name, e.g. maps.example.org. Set it once, before the first start, to the +# same value on every OpenConditions service of the instance. The first ingest +# start seals it in the database, and every service refuses another id; it is +# part of every record id, so it never changes. +OPENCONDITIONS_INSTANCE_ID= + # HTTP server (optional; defaults shown) PORT=4100 HOST=0.0.0.0 @@ -182,14 +195,14 @@ export function applyOrCheck( const svc = JSON.parse(readFileSync(paths.serviceJson, "utf8")) as ServiceJson; const targets: [string, string][] = [ [paths.envExample, nextEnvExample(safeRead(paths.envExample), catalog)], - [paths.serviceJson, nextServiceJson(svc, catalog)], + [paths.serviceJson, nextServiceJson(svc, catalog, REQUIRED_SERVICE_FIELDS)], [paths.doc, credentialsDocFor(catalog, svc.id)], ]; if (paths.feedsServiceJson) { const feeds = JSON.parse(readFileSync(paths.feedsServiceJson, "utf8")) as ServiceJson; targets.push([ paths.feedsServiceJson, - nextServiceJson(feeds, catalog, FEEDS_PROCESS_DESCRIPTIONS), + nextServiceJson(feeds, catalog, FEEDS_PROCESS_REQUIRED_FIELDS, FEEDS_PROCESS_DESCRIPTIONS), ]); } const drift: string[] = []; diff --git a/scripts/lib/gen-credentials-lib.ts b/scripts/lib/gen-credentials-lib.ts index 0fee6a383..a55ee01e2 100644 --- a/scripts/lib/gen-credentials-lib.ts +++ b/scripts/lib/gen-credentials-lib.ts @@ -162,6 +162,24 @@ export const FEEDS_PROCESS_DESCRIPTIONS: Readonly> = { "Required. Copy the value of openconditions-ingest's Secrets key; never generate a new one. The OAuth grant tokens this process refreshes are encrypted with it, and it refuses to start with any other key. It is not recoverable from the OpenConditions tables: the copy in your recovery set is the ingest service's.", }; +/** + * The fields the ingest service refuses to start without, which its + * manifest lists as `configSchema.required`: OpenMapX then applies a + * configuration only once an enabled service has a value or a stored secret + * for each, and names the ones it lacks. + */ +export const REQUIRED_SERVICE_FIELDS: readonly string[] = [ + "DATABASE_URL", + "OPENCONDITIONS_SECRETS_KEY", + "OPENCONDITIONS_INSTANCE_ID", +]; + +/** The heavy-feeds process's required fields: the ingest service's, and the feeds it polls. */ +export const FEEDS_PROCESS_REQUIRED_FIELDS: readonly string[] = [ + ...REQUIRED_SERVICE_FIELDS, + "OPENCONDITIONS_INGEST_FEEDS", +]; + /** * The ingest service's own configuration, hand-written here and written into * `service.json` beside the fields generated from the catalogue. Under @@ -250,7 +268,7 @@ export const SERVICE_FIELDS: Readonly> = { OPENCONDITIONS_EGRESS_ALLOWED_HOSTS: { title: "Egress allowed private hosts", description: - "Comma-separated hostnames the egress guard lets the service fetch although they resolve to private addresses, e.g. overpass for a self-hosted Overpass on the compose network. Empty: none.", + "Comma-separated hostnames the egress guard lets the service fetch although they resolve to private addresses, e.g. openmapx-overpass for OpenMapX's Overpass service. Empty: none.", default: "", }, OPENCONDITIONS_DOWNLOAD_MAX_BYTES: { @@ -332,7 +350,7 @@ export const SERVICE_FIELDS: Readonly> = { OPENCONDITIONS_INSTANCE_ID: { title: "Instance id", description: - "This instance's stable id, the namespace of every record it originates and its name to federation peers: lower-case letters, digits, dots and dashes, e.g. maps.example.org. Set it before federating, and to the same value as the contributions API's. Empty: local.", + "Required. This instance's stable id, the namespace of every record it originates and its name to federation peers: a lower-case DNS name, e.g. maps.example.org. Set it before the first start; it can never change afterwards. The first ingest process to start seals it in the database, and every OpenConditions service of the instance (the heavy-feeds ingest, contributions API and federation) needs this same value. The service refuses to start without it, with a value that is not a DNS name, or with another id than the sealed one.", default: "", }, OPENCONDITIONS_CROWD_LICENSE: { diff --git a/scripts/openmapx-product-contracts.json b/scripts/openmapx-product-contracts.json index c95d91d66..5b70b7bb6 100644 --- a/scripts/openmapx-product-contracts.json +++ b/scripts/openmapx-product-contracts.json @@ -1,19 +1,19 @@ { "schemaVersion": 1, "repository": "https://github.com/OpenMapX/openmapx", - "sourceSha": "bf551c68b4389b4acbdcbb878b005128a23763ac", + "sourceSha": "19754a18a752b9a6df1369007764fd44020bd195", "portable": { "name": "@openmapx/extension-cli", "version": "0.1.0", - "archiveSha256": "c0ba88afca002fcc6d04c9a401edf6feb4152a7c2291b821b53660a6ad4d3a08", - "packageTreeSha256": "ac57138e1c823598eb9bb05275890a7379c26392af2e56b45cafeaf9b6bd0224", + "archiveSha256": "e5be5897e3f2e948eeaeb915934f5c49c89fbeae59133b8aaae967dce632fa41", + "packageTreeSha256": "1695734d404b82713a03f42345e0a6af27153848d83ddeb1ecc97a44b3e09f4d", "commanderVersion": "15.0.0", "commanderTreeSha256": "8e2b1532b97a272ae20c51916cb938e66b78b74150a39d6b086a5d357d0e05c0" }, "admission": { - "entrySha256": "a86159486baf3a2e6e4f898ea8ea9aaddd865cff2cdecf09bff45e9523f00fe8", + "entrySha256": "82824fbd7f2f792ce903b71c6f542fdfa4c089a107dde05c0bd22381ea01983d", "sourceFile": "packages/core/src/services/community-manifest.ts", - "sourceSha256": "8f11bc46de13021fdf06b16f968d73d3d24f659b983c389cf9acc19e4ac6427e", + "sourceSha256": "a16d7072bead0938188efb6211bb570ecf55cd75088764f9805efee5d2da10a4", "export": "communityServiceManifestProblems" }, "scope": "Local portable extension/service and community admission contract validation only; not deployed host acceptance" diff --git a/scripts/qualify-container-images.py b/scripts/qualify-container-images.py index 051491fe9..f7ef51b5e 100755 --- a/scripts/qualify-container-images.py +++ b/scripts/qualify-container-images.py @@ -349,7 +349,7 @@ def verify_reports(directory, image, source, expected_execution): expected_checks = ( {"openlrGraphHttpNative"} if image == "openlr-resolver" - else {"httpNativeCrypto", "migratedTables"} + else {"httpNativeCrypto", "migratedTables", "sealedInstanceId"} ) if image == "ingest": expected_checks |= { @@ -392,6 +392,8 @@ def verify_reports(directory, image, source, expected_execution): or checks["migratedTables"] < 10 ): fail("runtime HTTP/migrations qualification missing") + if checks["sealedInstanceId"] != QUALIFICATION_INSTANCE_ID: + fail("runtime instance id seal qualification missing") if image == "ingest" and ( checks["bundledFeedsMigrationsImpit"] is not True or not checks["osmiumVersion"].startswith("osmium version 1.19.1") @@ -579,6 +581,29 @@ def remove_owned(kind, name, label): } """ +# The instance id every service of the fixture runs with. The ingest service +# seals it after migrating; the contributions and federation services wait for +# that row and refuse another id. +QUALIFICATION_INSTANCE_ID = "qualification.example.org" + +# The ingest service's instance id seal, as sealInstanceId writes it: one row, +# written once, then read back and compared, so a service started next with +# the same id finds it and one with another id is refused. +SEAL_INSTANCE_ID = """ +import postgres from "postgres"; +const id = process.env.OPENCONDITIONS_INSTANCE_ID; +const sql = postgres(process.env.DATABASE_URL, { max: 1 }); +try { + await sql` + INSERT INTO conditions.instance_identity (id, instance_id) VALUES (1, ${id}) + ON CONFLICT (id) DO NOTHING`; + const [row] = await sql`SELECT instance_id FROM conditions.instance_identity WHERE id = 1`; + if (row?.instance_id !== id) throw new Error("the sealed instance id differs"); +} finally { + await sql.end(); +} +""" + def ingest_migration_script(source): """The source's migrations, recorded in conditions.__drizzle_migrations as the @@ -739,11 +764,15 @@ def runtime_smoke(image, identity, source, output, *, exercise=None): "OPENCONDITIONS_GRANT_SECRET": uuid.uuid4().hex + uuid.uuid4().hex, "OPENCONDITIONS_REVIEWER_TOKEN": uuid.uuid4().hex + uuid.uuid4().hex, "OPENCONDITIONS_SECRETS_KEY": uuid.uuid4().hex + uuid.uuid4().hex, + "OPENCONDITIONS_INSTANCE_ID": QUALIFICATION_INSTANCE_ID, } - if image == "contributions-api": - # The ingest service seals the secrets key check after migrating, - # and this service waits for it; seal it as ingest does, inside - # the image, before the service starts. + + def seal(script, *names): + """Run a seal the ingest service writes after migrating, inside the + image, with the named variables of the service's environment.""" + passed = [] + for name in ("DATABASE_URL", *names): + passed += ["-e", f"{name}={env[name]}"] command( [ "docker", @@ -755,18 +784,23 @@ def runtime_smoke(image, identity, source, output, *, exercise=None): network, "--platform", PLATFORM, - "-e", - f"DATABASE_URL={env['DATABASE_URL']}", - "-e", - f"OPENCONDITIONS_SECRETS_KEY={env['OPENCONDITIONS_SECRETS_KEY']}", + *passed, "--entrypoint", "node", loaded, "--input-type=module", "-e", - SEAL_SECRETS_KEY_CHECK, + script, ] ) + + if image in ("contributions-api", "federation"): + # These services wait at start for what the ingest service seals + # after migrating, and refuse to start with another value; seal it + # as ingest does before the service starts. + seal(SEAL_INSTANCE_ID, "OPENCONDITIONS_INSTANCE_ID") + if image == "contributions-api": + seal(SEAL_SECRETS_KEY_CHECK, "OPENCONDITIONS_SECRETS_KEY") args = [ "docker", "run", @@ -836,6 +870,14 @@ def runtime_smoke(image, identity, source, output, *, exercise=None): if tables < 10: fail("migrations were not applied") record["checks"]["migratedTables"] = tables + # The ingest service seals its own id at start; the others started + # only because the id they were given matched the sealed one. + sealed = command( + [*sql, "select instance_id from conditions.instance_identity where id = 1"] + ).stdout.strip() + if sealed != QUALIFICATION_INSTANCE_ID: + fail("the instance id was not sealed as the service requires") + record["checks"]["sealedInstanceId"] = sealed if image == "ingest": record["checks"]["osmiumVersion"] = command( ["docker", "exec", app, "osmium", "--version"] diff --git a/services/contributions-api/README.md b/services/contributions-api/README.md index 5119ad49a..66cf73f3a 100644 --- a/services/contributions-api/README.md +++ b/services/contributions-api/README.md @@ -10,6 +10,8 @@ on (`@openconditions/core`, `model`, `contrib-core`). ## Crowd reports +Every signed claim and sub-claim body carries the claim version as its top-level member `"v": 1`, inside the signed bytes (see [the wire contract](../../packages/contrib-core/README.md#claim-version)). A report or vote whose body lacks it or names another version is refused with `400` and `{ error, code: "CLAIM_VERSION_UNSUPPORTED" }` before its signature is checked. + - `POST /contrib/reports` — a signed model claim. A situation claim lands as a situation record of the `crowd` source (`landClaim`, then the write seam), with its first `report` evidence row; its evidence decides when it ends @@ -59,20 +61,26 @@ operator's erasure (see `docs/federation-gdpr.md`). ## Configuration -| Variable | Meaning | Default | -| --------------------------------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------- | -| `DATABASE_URL` | PostgreSQL/PostGIS connection URL. Required. | none | -| `OPENCONDITIONS_GRANT_SECRET` | HMAC secret signing reporting grants. Required in production. | ephemeral outside production | -| `OPENCONDITIONS_REVIEWER_TOKEN` | Bearer token of the reviewer surface. Required in production. | ephemeral outside production | -| `OPENCONDITIONS_SECRETS_KEY` | Key the issuer's private keys are encrypted with; the ingest service's. Required. | none | -| `OPENCONDITIONS_ISSUER_NAME` | TokenChallenge issuer name. | `contributions.openconditions.org` | -| `OPENCONDITIONS_CROSS_VALIDATE_SWEEP` | `off` stops the sweep that retries cross-validation of unresolved crowd reports. | on | -| `OPENCONDITIONS_INSTANCE_ID` | This instance's id, the namespace of the crowd records it lands; the ingest service's. | `local` | -| `OPENCONDITIONS_CROWD_LICENSE` | Licence of this instance's crowd reports (an id of the licence registry); the ingest service's. | `ODbL-1.0` | -| `OPENCONDITIONS_CROWD_SOURCE_URI` | Link the crowd's credit carries, an http(s) URL; the ingest service's. | none | -| `OPENCONDITIONS_ALLOW_POLICE_CATEGORY` | `true` lets crowd reports of police presence land. | off | -| `OPENCONDITIONS_SCHEMA_WAIT_TIMEOUT_MS` | How long the service waits at start for the schema version, in milliseconds. | 300000 | +| Variable | Meaning | Default | +| ---------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------- | +| `DATABASE_URL` | PostgreSQL/PostGIS connection URL. Required. | none | +| `OPENCONDITIONS_GRANT_SECRET` | HMAC secret signing reporting grants. Required in production. | ephemeral outside production | +| `OPENCONDITIONS_REVIEWER_TOKEN` | Bearer token of the reviewer surface. Required in production. | ephemeral outside production | +| `OPENCONDITIONS_SECRETS_KEY` | Key the issuer's private keys are encrypted with; the ingest service's. Required. | none | +| `OPENCONDITIONS_ISSUER_NAME` | TokenChallenge issuer name. | `contributions.openconditions.org` | +| `OPENCONDITIONS_CROSS_VALIDATE_SWEEP` | `off` stops the sweep that retries cross-validation of unresolved crowd reports. | on | +| `OPENCONDITIONS_INSTANCE_ID` | This instance's id, the namespace of the crowd records it lands; the ingest service's. Required. | none | +| `OPENCONDITIONS_CROWD_LICENSE` | Licence of this instance's crowd reports (an id of the licence registry); the ingest service's. | `ODbL-1.0` | +| `OPENCONDITIONS_CROWD_SOURCE_URI` | Link the crowd's credit carries, an http(s) URL; the ingest service's. | none | +| `OPENCONDITIONS_ALLOW_POLICE_CATEGORY` | `true` lets crowd reports of police presence land. | off | +| `OPENCONDITIONS_SCHEMA_WAIT_TIMEOUT_MS` | How long the service waits at start for the schema version, in milliseconds. | 300000 | +| `OPENCONDITIONS_RELAY_TOKEN` | Bearer token of a trusted relay, at least 32 characters; OpenMapX's `OPENCONDITIONS_RELAY_TOKEN`. | none (no relay trusted) | +| `OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE` | Enrollments a minute all requests bearing the relay token may make together. | 600 | + +Each of the five secrets may instead be a file named by `_FILE`. The secrets key is a copy of the ingest service's, never a newly generated one: after the schema version the service waits for the ingest service's key check (`conditions.secrets_key_check`) and refuses to start when its key does not open it; see [Secrets encrypted at rest](../../README.md#secrets-encrypted-at-rest). It then waits for the instance id the ingest service sealed (`conditions.instance_identity`) and refuses to start with another one; see [the instance id](../../README.md#the-instance-id). Under OpenMapX the service is a community service whose `container.environment` reaches the container verbatim, so `service.json` declares these as `configSchema` fields. The secrets are vault secrets the operator sets once in the admin services panel (`openconditions-contributions-api`, Credentials); OpenMapX mounts each as a file and sets `_FILE`. On the shared OpenMapX database `DATABASE_URL` connects as this service's own role, for example `postgresql://openconditions_contributions:@openmapx-postgis:5432/openmapx`. Never use the PostgreSQL superuser: create the role as OpenMapX's community extensions guide describes. The settings are set in the same panel, or as `SERVICE_OPENCONDITIONS_CONTRIBUTIONS_API_` in OpenMapX's `.env`. Settings kept in OpenMapX's `.env` are applied with `pnpm openmapx services start openconditions-contributions-api` (which resets every setting saved only in the admin form, so keep all of them in one place). Settings saved in the form are applied with **Save & Apply**. + +### Behind a relay -Each of the four secrets may instead be a file named by `_FILE`. The secrets key is a copy of the ingest service's, never a newly generated one: after the schema version the service waits for the ingest service's key check (`conditions.secrets_key_check`) and refuses to start when its key does not open it; see [Secrets encrypted at rest](../../README.md#secrets-encrypted-at-rest). Under OpenMapX the service is a community service whose `container.environment` reaches the container verbatim, so `service.json` declares these as `configSchema` fields. The secrets are vault secrets the operator sets once in the admin services panel (`openconditions-contributions-api`, Credentials); OpenMapX mounts each as a file and sets `_FILE`. On the shared OpenMapX database `DATABASE_URL` connects as this service's own role, for example `postgresql://openconditions_contributions:@openmapx-postgis:5432/openmapx`. Never use the PostgreSQL superuser: create the role as OpenMapX's community extensions guide describes. The settings are set in the same panel, or as `SERVICE_OPENCONDITIONS_CONTRIBUTIONS_API_` in OpenMapX's `.env`. Settings kept in OpenMapX's `.env` are applied with `pnpm openmapx services start openconditions-contributions-api` (which resets every setting saved only in the admin form, so keep all of them in one place). Settings saved in the form are applied with **Save & Apply**. +Enrollment (`POST /contrib/enroll`) is limited to 10 a minute per client address; it is the service's only limit keyed on an address, as the report and vote limits key on the reporter. OpenMapX's API relays its users' requests from its own container and never forwards a user's address, so behind it every user would share one address's limit. With `OPENCONDITIONS_RELAY_TOKEN` set, a request whose `Authorization` header is `Bearer ` (compared in constant time) is counted in one relay bucket of `OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE` instead, and the relay limits its own clients per address. A request without the token, or with another bearer, keeps its address's limit, also from the relay's address. Set the same token on both sides; a set token shorter than 32 characters stops the boot. An enrollment that carries another bearer while a relay token is set, the sign of a relay whose token differs, is logged as a warning at most every ten minutes, naming neither the token nor the address. The relay must not send its token to `GET /contrib/reporter/me`, which reads the reporter's grant from the same header. The service applies no migrations. The ingest service migrates the `conditions` schema; at start this service waits until `conditions.__drizzle_migrations` records the latest migration this build ships, or a later one, polling every two seconds. After `OPENCONDITIONS_SCHEMA_WAIT_TIMEOUT_MS` it stops and names the version it expected and what it found. Its role needs no DDL rights. After every migrate the ingest service grants `openconditions_contributions` the read of that table and exactly the privileges the service's queries use. Create the role before the ingest service first starts; one created later gets its grants when the ingest service restarts. See [database roles and grants](../../docs/database-migrations.md#database-roles-and-grants). diff --git a/services/contributions-api/service.json b/services/contributions-api/service.json index 1f194775a..a89919fba 100644 --- a/services/contributions-api/service.json +++ b/services/contributions-api/service.json @@ -2,12 +2,13 @@ "id": "openconditions-contributions-api", "name": "OpenConditions Contributions API", "version": "0.8.1", + "platform": "1.0", "description": "Crowd-report intake and evidence lifecycle for road conditions: verifies signed device reports, deduplicates and corroborates co-located phenomena, cross-validates against official feeds, and serves the operator reviewer surface — all over the shared PostGIS `conditions` schema. Peer confirmation never routes or trains reputation on its own; only official-feed cross-validation (and operator resolution) does.", "author": "OpenConditions", "license": "AGPL-3.0-or-later", "homepage": "https://openconditions.org", "documentation": "https://github.com/openconditions/openconditions", - "quality": "community-verified", + "quality": "community", "container": { "image": "ghcr.io/openconditions/contributions-api", "tag": "0.8.1", @@ -49,6 +50,13 @@ }, "configSchema": { "type": "object", + "required": [ + "DATABASE_URL", + "OPENCONDITIONS_SECRETS_KEY", + "OPENCONDITIONS_GRANT_SECRET", + "OPENCONDITIONS_REVIEWER_TOKEN", + "OPENCONDITIONS_INSTANCE_ID" + ], "properties": { "DATABASE_URL": { "type": "string", @@ -74,10 +82,23 @@ "description": "Required. Bearer token of the operator reviewer surface; generate with openssl rand -hex 32. The service refuses to start without it.", "x-openmapx-secret": true }, + "OPENCONDITIONS_RELAY_TOKEN": { + "type": "string", + "title": "Relay token", + "description": "Bearer token of the application that relays its users' crowd requests from one address, at least 32 characters; generate with openssl rand -hex 32. Must equal OpenMapX's own OPENCONDITIONS_RELAY_TOKEN, which OpenMapX's api service sends. A request bearing it is counted against the relay enroll limit instead of its address's (10 enrollments a minute), since the relay forwards no user's address. Unset, every request is limited by its address, and all OpenMapX users share one address's limit. A set but shorter token fails boot.", + "x-openmapx-secret": true + }, + "OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE": { + "type": "string", + "title": "Relay enroll limit (per minute)", + "description": "Enrollments a minute the requests bearing the relay token may make together, a whole number above 0. Empty: 600.", + "default": "", + "x-openmapx-secret": false + }, "OPENCONDITIONS_INSTANCE_ID": { "type": "string", "title": "Instance id", - "description": "This instance's stable id, the namespace of the crowd records it lands and its crowd's credit: lower-case letters, digits, dots and dashes, e.g. maps.example.org. Set it to the same value as the ingest service's. Empty: local.", + "description": "Required. This instance's stable id, the namespace of the crowd records it lands and its crowd's credit: a lower-case DNS name, e.g. maps.example.org. Copy the value of openconditions-ingest's Instance id. The service refuses to start without it, with a value that is not a DNS name, or with another id than the one the ingest service sealed in the database.", "default": "", "x-openmapx-secret": false }, diff --git a/services/contributions-api/src/__tests__/attester-issuer.integration.test.ts b/services/contributions-api/src/__tests__/attester-issuer.integration.test.ts index ac3306d05..20c7b37ba 100644 --- a/services/contributions-api/src/__tests__/attester-issuer.integration.test.ts +++ b/services/contributions-api/src/__tests__/attester-issuer.integration.test.ts @@ -1,7 +1,12 @@ import { createHash } from "node:crypto"; import { publicVerif, type Token } from "@cloudflare/privacypass-ts"; import { generateReporterKey, type ReporterKey } from "@openconditions/contrib-core"; -import { SecretsKey, sealSecretsKeyCheck, storedSecret } from "@openconditions/core/server"; +import { + SecretsKey, + sealInstanceId, + sealSecretsKeyCheck, + storedSecret, +} from "@openconditions/core/server"; import { createTestDatabase, dumpHolds, @@ -32,6 +37,7 @@ const NOW = "2026-07-12T08:00:00.000Z"; const GRANT_SECRET_VALUE = "attester-issuer-test-secret"; const GRANT_SECRET = new TextEncoder().encode(GRANT_SECRET_VALUE); const secrets = SecretsKey.parse(TEST_SECRETS_KEY); +const INSTANCE_ID = "contrib.example.org"; const noopLog = { info: () => {}, @@ -560,13 +566,38 @@ describe("build() fail-closed", () => { await expect( build({ sql, - env: { NODE_ENV: "production", OPENCONDITIONS_SECRETS_KEY: TEST_SECRETS_KEY }, + env: { + NODE_ENV: "production", + OPENCONDITIONS_SECRETS_KEY: TEST_SECRETS_KEY, + OPENCONDITIONS_INSTANCE_ID: INSTANCE_ID, + }, }), ).rejects.toThrow(/OPENCONDITIONS_GRANT_SECRET/); }, 30_000); + it("throws without an instance id, and with one sealed for another instance", async () => { + const env = { + OPENCONDITIONS_GRANT_SECRET: GRANT_SECRET_VALUE, + OPENCONDITIONS_SECRETS_KEY: TEST_SECRETS_KEY, + }; + await expect(build({ sql, env, logger: false })).rejects.toThrow( + /OPENCONDITIONS_INSTANCE_ID is required/, + ); + await sealInstanceId(sql, "other.example.org"); + try { + await expect( + build({ sql, env: { ...env, OPENCONDITIONS_INSTANCE_ID: INSTANCE_ID }, logger: false }), + ).rejects.toThrow(/differs from "other\.example\.org"/); + } finally { + await sql`TRUNCATE conditions.instance_identity`; + } + }, 30_000); + it("throws without a secrets key, or with one that is no key", async () => { - const env = { OPENCONDITIONS_GRANT_SECRET: GRANT_SECRET_VALUE }; + const env = { + OPENCONDITIONS_GRANT_SECRET: GRANT_SECRET_VALUE, + OPENCONDITIONS_INSTANCE_ID: INSTANCE_ID, + }; await expect(build({ sql, env, logger: false })).rejects.toThrow( /OPENCONDITIONS_SECRETS_KEY is required: set OPENCONDITIONS_SECRETS_KEY_FILE/, ); @@ -582,6 +613,7 @@ describe("build() fail-closed", () => { env: { OPENCONDITIONS_GRANT_SECRET: GRANT_SECRET_VALUE, OPENCONDITIONS_SECRETS_KEY: "f0".repeat(32), + OPENCONDITIONS_INSTANCE_ID: INSTANCE_ID, }, logger: false, }), @@ -589,7 +621,10 @@ describe("build() fail-closed", () => { }, 30_000); it("throws with a key other than the one the ingest service sealed the key check with", async () => { - const env = { OPENCONDITIONS_GRANT_SECRET: GRANT_SECRET_VALUE }; + const env = { + OPENCONDITIONS_GRANT_SECRET: GRANT_SECRET_VALUE, + OPENCONDITIONS_INSTANCE_ID: INSTANCE_ID, + }; await sealSecretsKeyCheck(sql, secrets); try { const matching = await build({ @@ -644,6 +679,7 @@ describe("HTTP surface + end-to-end flow with log separation", () => { env: { OPENCONDITIONS_GRANT_SECRET: GRANT_SECRET_VALUE, OPENCONDITIONS_SECRETS_KEY: TEST_SECRETS_KEY, + OPENCONDITIONS_INSTANCE_ID: INSTANCE_ID, }, logger: capture.logger, // Pin the clock so the SERVER-derived report epoch is a fixed UTC day. diff --git a/services/contributions-api/src/__tests__/crowd-fixtures.integration.ts b/services/contributions-api/src/__tests__/crowd-fixtures.integration.ts index cde90531b..6b4d4c6c6 100644 --- a/services/contributions-api/src/__tests__/crowd-fixtures.integration.ts +++ b/services/contributions-api/src/__tests__/crowd-fixtures.integration.ts @@ -31,6 +31,7 @@ export const CROWD_ATTRIBUTION: Attribution = { /** A crowd report of an obstruction (debris on the road) at a point. */ export function situationClaim(over: Partial = {}): SituationClaim { return { + v: 1, claimClass: "situation", kind: "incident", type: "obstruction", diff --git a/services/contributions-api/src/__tests__/erase.integration.test.ts b/services/contributions-api/src/__tests__/erase.integration.test.ts index ee7f78766..6a42451a0 100644 --- a/services/contributions-api/src/__tests__/erase.integration.test.ts +++ b/services/contributions-api/src/__tests__/erase.integration.test.ts @@ -110,7 +110,9 @@ describe("eraseRecord", () => { ]); expect(await history(id)).toEqual([1, 2]); - expect(await eraseRecord(sql, registry, { class: "situation", id }, ERASED_AT)).toBe("erased"); + expect(await eraseRecord(sql, registry, { class: "situation", id }, ERASED_AT, INSTANCE)).toBe( + "erased", + ); const row = await stored(id); expect(row.revision).toBe(3); @@ -158,7 +160,7 @@ describe("eraseRecord", () => { it("changes nothing when the record is already erased", async () => { const id = "oc:situation:de-autobahn-events:E1"; - expect(await eraseRecord(sql, registry, { class: "situation", id }, LATER)).toBe( + expect(await eraseRecord(sql, registry, { class: "situation", id }, LATER, INSTANCE)).toBe( "already erased", ); const row = await stored(id); @@ -183,7 +185,9 @@ describe("eraseRecord", () => { WHERE id = ${id}`; expect((await journal(id)).map((e) => e.operation)).toEqual(["create", "delete"]); - expect(await eraseRecord(sql, registry, { class: "situation", id }, ERASED_AT)).toBe("erased"); + expect(await eraseRecord(sql, registry, { class: "situation", id }, ERASED_AT, INSTANCE)).toBe( + "erased", + ); expect((await stored(id)).tombstone_reason).toBe(ERASURE_REASON); // The withdrawn delete stays (it carries no content); the erasure adds its own. expect(await journal(id)).toEqual([ @@ -194,7 +198,7 @@ describe("eraseRecord", () => { it("answers not found for a record this instance does not hold", async () => { const ref = { class: "situation" as const, id: "oc:situation:de-autobahn-events:missing" }; - expect(await eraseRecord(sql, registry, ref, ERASED_AT)).toBe("not found"); + expect(await eraseRecord(sql, registry, ref, ERASED_AT, INSTANCE)).toBe("not found"); const [facts] = await sql<{ n: number }[]>` SELECT count(*)::int AS n FROM conditions.federation_tombstone`; expect(facts!.n).toBe(2); @@ -205,7 +209,9 @@ describe("eraseRecord", () => { expect(await journal(id)).toHaveLength(1); await sql`DELETE FROM conditions.federation_subscription`; - expect(await eraseRecord(sql, registry, { class: "situation", id }, ERASED_AT)).toBe("erased"); + expect(await eraseRecord(sql, registry, { class: "situation", id }, ERASED_AT, INSTANCE)).toBe( + "erased", + ); // The outbox and backfill serve without a subscription, so the snapshot // must go and the retraction must reach peers that pulled it. @@ -216,7 +222,9 @@ describe("eraseRecord", () => { it("journals no tombstone of a record never journalled while nobody subscribes", async () => { const id = await seedFeedSituation(sql, "E5", {}, T0); - expect(await eraseRecord(sql, registry, { class: "situation", id }, ERASED_AT)).toBe("erased"); + expect(await eraseRecord(sql, registry, { class: "situation", id }, ERASED_AT, INSTANCE)).toBe( + "erased", + ); expect(await journal(id)).toEqual([]); }, 30_000); diff --git a/services/contributions-api/src/__tests__/inbox.integration.test.ts b/services/contributions-api/src/__tests__/inbox.integration.test.ts index d3c66bae1..46397e7d5 100644 --- a/services/contributions-api/src/__tests__/inbox.integration.test.ts +++ b/services/contributions-api/src/__tests__/inbox.integration.test.ts @@ -700,7 +700,13 @@ describe("a peer's retractions", () => { const own = peerSituation("e-5"); await ingestFederatedPage(sql, page(change(own, 1)), ctx()); expect( - await eraseRecord(sql, registry, { class: "situation", id: own["id"] as string }, NOW), + await eraseRecord( + sql, + registry, + { class: "situation", id: own["id"] as string }, + NOW, + INSTANCE, + ), ).toBe("erased"); const other = "other.example.com"; const theirs = sent(peerRecord(feedSituationDraft("e-5"), 4, undefined, other)); diff --git a/services/contributions-api/src/__tests__/observation-claims.integration.test.ts b/services/contributions-api/src/__tests__/observation-claims.integration.test.ts index 1fa6e8779..94560dbb7 100644 --- a/services/contributions-api/src/__tests__/observation-claims.integration.test.ts +++ b/services/contributions-api/src/__tests__/observation-claims.integration.test.ts @@ -235,6 +235,7 @@ async function post(report: SignedReport, grant: string) { const claimOf = (over: Rec) => ({ + v: 1, claimClass: "observation", property: "charging.evse_status", result: { type: "category", value: "out_of_order", vocabulary: "evse_status" }, @@ -439,6 +440,7 @@ describe("a charge point two sources describe", () => { payload: { subClaim: await signSubClaim( { + v: 1, subject: { class: "observation", id }, claimType: action, reportedAt: clock.now, @@ -604,6 +606,7 @@ describe("observation report submission quotas", () => { payload: { subClaim: await signSubClaim( { + v: 1, subject: { class: "observation", id }, claimType: action, reportedAt: clock.now, @@ -622,6 +625,7 @@ describe("observation report submission quotas", () => { payload: { subClaim: await signSubClaim( { + v: 1, subject: { class: "observation", id: ids[0]! }, claimType: "flag", reportedAt: clock.now, diff --git a/services/contributions-api/src/__tests__/relay-enroll.integration.test.ts b/services/contributions-api/src/__tests__/relay-enroll.integration.test.ts new file mode 100644 index 000000000..48b617806 --- /dev/null +++ b/services/contributions-api/src/__tests__/relay-enroll.integration.test.ts @@ -0,0 +1,122 @@ +import { + createTestDatabase, + TEST_SECRETS_KEY, + type TestDatabase, +} from "@openconditions/test-database"; +import type { FastifyInstance } from "fastify"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { ATTESTER_POLICY } from "../attester/policy.js"; +import { build } from "../server.js"; +import { INSTANCE } from "./crowd-fixtures.integration.js"; + +/** + * The enrollment limit behind a relay: the relay forwards every user's + * request from its own address, so a request bearing the relay token is + * counted in the relay's bucket, never in its address's. + */ + +const RELAY_TOKEN = "relay-token-for-the-enroll-limit-test"; +const BASE_ENV = { + OPENCONDITIONS_GRANT_SECRET: "relay-enroll-test-secret", + OPENCONDITIONS_SECRETS_KEY: TEST_SECRETS_KEY, + OPENCONDITIONS_INSTANCE_ID: INSTANCE, +}; + +let db: TestDatabase; +const apps: FastifyInstance[] = []; + +beforeAll(async () => { + db = await createTestDatabase(); +}, 120_000); + +afterAll(async () => { + for (const app of apps.splice(0)) await app.close(); + await db?.close(); +}, 30_000); + +async function app( + env: Record, + logger: Parameters[0]["logger"] = false, +): Promise { + const built = await build({ sql: db.sql, env: { ...BASE_ENV, ...env }, logger }); + apps.push(built); + return built; +} + +/** Status codes of `count` empty enrollments from one address: 400 when admitted, 429 when limited. */ +async function enrollments( + server: FastifyInstance, + count: number, + remoteAddress: string, + authorization?: string, +): Promise { + const codes: number[] = []; + for (let i = 0; i < count; i++) { + const res = await server.inject({ + method: "POST", + url: "/contrib/enroll", + payload: {}, + remoteAddress, + ...(authorization === undefined ? {} : { headers: { authorization } }), + }); + codes.push(res.statusCode); + } + return codes; +} + +describe("the enrollment limit behind a relay", () => { + const perAddress = ATTESTER_POLICY.enrollRateLimitPerMinute; + + it("keys on the address without a relay token configured, whatever the bearer", async () => { + const server = await app({}); + const codes = await enrollments(server, perAddress + 1, "10.0.0.1", `Bearer ${RELAY_TOKEN}`); + expect(codes.slice(0, perAddress).every((c) => c === 400)).toBe(true); + expect(codes[perAddress]).toBe(429); + }); + + it("counts requests bearing the relay token in the relay bucket, not the address's", async () => { + const server = await app({ + OPENCONDITIONS_RELAY_TOKEN: RELAY_TOKEN, + OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE: String(perAddress * 3), + }); + const relayed = await enrollments(server, perAddress * 3, "10.0.0.2", `Bearer ${RELAY_TOKEN}`); + expect(relayed.every((c) => c === 400)).toBe(true); + // The relay's own ceiling holds. + expect(await enrollments(server, 1, "10.0.0.2", `Bearer ${RELAY_TOKEN}`)).toEqual([429]); + // The address the relay sends from keeps its own, untouched bucket. + const direct = await enrollments(server, perAddress + 1, "10.0.0.2"); + expect(direct.slice(0, perAddress).every((c) => c === 400)).toBe(true); + expect(direct[perAddress]).toBe(429); + }); + + it("keys a wrong bearer on its address, and warns once without the token or address", async () => { + const lines: string[] = []; + const server = await app( + { OPENCONDITIONS_RELAY_TOKEN: RELAY_TOKEN }, + { level: "warn", stream: { write: (line: string) => lines.push(line) } }, + ); + const codes = await enrollments(server, perAddress + 1, "10.0.0.3", "Bearer not-the-token"); + expect(codes[perAddress]).toBe(429); + const warnings = lines.filter((line) => line.includes("other than OPENCONDITIONS_RELAY_TOKEN")); + expect(warnings).toHaveLength(1); + expect(warnings[0]).not.toContain("not-the-token"); + expect(warnings[0]).not.toContain(RELAY_TOKEN); + expect(warnings[0]).not.toContain("10.0.0.3"); + }); + + it("does not warn about requests without a bearer", async () => { + const lines: string[] = []; + const server = await app( + { OPENCONDITIONS_RELAY_TOKEN: RELAY_TOKEN }, + { level: "warn", stream: { write: (line: string) => lines.push(line) } }, + ); + await enrollments(server, 2, "10.0.0.4"); + expect(lines.filter((line) => line.includes("OPENCONDITIONS_RELAY_TOKEN"))).toEqual([]); + }); + + it("refuses to build with a set but short relay token", async () => { + await expect(app({ OPENCONDITIONS_RELAY_TOKEN: "short" })).rejects.toThrow( + /OPENCONDITIONS_RELAY_TOKEN must be at least 32 characters/, + ); + }); +}); diff --git a/services/contributions-api/src/__tests__/relay.test.ts b/services/contributions-api/src/__tests__/relay.test.ts new file mode 100644 index 000000000..1ab041aa8 --- /dev/null +++ b/services/contributions-api/src/__tests__/relay.test.ts @@ -0,0 +1,74 @@ +import type { FastifyRequest } from "fastify"; +import { describe, expect, it } from "vitest"; +import { + DEFAULT_RELAY_ENROLL_LIMIT_PER_MINUTE, + isRelayed, + relayStatus, + resolveRelayTrust, +} from "../relay.js"; + +const TOKEN = "r".repeat(32); + +const request = (authorization?: string) => + ({ headers: authorization === undefined ? {} : { authorization } }) as FastifyRequest; + +describe("resolveRelayTrust", () => { + it("trusts no relay without a token", () => { + expect(resolveRelayTrust({})).toBeUndefined(); + expect(resolveRelayTrust({ OPENCONDITIONS_RELAY_TOKEN: "" })).toBeUndefined(); + }); + + it("takes a token of at least 32 characters with the default enroll limit", () => { + expect(resolveRelayTrust({ OPENCONDITIONS_RELAY_TOKEN: TOKEN })).toEqual({ + token: TOKEN, + enrollLimitPerMinute: DEFAULT_RELAY_ENROLL_LIMIT_PER_MINUTE, + }); + expect(DEFAULT_RELAY_ENROLL_LIMIT_PER_MINUTE).toBe(600); + }); + + it("fails boot on a set but short token", () => { + expect(() => resolveRelayTrust({ OPENCONDITIONS_RELAY_TOKEN: "r".repeat(31) })).toThrow( + /OPENCONDITIONS_RELAY_TOKEN must be at least 32 characters/, + ); + }); + + it("reads the relay enroll limit, refusing anything but a whole number above 0", () => { + expect( + resolveRelayTrust({ + OPENCONDITIONS_RELAY_TOKEN: TOKEN, + OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE: "1200", + })?.enrollLimitPerMinute, + ).toBe(1200); + for (const bad of ["0", "-1", "1.5", "lots"]) { + expect(() => + resolveRelayTrust({ + OPENCONDITIONS_RELAY_TOKEN: TOKEN, + OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE: bad, + }), + ).toThrow(/OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE must be a whole number above 0/); + } + }); +}); + +describe("isRelayed", () => { + const relay = { token: TOKEN, enrollLimitPerMinute: 600 }; + + it("is true only for the configured token as the bearer", () => { + expect(isRelayed(request(`Bearer ${TOKEN}`), relay)).toBe(true); + expect(isRelayed(request(`Bearer ${TOKEN}x`), relay)).toBe(false); + expect(isRelayed(request(TOKEN), relay)).toBe(false); + expect(isRelayed(request(), relay)).toBe(false); + }); + + it("is never true without a configured relay", () => { + expect(isRelayed(request(`Bearer ${TOKEN}`), undefined)).toBe(false); + }); + + it("tells another bearer apart from none, only when a relay is configured", () => { + expect(relayStatus(request(`Bearer ${TOKEN}`), relay)).toBe("relayed"); + expect(relayStatus(request("Bearer not-the-token"), relay)).toBe("other-bearer"); + expect(relayStatus(request(), relay)).toBe("none"); + expect(relayStatus(request("Basic abc"), relay)).toBe("none"); + expect(relayStatus(request("Bearer not-the-token"), undefined)).toBe("none"); + }); +}); diff --git a/services/contributions-api/src/__tests__/reports.integration.test.ts b/services/contributions-api/src/__tests__/reports.integration.test.ts index 2e20a267d..d489cfc77 100644 --- a/services/contributions-api/src/__tests__/reports.integration.test.ts +++ b/services/contributions-api/src/__tests__/reports.integration.test.ts @@ -367,6 +367,18 @@ describe("POST /contrib/reports — rejections at the trust boundary", () => { expect(res.statusCode).toBe(400); }, 60_000); + it("rejects a claim without the claim version, or of another, with 400 CLAIM_VERSION_UNSUPPORTED", async () => { + const key = await generateReporterKey(); + const grant = await enroll(key); + const { v: _v, ...unversioned } = makeClaim({ nonce: "no-version-0000001" }); + for (const claim of [unversioned, makeClaim({ nonce: "no-version-0000001", v: 2 as 1 })]) { + const res = await postReport(await withClaim(key, claim), grant); + expect(res.statusCode).toBe(400); + expect(res.json()).toMatchObject({ code: "CLAIM_VERSION_UNSUPPORTED" }); + } + expect(await readSituation(crowdId(key, "no-version-0000001"))).toBeUndefined(); + }, 60_000); + it("rejects a claim the registry refuses with 400 at verification and writes nothing", async () => { const key = await generateReporterKey(); const grant = await enroll(key); @@ -437,6 +449,7 @@ describe("POST /contrib/reports — rejections at the trust boundary", () => { const report = await signReport( registry, { + v: 1, claimClass: "observation", subject: { featureId: "oc:feature:de-bnetza:site-1", componentKey: "evse-1" }, property: "charging.evse_status", diff --git a/services/contributions-api/src/__tests__/reviewer.integration.test.ts b/services/contributions-api/src/__tests__/reviewer.integration.test.ts index baa665572..83f19b147 100644 --- a/services/contributions-api/src/__tests__/reviewer.integration.test.ts +++ b/services/contributions-api/src/__tests__/reviewer.integration.test.ts @@ -112,6 +112,7 @@ async function signSub( ): Promise { return signSubClaim( { + v: 1, subject: { class: "situation", id }, claimType, reportedAt: nowValue, diff --git a/services/contributions-api/src/__tests__/role-grants.integration.test.ts b/services/contributions-api/src/__tests__/role-grants.integration.test.ts index d17d0a8bf..ace12555f 100644 --- a/services/contributions-api/src/__tests__/role-grants.integration.test.ts +++ b/services/contributions-api/src/__tests__/role-grants.integration.test.ts @@ -339,6 +339,7 @@ async function vote( ) { const subClaim = await signSubClaim( { + v: 1, subject: { class: recordClass, id }, claimType: action, reportedAt: clock.now, @@ -490,6 +491,7 @@ describe("the contributions service as its own role", () => { const price = async (delta: number, reportedAt: string) => { const who = await reporter(); const claim = { + v: 1, claimClass: "observation", property: "fuel.price", subject: { featureId: station["id"], componentKey: "e5" }, @@ -548,6 +550,7 @@ describe("the contributions service as its own role", () => { featureId = site.feature["id"], ) => ({ + v: 1, claimClass: "observation", property: "charging.evse_status", result: { type: "category", value, vocabulary: "evse_status" }, diff --git a/services/contributions-api/src/__tests__/subclaims.integration.test.ts b/services/contributions-api/src/__tests__/subclaims.integration.test.ts index 34720e227..07adc854d 100644 --- a/services/contributions-api/src/__tests__/subclaims.integration.test.ts +++ b/services/contributions-api/src/__tests__/subclaims.integration.test.ts @@ -121,6 +121,7 @@ async function signSub( overrides: Partial = {}, ): Promise { const body: SubClaimBody = { + v: 1, subject: typeof subject === "string" ? situationRef(subject) : subject, claimType, reportedAt: nowValue, @@ -644,6 +645,20 @@ describe("POST /contrib/reports/:class/:id/:action — rejections at the trust b expect(await countSubClaims(id, key.keyId, "confirm")).toBe(1); }, 60_000); + it("rejects a sub-claim without the claim version, or of another, with 400 CLAIM_VERSION_UNSUPPORTED", async () => { + const { id } = await landSituation("reject-version-0001"); + const keyB = await generateReporterKey(); + const grantB = await enroll(keyB); + const signed = await signSub(keyB, id, "confirm"); + const { v: _v, ...unversioned } = signed; + for (const body of [unversioned, { ...signed, v: 2 }]) { + const res = await vote(id, "confirm", body as unknown as SignedSubClaim, grantB); + expect(res.statusCode).toBe(400); + expect(res.json()).toMatchObject({ code: "CLAIM_VERSION_UNSUPPORTED" }); + } + expect(await countSubClaims(id, keyB.keyId, "confirm")).toBe(0); + }, 60_000); + it("rejects a claimType that disagrees with the route action with 400", async () => { const { id } = await landSituation("reject-mismatch-001"); const keyB = await generateReporterKey(); diff --git a/services/contributions-api/src/attester/policy.ts b/services/contributions-api/src/attester/policy.ts index 805720481..0cef06568 100644 --- a/services/contributions-api/src/attester/policy.ts +++ b/services/contributions-api/src/attester/policy.ts @@ -152,7 +152,10 @@ export const ATTESTER_POLICY = { /** Cohort prior for a brand-new reporter's Beta reliability posterior. */ cohortPriorAlpha: 2, cohortPriorBeta: 2, - /** Enrollment endpoint rate limit, per client IP. */ + /** + * Enrollment endpoint rate limit, per client IP. Requests bearing the relay + * token share the relay's own limit instead (see relay.ts). + */ enrollRateLimitPerMinute: 10, /** Additive trustSignal weights (clamped to [0, 1] after summing). */ trust: { diff --git a/services/contributions-api/src/bearer.ts b/services/contributions-api/src/bearer.ts new file mode 100644 index 000000000..88dfb8bd9 --- /dev/null +++ b/services/contributions-api/src/bearer.ts @@ -0,0 +1,28 @@ +/** + * Bearer credentials of the operator surfaces (the reviewer token, the relay + * token): read from the Authorization header and compared in constant time. + */ +import { createHash, timingSafeEqual } from "node:crypto"; +import type { FastifyRequest } from "fastify"; + +/** + * Constant-time string equality. Both sides are hashed to a fixed 32-byte + * digest first, so neither the comparison nor a length check leaks how much + * of a guess was right. + */ +export function constantTimeEquals(a: string, b: string): boolean { + const ha = createHash("sha256").update(a, "utf8").digest(); + const hb = createHash("sha256").update(b, "utf8").digest(); + return timingSafeEqual(ha, hb); +} + +/** + * The `Bearer ` credential of the Authorization header; the empty + * string when the header is missing or not a bearer scheme, so a caller + * always feeds a string into the constant-time compare. + */ +export function bearerToken(req: FastifyRequest): string { + const header = req.headers["authorization"]; + if (typeof header !== "string" || !header.startsWith("Bearer ")) return ""; + return header.slice("Bearer ".length); +} diff --git a/services/contributions-api/src/federation/tombstone.ts b/services/contributions-api/src/federation/tombstone.ts index 4c941071f..886c4cb90 100644 --- a/services/contributions-api/src/federation/tombstone.ts +++ b/services/contributions-api/src/federation/tombstone.ts @@ -16,7 +16,7 @@ * peers and removes its earlier outbox entries, and its fact is recorded. */ -import { type RevisionedClass, resolveInstanceId } from "@openconditions/core/server"; +import type { RevisionedClass } from "@openconditions/core/server"; import type { Registry } from "@openconditions/model"; import { tombstoneRecords, updateCanonicalView } from "@openconditions/storage"; import type postgres from "postgres"; @@ -65,7 +65,7 @@ export async function eraseRecord( registry: Registry, ref: { class: RevisionedClass; id: string }, now: string, - instanceId: string = resolveInstanceId(), + instanceId: string, ): Promise<"erased" | "already erased" | "not found"> { return sql.begin(async (tx) => { await lockRecord(tx, ref.class, ref.id); diff --git a/services/contributions-api/src/main.ts b/services/contributions-api/src/main.ts index acf4e2114..5cb6d23ee 100644 --- a/services/contributions-api/src/main.ts +++ b/services/contributions-api/src/main.ts @@ -7,8 +7,10 @@ import { assertStoredCodesRegistered, + resolveInstanceId, schemaWaitTimeoutMs, secretsKeyFromEnv, + waitForInstanceId, waitForSchemaVersion, waitForSecretsKeyCheck, } from "@openconditions/core/server"; @@ -22,6 +24,7 @@ import { sweepCrossValidateObservations, sweepFederatedCrossValidate, } from "./evidence/crossValidateSweep.js"; +import { resolveRelayTrust } from "./relay.js"; import { build } from "./server.js"; const PORT = parseInt(process.env["PORT"] || "4200", 10); @@ -41,6 +44,8 @@ async function boot() { // database is read. const schemaWaitMs = schemaWaitTimeoutMs(process.env, "OPENCONDITIONS_SCHEMA_WAIT_TIMEOUT_MS"); const secretsKey = secretsKeyFromEnv(process.env); + const instanceId = resolveInstanceId(process.env); + resolveRelayTrust(process.env); // Requests and short sweeps only: a statement past 30 s or a lock wait past // 10 s fails rather than holding one of the five connections. Startup @@ -72,6 +77,13 @@ async function boot() { onWait: () => console.info("[contributions-api] waiting for the ingest service to seal the key check"), }); + // The crowd records it lands carry the instance id; one other than the id + // the ingest service sealed stops the boot. + await waitForInstanceId(sql, instanceId, { + timeoutMs: schemaWaitMs, + onWait: () => + console.info("[contributions-api] waiting for the ingest service to seal the instance id"), + }); const registry = productionRegistry(); await assertStoredCodesRegistered(sql, registry, { sourceFormats: false }); const app = await build({ sql, registry }); diff --git a/services/contributions-api/src/relay.ts b/services/contributions-api/src/relay.ts new file mode 100644 index 000000000..676870713 --- /dev/null +++ b/services/contributions-api/src/relay.ts @@ -0,0 +1,81 @@ +/** + * Relay trust. A fronting application (OpenMapX's API) forwards its users' + * requests from one address and never forwards theirs, so a limit keyed on + * the client address would put every user of that application in one bucket. + * A request carrying the configured relay token as its bearer is therefore + * counted in a relay bucket of its own, with a ceiling sized for the whole + * application; the relay limits its own clients per address. Without the + * token configured every request is keyed on its address as before. + */ +import { strictCredential } from "@openconditions/ingest-framework"; +import type { FastifyRequest } from "fastify"; +import { bearerToken, constantTimeEquals } from "./bearer.js"; + +export const RELAY_TOKEN_VARIABLE = "OPENCONDITIONS_RELAY_TOKEN"; +export const RELAY_ENROLL_LIMIT_VARIABLE = "OPENCONDITIONS_RELAY_ENROLL_LIMIT_PER_MINUTE"; + +/** The shortest relay token accepted, so a guessable one fails boot. */ +export const MIN_RELAY_TOKEN_LENGTH = 32; + +/** Enrollments a minute the relay bucket allows, unless configured. */ +export const DEFAULT_RELAY_ENROLL_LIMIT_PER_MINUTE = 600; + +/** The bucket key of relayed requests; an address can never take this form. */ +export const RELAY_BUCKET = "relay"; + +/** How often a bearer that is not the relay token is reported at most. */ +export const RELAY_WARNING_INTERVAL_MS = 10 * 60_000; + +export interface RelayTrust { + token: string; + enrollLimitPerMinute: number; +} + +/** + * Reads the relay settings: undefined without a token (no relay is trusted). + * A token shorter than {@link MIN_RELAY_TOKEN_LENGTH} characters, or a limit + * that is not a whole number above 0, throws, so a misconfiguration stops the + * boot. The token may instead be a file named by `OPENCONDITIONS_RELAY_TOKEN_FILE`. + */ +export function resolveRelayTrust(env: Record): RelayTrust | undefined { + const token = strictCredential(env, RELAY_TOKEN_VARIABLE); + const rawLimit = env[RELAY_ENROLL_LIMIT_VARIABLE]?.trim() ?? ""; + let enrollLimitPerMinute = DEFAULT_RELAY_ENROLL_LIMIT_PER_MINUTE; + if (rawLimit !== "") { + const value = Number(rawLimit); + if (!/^\d+$/.test(rawLimit) || !Number.isSafeInteger(value) || value <= 0) { + throw new Error( + `${RELAY_ENROLL_LIMIT_VARIABLE} must be a whole number above 0, got "${rawLimit}"`, + ); + } + enrollLimitPerMinute = value; + } + if (token === undefined) return undefined; + if (token.length < MIN_RELAY_TOKEN_LENGTH) { + throw new Error( + `${RELAY_TOKEN_VARIABLE} must be at least ${MIN_RELAY_TOKEN_LENGTH} characters; generate it with openssl rand -hex 32`, + ); + } + return { token, enrollLimitPerMinute }; +} + +/** + * How a request stands to the configured relay: `relayed` when its bearer is + * the relay token (compared in constant time), `other-bearer` when a relay is + * configured and the request carries another bearer (a relay whose token + * differs from this service's), `none` otherwise. + */ +export function relayStatus( + req: FastifyRequest, + relay: RelayTrust | undefined, +): "relayed" | "other-bearer" | "none" { + if (relay === undefined) return "none"; + const provided = bearerToken(req); + if (constantTimeEquals(provided, relay.token)) return "relayed"; + return provided === "" ? "none" : "other-bearer"; +} + +/** Whether the request's bearer is the relay token. */ +export function isRelayed(req: FastifyRequest, relay: RelayTrust | undefined): boolean { + return relayStatus(req, relay) === "relayed"; +} diff --git a/services/contributions-api/src/reviewer/auth.ts b/services/contributions-api/src/reviewer/auth.ts index 0c83f155a..b597b18ec 100644 --- a/services/contributions-api/src/reviewer/auth.ts +++ b/services/contributions-api/src/reviewer/auth.ts @@ -6,9 +6,9 @@ * 32-byte digest first, so neither the comparison nor a length check leaks how * much of a guess was right). */ -import { createHash, timingSafeEqual } from "node:crypto"; import { strictCredential } from "@openconditions/ingest-framework"; import type { FastifyReply, FastifyRequest, preHandlerHookHandler } from "fastify"; +import { bearerToken, constantTimeEquals } from "../bearer.js"; /** * Resolves the reviewer bearer token from the environment, mirroring the grant @@ -45,27 +45,6 @@ export function resolveReviewerToken( return ephemeral; } -/** Constant-time string equality; hashing first keeps it length-safe. */ -function constantTimeEquals(a: string, b: string): boolean { - const ha = createHash("sha256").update(a, "utf8").digest(); - const hb = createHash("sha256").update(b, "utf8").digest(); - return timingSafeEqual(ha, hb); -} - -/** - * Extract a `Bearer ` credential from the Authorization header. Returns - * the empty string when the header is missing or not a bearer scheme, so the - * caller always feeds a string into the constant-time compare (never short- - * circuiting on absence). - */ -function bearerToken(req: FastifyRequest): string { - const header = req.headers["authorization"]; - if (typeof header !== "string" || !header.startsWith("Bearer ")) { - return ""; - } - return header.slice("Bearer ".length); -} - /** * Build the `requireReviewer` preHandler bound to a resolved operator token. A * missing or wrong bearer → 401; a correct bearer passes through. Attached to diff --git a/services/contributions-api/src/server.ts b/services/contributions-api/src/server.ts index b24ad4286..03a4fc27b 100644 --- a/services/contributions-api/src/server.ts +++ b/services/contributions-api/src/server.ts @@ -11,6 +11,7 @@ */ import { + CLAIM_VERSION, checkGeometryPlausibility, type SignedReport, type SignedSubClaim, @@ -21,6 +22,7 @@ import { type GeoJsonGeometry, reliabilityLowerBound } from "@openconditions/cor import { resolveInstanceId, secretsKeyFromEnv, + verifyInstanceId, verifySecretsKeyCheck, } from "@openconditions/core/server"; import { resolveCrowdCredit } from "@openconditions/ingest-framework"; @@ -54,6 +56,12 @@ import { TokenVerifier } from "./issuer/verify.js"; import { ClaimRefusedError, GeometryInvalidError, landReport } from "./landing/land.js"; import { ConflictingReportError, landObservationReport } from "./landing/observation.js"; import { isPoliceCategoryEnabled, isPoliceClaim } from "./policy/police.js"; +import { + RELAY_BUCKET, + RELAY_WARNING_INTERVAL_MS, + relayStatus, + resolveRelayTrust, +} from "./relay.js"; import { makeRequireReviewer, resolveReviewerToken } from "./reviewer/auth.js"; import { blockKey, listBlocked, unblockKey } from "./reviewer/blocklist.js"; import { acceptSituation, rejectSituation } from "./reviewer/decide.js"; @@ -158,7 +166,22 @@ interface SubClaimBody { const SUB_CLAIM_ACTIONS = new Set(["confirm", "negate", "flag"]); -/** Minimal per-IP token bucket for the enrollment endpoint. */ +/** The stable code of a signed claim whose `v` is missing or not one this service verifies. */ +export const CLAIM_VERSION_UNSUPPORTED = "CLAIM_VERSION_UNSUPPORTED"; + +/** Whether a signed body names the claim version this service verifies; checked before the signature. */ +function hasClaimVersion(body: unknown): boolean { + return body !== null && typeof body === "object" && (body as { v?: unknown }).v === CLAIM_VERSION; +} + +function unsupportedClaimVersion(label: string): { error: string; code: string } { + return { + error: `${label}.v must be ${CLAIM_VERSION}, the signed claim version this service verifies`, + code: CLAIM_VERSION_UNSUPPORTED, + }; +} + +/** Minimal keyed token bucket for the enrollment endpoint: per address, or the relay's. */ class EnrollLimiter { private readonly buckets = new Map(); @@ -167,16 +190,16 @@ class EnrollLimiter { private readonly windowMs: number, ) {} - allow(ip: string, nowMs: number): boolean { + allow(key: string, nowMs: number): boolean { if (this.buckets.size > 10_000) { - for (const [key, stale] of this.buckets) { - if (nowMs - stale.lastRefill > this.windowMs * 2) this.buckets.delete(key); + for (const [stored, stale] of this.buckets) { + if (nowMs - stale.lastRefill > this.windowMs * 2) this.buckets.delete(stored); } } - let bucket = this.buckets.get(ip); + let bucket = this.buckets.get(key); if (bucket === undefined) { bucket = { tokens: this.max, lastRefill: nowMs }; - this.buckets.set(ip, bucket); + this.buckets.set(key, bucket); } const elapsed = nowMs - bucket.lastRefill; bucket.tokens = Math.min(this.max, bucket.tokens + (elapsed / this.windowMs) * this.max); @@ -223,29 +246,56 @@ export async function build(options: BuildOptions): Promise { // production exactly like the grant secret. const reviewerToken = resolveReviewerToken(env, (msg) => attesterLog.warn(msg)); const requireReviewer = makeRequireReviewer(reviewerToken); - - // A key other than the one the ingest service sealed the check row with - // stops the boot; then every stored issuer key must open. An absent row is - // let through on purpose: the only callers are main.ts, which has already - // waited for the row with waitForSecretsKeyCheck, and tests that build the + // A set but short relay token, or a malformed relay limit, fails boot. + const relay = resolveRelayTrust(env); + + // A key other than the one the ingest service sealed the check row with, + // or an instance id other than the sealed one, stops the boot; then every + // stored issuer key must open. An absent row is let through on purpose: the + // only callers are main.ts, which has already waited for both rows with + // waitForSecretsKeyCheck and waitForInstanceId, and tests that build the // server on a database no ingest service started on. None of the package's // entry points exposes this function, so no other path reaches it without // that wait. await verifySecretsKeyCheck(sql, secretsKey); + await verifyInstanceId(sql, instanceId); await assertIssuerKeysOpen(sql, secretsKey); await ensureIssuerKeys(sql, secretsKey, now(), issuerName); const verifier = new TokenVerifier({ issuerName, log: originLog }); app.decorate("tokenVerifier", verifier); + // The only address-keyed limit: a relayed request is counted in the relay's + // bucket, since the relay forwards no client address (see relay.ts). const enrollLimiter = new EnrollLimiter(ATTESTER_POLICY.enrollRateLimitPerMinute, 60_000); + const relayEnrollLimiter = + relay === undefined ? undefined : new EnrollLimiter(relay.enrollLimitPerMinute, 60_000); + // A relay whose token differs from this service's is limited by its own + // address, for all its users together; say so, at most every ten minutes, + // naming neither token nor address. + let lastRelayMismatchWarning = Number.NEGATIVE_INFINITY; app.get("/status", async (_req, reply) => { return reply.send({ status: "ok", service: "openconditions-contributions-api" }); }); app.post<{ Body: EnrollBody }>("/contrib/enroll", async (req, reply) => { - if (!enrollLimiter.allow(req.ip, Date.now())) { + const nowMs = Date.now(); + const relayed = relayStatus(req, relay); + if ( + relayed === "other-bearer" && + nowMs - lastRelayMismatchWarning >= RELAY_WARNING_INTERVAL_MS + ) { + lastRelayMismatchWarning = nowMs; + attesterLog.warn( + "an enrollment carried a bearer token other than OPENCONDITIONS_RELAY_TOKEN and was limited by its address: check that the relay's OPENCONDITIONS_RELAY_TOKEN equals this service's", + ); + } + const allowed = + relayEnrollLimiter !== undefined && relayed === "relayed" + ? relayEnrollLimiter.allow(RELAY_BUCKET, nowMs) + : enrollLimiter.allow(req.ip, nowMs); + if (!allowed) { return reply.status(429).send({ error: "Too many enrollment attempts" }); } const { pubJwk, proof } = req.body ?? {}; @@ -356,6 +406,9 @@ export async function build(options: BuildOptions): Promise { if (typeof report.keyId !== "string" || report.keyId.length === 0) { return reply.status(400).send({ error: "report.keyId is required" }); } + if (!hasClaimVersion(report.claim)) { + return reply.status(400).send(unsupportedClaimVersion("report.claim")); + } const nowIso = now(); // 1. The grant binds the key. It must be valid, unexpired, and issued FOR @@ -596,6 +649,9 @@ export async function build(options: BuildOptions): Promise { if (typeof subClaim.keyId !== "string" || subClaim.keyId.length === 0) { return reply.status(400).send({ error: "subClaim.keyId is required" }); } + if (!hasClaimVersion(subClaim)) { + return reply.status(400).send(unsupportedClaimVersion("subClaim")); + } const nowIso = now(); // 2. The grant binds the key: valid, unexpired, issued FOR this exact key. diff --git a/services/federation/service.json b/services/federation/service.json index d184b3e3a..e15b98542 100644 --- a/services/federation/service.json +++ b/services/federation/service.json @@ -2,12 +2,13 @@ "id": "openconditions-federation", "name": "OpenConditions Federation", "version": "0.8.1", + "platform": "1.0", "description": "Exchanges road and traffic conditions with pinned peer instances: serves this instance's actor document and signed outbox, takes peers' subscriptions and pushes to their inboxes, lands their records through the same admission as crowd reports, and keeps this instance subscribed to the peers it follows — all over the shared PostGIS `conditions` schema. Off until OPENCONDITIONS_FEDERATION_ENABLED is true; peers reach it only through a public route the operator provides (see docs/federation-onboarding.md).", "author": "OpenConditions", "license": "AGPL-3.0-or-later", "homepage": "https://openconditions.org", "documentation": "https://github.com/openconditions/openconditions/blob/main/docs/federation-onboarding.md", - "quality": "community-verified", + "quality": "community", "container": { "image": "ghcr.io/openconditions/federation", "tag": "0.8.1", @@ -59,6 +60,7 @@ }, "configSchema": { "type": "object", + "required": ["DATABASE_URL", "OPENCONDITIONS_INSTANCE_ID"], "properties": { "DATABASE_URL": { "type": "string", @@ -82,7 +84,7 @@ "OPENCONDITIONS_INSTANCE_ID": { "type": "string", "title": "Instance id", - "description": "This instance's stable id, the same value as the ingest and contributions services': the actor's instanceId must equal it, or the service refuses to start. Empty: local.", + "description": "Required. Copy the value of openconditions-ingest's Instance id, a lower-case DNS name such as maps.example.org; enabled, the actor's instanceId must equal it too. The service refuses to start without it, with a value that is not a DNS name, or with another id than the one the ingest service sealed in the database.", "default": "", "x-openmapx-secret": false }, diff --git a/services/federation/src/__tests__/admin.integration.test.ts b/services/federation/src/__tests__/admin.integration.test.ts index 589930154..33022e28c 100644 --- a/services/federation/src/__tests__/admin.integration.test.ts +++ b/services/federation/src/__tests__/admin.integration.test.ts @@ -1,10 +1,11 @@ +import { sealInstanceId } from "@openconditions/core/server"; import { isPeerBlocked } from "@openconditions/federation"; import { productionRegistry } from "@openconditions/model-registry"; import { syncSources } from "@openconditions/storage"; import { createTestDatabase, type TestDatabase } from "@openconditions/test-database"; import type postgres from "postgres"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { type AdminDeps, runAdminCommand } from "../ops/admin.js"; +import { type AdminDeps, runAdminCommand, sealedInstanceId } from "../ops/admin.js"; import { OWN_INSTANCE, ownSituation, situationId, storeSituation } from "./record-fixtures.js"; let db: TestDatabase; @@ -120,4 +121,21 @@ describe("the federation admin command", () => { expect(lines[0]).toMatch(/^usage: federation-admin/); } }); + + it("runs as the sealed instance id only", async () => { + const env = { OPENCONDITIONS_INSTANCE_ID: OWN_INSTANCE }; + await expect(sealedInstanceId(sql, env)).rejects.toThrow( + /conditions\.instance_identity is empty/, + ); + await sealInstanceId(sql, OWN_INSTANCE); + try { + await expect(sealedInstanceId(sql, env)).resolves.toBe(OWN_INSTANCE); + await expect( + sealedInstanceId(sql, { OPENCONDITIONS_INSTANCE_ID: "other.example.org" }), + ).rejects.toThrow(/differs from/); + await expect(sealedInstanceId(sql, {})).rejects.toThrow(/is required/); + } finally { + await sql`TRUNCATE conditions.instance_identity`; + } + }); }); diff --git a/services/federation/src/main.ts b/services/federation/src/main.ts index 26505ed2c..7b672cf46 100644 --- a/services/federation/src/main.ts +++ b/services/federation/src/main.ts @@ -7,7 +7,9 @@ import { assertStoredCodesRegistered, + resolveInstanceId, schemaWaitTimeoutMs, + waitForInstanceId, waitForSchemaVersion, waitForSecretsKeyCheck, } from "@openconditions/core/server"; @@ -93,6 +95,9 @@ async function boot() { // A malformed timeout, and with federation enabled a missing or malformed // secrets key or actor, fails boot before the database is read. const schemaWaitMs = schemaWaitTimeoutMs(process.env, "OPENCONDITIONS_SCHEMA_WAIT_TIMEOUT_MS"); + // Required whether or not federation is enabled: the journal and the + // archives it keeps hold this instance's record ids. + const instanceId = resolveInstanceId(process.env); const settings = resolveFederationSettings(process.env); if (settings.enabled) { // The actor says which protocol versions it speaks; peers negotiate on @@ -143,6 +148,12 @@ async function boot() { ), }); console.info("[federation-api] database schema is at this build's version"); + // An instance id other than the one the ingest service sealed stops the boot. + await waitForInstanceId(sql, instanceId, { + timeoutMs: schemaWaitMs, + onWait: () => + console.info("[federation-api] waiting for the ingest service to seal the instance id"), + }); await assertStoredCodesRegistered(sql, productionRegistry(), { sourceFormats: false }); // The journal must belong to the database's current history before anything diff --git a/services/federation/src/ops/admin.ts b/services/federation/src/ops/admin.ts index 49166a7ba..7bc40b136 100644 --- a/services/federation/src/ops/admin.ts +++ b/services/federation/src/ops/admin.ts @@ -18,7 +18,11 @@ */ import { pathToFileURL } from "node:url"; import { eraseRecord } from "@openconditions/contributions-api/federation/tombstone"; -import { type RevisionedClass, resolveInstanceId } from "@openconditions/core/server"; +import { + type RevisionedClass, + resolveInstanceId, + verifyInstanceId, +} from "@openconditions/core/server"; import { blockPeer, listBlockedPeers, unblockPeer } from "@openconditions/federation"; import { requireCredential } from "@openconditions/ingest-framework"; import type { Registry } from "@openconditions/model"; @@ -123,6 +127,21 @@ export async function runAdminCommand(args: readonly string[], deps: AdminDeps): return usage(); } +/** + * This instance's id from `env`, checked against the one the ingest service + * sealed, as every service checks it at start: the erasure rewrites records + * under it. Throws when no id is sealed yet or `env` names another. + */ +export async function sealedInstanceId(sql: postgres.Sql, env: NodeJS.ProcessEnv): Promise { + const instanceId = resolveInstanceId(env); + if ((await verifyInstanceId(sql, instanceId)) === "absent") { + throw new Error( + "conditions.instance_identity is empty: start the ingest service once, which seals the instance id, before using federation-admin", + ); + } + return instanceId; +} + async function main(): Promise { const sql = postgres(requireCredential(process.env, "DATABASE_URL"), { max: 1, @@ -133,7 +152,7 @@ async function main(): Promise { process.exitCode = await runAdminCommand(process.argv.slice(2), { sql, registry: productionRegistry(), - instanceId: resolveInstanceId(process.env), + instanceId: await sealedInstanceId(sql, process.env), operator: "federation-admin", now: () => new Date().toISOString(), out: (line) => process.stdout.write(`${line}\n`), diff --git a/services/federation/src/server.ts b/services/federation/src/server.ts index 5fa4e171d..703da2719 100644 --- a/services/federation/src/server.ts +++ b/services/federation/src/server.ts @@ -10,7 +10,7 @@ * Exported as build() so tests can fastify.inject; only main.ts listens. */ -import { verifySecretsKeyCheck } from "@openconditions/core/server"; +import { verifyInstanceId, verifySecretsKeyCheck } from "@openconditions/core/server"; import { ACTOR_WELL_KNOWN_PATH, anonymousRateKey, @@ -170,12 +170,15 @@ export async function build(options: BuildOptions): Promise { const peers = options.peers ?? (await PeerBook.load(sql, settings.peers)); // A key other than the one the ingest service sealed the check row with // stops the boot, and so does one that cannot open the stored instance - // keys, naming the key. An absent row is let through on purpose: the only - // callers are main.ts, which has already waited for the row with - // waitForSecretsKeyCheck, and tests that build the server on a database no - // ingest service started on. The package is private and declares no entry - // point, so no other path reaches it without that wait. + // keys, naming the key, or an actor of another instance than the sealed + // one. An absent row is let through on purpose: the only callers are + // main.ts, which has already waited for both rows with + // waitForSecretsKeyCheck and waitForInstanceId, and tests that build the + // server on a database no ingest service started on. The package is + // private and declares no entry point, so no other path reaches it without + // that wait. await verifySecretsKeyCheck(sql, secretsKey); + await verifyInstanceId(sql, actorConfig.instanceId); await assertInstanceKeysOpen(sql, secretsKey); await maintainInstanceKey(sql, secretsKey, now(), actorConfig.instanceId); diff --git a/services/ingest-heavy/service.json b/services/ingest-heavy/service.json index 524f5c443..dd9377ea4 100644 --- a/services/ingest-heavy/service.json +++ b/services/ingest-heavy/service.json @@ -2,12 +2,13 @@ "id": "openconditions-ingest-heavy", "name": "OpenConditions Ingest (heavy feeds)", "version": "0.8.1", + "platform": "1.0", "description": "Optional second OpenConditions ingest process, from the same image: it polls only the feeds its Feeds this process polls setting names (such as nl-ndw-flow and nl-ndw-charging), so their long parses and writes stop delaying the other feeds. It serves no API and runs no maintenance; openconditions-ingest does both and must leave these feeds to it (its Feeds left to another process setting).", "author": "OpenConditions", "license": "AGPL-3.0-or-later", "homepage": "https://openconditions.org", "documentation": "https://github.com/openconditions/openconditions/blob/main/services/ingest/README.md#a-second-ingest-process", - "quality": "community-verified", + "quality": "community", "container": { "image": "ghcr.io/openconditions/ingest", "tag": "0.8.1", @@ -147,7 +148,7 @@ "OPENCONDITIONS_EGRESS_ALLOWED_HOSTS": { "type": "string", "title": "Egress allowed private hosts", - "description": "Comma-separated hostnames the egress guard lets the service fetch although they resolve to private addresses, e.g. overpass for a self-hosted Overpass on the compose network. Empty: none.", + "description": "Comma-separated hostnames the egress guard lets the service fetch although they resolve to private addresses, e.g. openmapx-overpass for OpenMapX's Overpass service. Empty: none.", "default": "", "x-openmapx-secret": false }, @@ -250,7 +251,7 @@ "OPENCONDITIONS_INSTANCE_ID": { "type": "string", "title": "Instance id", - "description": "This instance's stable id, the namespace of every record it originates and its name to federation peers: lower-case letters, digits, dots and dashes, e.g. maps.example.org. Set it before federating, and to the same value as the contributions API's. Empty: local.", + "description": "Required. This instance's stable id, the namespace of every record it originates and its name to federation peers: a lower-case DNS name, e.g. maps.example.org. Set it before the first start; it can never change afterwards. The first ingest process to start seals it in the database, and every OpenConditions service of the instance (the heavy-feeds ingest, contributions API and federation) needs this same value. The service refuses to start without it, with a value that is not a DNS name, or with another id than the sealed one.", "default": "", "x-openmapx-secret": false }, @@ -1286,6 +1287,12 @@ "notes": "The legacy API key (consumer key and secret from api.eumetsat.int/api-key) does not work: licensed Copernicus data answers it with 403 'Copernicus license required'. A refresh token obtained elsewhere can be stored instead with `node dist/feed-auth.js import eumetsat`, which reads it from stdin (`docker compose exec -T ingest node dist/feed-auth.js import eumetsat < token-file`). If the service is stopped for 30 days the login lapses and must be repeated." } } - } + }, + "required": [ + "DATABASE_URL", + "OPENCONDITIONS_SECRETS_KEY", + "OPENCONDITIONS_INSTANCE_ID", + "OPENCONDITIONS_INGEST_FEEDS" + ] } } diff --git a/services/ingest/README.md b/services/ingest/README.md index dd8f1ff9d..8b0d571b9 100644 --- a/services/ingest/README.md +++ b/services/ingest/README.md @@ -14,8 +14,10 @@ road-surface sensor and their `weather.*` and `road.*` readings, maintenance tracking into anonymous `vehicle.position` readings, and border feeds into crossings with a lane group per queue and its `border.wait` reading, and writes them to the shared PostGIS `conditions` schema. Also serves the public, -rate-limited record API (described at `GET /openapi.json`) and the routing -outputs (`/segments/conditions.json`, Valhalla exclusions): +rate-limited record API and the routing outputs (`/segments/conditions.json`, +Valhalla exclusions), both described at `GET /openapi.json`. Paths never break: +a breaking change gets a new path, and the old one keeps its contract (see +[the public API](../../README.md#public-api)): - situations: `/situations` (JSON, `.geojson`, `.jsonld`), `/situations/{id}`, `/traff.xml`, `/datex2/situations.xml`, and the `/stream` of server-sent events; @@ -104,7 +106,11 @@ escapes it. `OPENCONDITIONS_OPERATOR_TOKEN`, run `pnpm openmapx services start api data-manager` on the OpenMapX host; the admin panel never recreates `api`. -- **Settings**: every other knob (`OPENCONDITIONS_INSTANCE_ID`, the crowd +- **Instance id**: `OPENCONDITIONS_INSTANCE_ID`, required, a lower-case DNS + name set once before the first start and never changed. The first ingest + process seals it in the database, and every other service needs the same + value; see [the instance id](../../README.md#the-instance-id). +- **Settings**: every other knob (the crowd credit `/sources` states, `OPENCONDITIONS_CROWD_LICENSE` and `OPENCONDITIONS_CROWD_SOURCE_URI`, which must equal the contributions API's, the rate diff --git a/services/ingest/openapi.json b/services/ingest/openapi.json index 68f1dbcab..e0a33c1dd 100644 --- a/services/ingest/openapi.json +++ b/services/ingest/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "OpenConditions", "version": "1.0.0", - "description": "Road conditions as model records. Collections are paginated by a keyset cursor: a walk is complete when `next` is null. TraFF is instead one complete bounded feed, or 413 when filters must be narrowed. A request without a bearer token reads in the public scope, which withholds restricted sources and licences that are not public; the operator token reads in the operator scope, which withholds nothing. The emitters always read in the public scope." + "description": "Road conditions as model records, and the routing, speed and status products built from them. Collections are paginated by a keyset cursor: a walk is complete when `next` is null. TraFF is instead one complete bounded feed, or 413 when filters must be narrowed. A request without a bearer token reads in the public scope, which withholds restricted sources and licences that are not public; the operator token reads in the operator scope, which withholds nothing. The emitters always read in the public scope. Paths never break: a path keeps its meaning, and its responses gain members but never lose or change one. A breaking change gets a new path, and the old path keeps its contract." }, "components": { "securitySchemes": { @@ -2618,6 +2618,266 @@ } } } + }, + "/feeds/status": { + "get": { + "operationId": "getFeedStatus", + "summary": "The feeds of the catalogue with their operational status: `{ schemaVersion, instanceId, collectedAt, graph, feeds }`. `graph` is the road graph's `{ generation, status, regions }` (`status` one of `ready`, `partial`, `missing`, `unknown`). Each feed has its id, name, domain, credential flags (`hasCredentials`, `missingEnv`), `selectionState`, cadence, freshness window and rights, its durable poll status, and `binding` metrics where its events bind to the road graph; discovered catalogue children and disabled feeds (`state: disabled`, `disabledReason`) are listed too.", + "parameters": [], + "security": [ + {}, + { + "operatorToken": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": {} + } + }, + "401": { + "description": "A bearer token other than the configured operator token (with none configured, a bearer token reads in public scope)", + "content": { + "application/json": {} + } + }, + "429": { + "description": "The client's rate limit is spent; `Retry-After` says when to retry", + "content": { + "application/json": {} + } + } + } + } + }, + "/valhalla/exclusions.json": { + "get": { + "operationId": "getValhallaExclusions", + "summary": "The bound closures in effect at `at` inside `bbox` as Valhalla exclusions, with the routing evidence they come from (`routing_evidence`, as `/segments/conditions.json` serves it). Only `exact` and `likely` bindings are read. `Cache-Control` lasts until the earliest freshness, expiry, validity end or transition of a served condition, at most 90 s. `X-Data-License` lists the licences of the rows served (`unknown` when there are none).", + "parameters": [ + { + "name": "bbox", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "west,south,east,north in WGS84 degrees, west not greater than east" + }, + "description": "west,south,east,north in WGS84 degrees, west not greater than east" + }, + { + "name": "at", + "in": "query", + "required": false, + "schema": { + "type": "string", + "description": "The ISO 8601 instant the effects are evaluated at; default now" + }, + "description": "The ISO 8601 instant the effects are evaluated at; default now" + } + ], + "security": [ + {}, + { + "operatorToken": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": {} + } + }, + "400": { + "description": "Invalid request" + }, + "401": { + "description": "A bearer token other than the configured operator token (with none configured, a bearer token reads in public scope)", + "content": { + "application/json": {} + } + }, + "429": { + "description": "The client's rate limit is spent; `Retry-After` says when to retry", + "content": { + "application/json": {} + } + } + } + } + }, + "/segments.geojson": { + "get": { + "operationId": "listSegmentsGeoJson", + "summary": "The directed road segments inside `bbox` (at most 20,000) as a GeoJSON FeatureCollection, each with its current fused speed, level of service and confidence where it has one, and per field the sources and contributors behind it. In the public scope a speed any restricted source contributed to is withheld: the segment keeps its geometry without speed properties. `X-Data-License` lists the licences of the rows served (`unknown` when there are none).", + "parameters": [ + { + "name": "bbox", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "west,south,east,north in WGS84 degrees, west not greater than east" + }, + "description": "west,south,east,north in WGS84 degrees, west not greater than east" + } + ], + "security": [ + {}, + { + "operatorToken": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/geo+json": {} + } + }, + "400": { + "description": "Invalid request" + }, + "401": { + "description": "A bearer token other than the configured operator token (with none configured, a bearer token reads in public scope)", + "content": { + "application/json": {} + } + }, + "429": { + "description": "The client's rate limit is spent; `Retry-After` says when to retry", + "content": { + "application/json": {} + } + } + } + } + }, + "/segments/speed.csv": { + "get": { + "operationId": "getSegmentSpeedCsv", + "summary": "One CSV row per directed segment that has a current fused speed: OSM way id, direction, current and free-flow speed and level of service, for routing. A segment without a speed is left out, and in the public scope so is a speed any restricted source contributed to. `X-Data-License` lists the licences of the rows served (`unknown` when there are none).", + "parameters": [], + "security": [ + {}, + { + "operatorToken": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/csv": {} + } + }, + "401": { + "description": "A bearer token other than the configured operator token (with none configured, a bearer token reads in public scope)", + "content": { + "application/json": {} + } + }, + "429": { + "description": "The client's rate limit is spent; `Retry-After` says when to retry", + "content": { + "application/json": {} + } + } + } + } + }, + "/segments/profiles.json": { + "get": { + "operationId": "getSegmentProfiles", + "summary": "The weekly speed profile of every directed segment that has one: `[{ way_id, dir, free_flow_kph, constrained_kph, hourly, lineage_version, native_sources, contributors, lineage_complete }]`. `hourly[dow * 24 + hour]` is the speed in km/h (null where no bucket exists), Sunday first, in the segment's region-local time. In the public scope a segment is left out whole when any of its buckets was built from a restricted source or from no recorded source. `X-Data-License` lists the licences of the rows served (`unknown` when there are none).", + "parameters": [], + "security": [ + {}, + { + "operatorToken": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": {} + } + }, + "401": { + "description": "A bearer token other than the configured operator token (with none configured, a bearer token reads in public scope)", + "content": { + "application/json": {} + } + }, + "429": { + "description": "The client's rate limit is spent; `Retry-After` says when to retry", + "content": { + "application/json": {} + } + } + } + } + }, + "/segments/conditions.json": { + "get": { + "operationId": "getSegmentConditions", + "summary": "The bound effects in effect at `at`, optionally inside `bbox`, one row per effect keyed by directed OSM way spans, with each row's routing evidence (source, licence, attribution, rights, freshness and validity). Only `exact` and `likely` bindings are read. `X-Data-License` lists the licences of the rows served (`unknown` when there are none).", + "parameters": [ + { + "name": "bbox", + "in": "query", + "required": false, + "schema": { + "type": "string", + "description": "west,south,east,north in WGS84 degrees, west not greater than east" + }, + "description": "west,south,east,north in WGS84 degrees, west not greater than east" + }, + { + "name": "at", + "in": "query", + "required": false, + "schema": { + "type": "string", + "description": "The ISO 8601 instant the effects are evaluated at; default now" + }, + "description": "The ISO 8601 instant the effects are evaluated at; default now" + } + ], + "security": [ + {}, + { + "operatorToken": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": {} + } + }, + "400": { + "description": "Invalid request" + }, + "401": { + "description": "A bearer token other than the configured operator token (with none configured, a bearer token reads in public scope)", + "content": { + "application/json": {} + } + }, + "429": { + "description": "The client's rate limit is spent; `Retry-After` says when to retry", + "content": { + "application/json": {} + } + } + } + } } } } diff --git a/services/ingest/service.json b/services/ingest/service.json index 9b37e070c..40d1c9f2e 100644 --- a/services/ingest/service.json +++ b/services/ingest/service.json @@ -2,12 +2,13 @@ "id": "openconditions-ingest", "name": "OpenConditions Ingest", "version": "0.8.1", + "platform": "1.0", "description": "Fetches open road-condition, fuel-price, parking and EV-charging feeds (NDW, Autobahn, Digitraffic, DriveBC, WZDx, Tankerkoenig, ParkAPI, BNetzA, OCPI and DATEX II charging publishers, and others), normalises them to the canonical model, and writes them to the shared PostGIS `conditions` schema for OpenMapX to read. Also serves public, rate-limited emitter feeds (GeoJSON, TraFF, DATEX II, GTFS-RT, JSON-LD, Valhalla exclusions, SSE).", "author": "OpenConditions", "license": "AGPL-3.0-or-later", "homepage": "https://openconditions.org", "documentation": "https://github.com/openconditions/openconditions", - "quality": "community-verified", + "quality": "community", "container": { "image": "ghcr.io/openconditions/ingest", "tag": "0.8.1", @@ -150,7 +151,7 @@ "OPENCONDITIONS_EGRESS_ALLOWED_HOSTS": { "type": "string", "title": "Egress allowed private hosts", - "description": "Comma-separated hostnames the egress guard lets the service fetch although they resolve to private addresses, e.g. overpass for a self-hosted Overpass on the compose network. Empty: none.", + "description": "Comma-separated hostnames the egress guard lets the service fetch although they resolve to private addresses, e.g. openmapx-overpass for OpenMapX's Overpass service. Empty: none.", "default": "", "x-openmapx-secret": false }, @@ -253,7 +254,7 @@ "OPENCONDITIONS_INSTANCE_ID": { "type": "string", "title": "Instance id", - "description": "This instance's stable id, the namespace of every record it originates and its name to federation peers: lower-case letters, digits, dots and dashes, e.g. maps.example.org. Set it before federating, and to the same value as the contributions API's. Empty: local.", + "description": "Required. This instance's stable id, the namespace of every record it originates and its name to federation peers: a lower-case DNS name, e.g. maps.example.org. Set it before the first start; it can never change afterwards. The first ingest process to start seals it in the database, and every OpenConditions service of the instance (the heavy-feeds ingest, contributions API and federation) needs this same value. The service refuses to start without it, with a value that is not a DNS name, or with another id than the sealed one.", "default": "", "x-openmapx-secret": false }, @@ -1289,7 +1290,12 @@ "notes": "The legacy API key (consumer key and secret from api.eumetsat.int/api-key) does not work: licensed Copernicus data answers it with 403 'Copernicus license required'. A refresh token obtained elsewhere can be stored instead with `node dist/feed-auth.js import eumetsat`, which reads it from stdin (`docker compose exec -T ingest node dist/feed-auth.js import eumetsat < token-file`). If the service is stopped for 30 days the login lapses and must be repeated." } } - } + }, + "required": [ + "DATABASE_URL", + "OPENCONDITIONS_SECRETS_KEY", + "OPENCONDITIONS_INSTANCE_ID" + ] }, "ui": { "category": "data" diff --git a/services/ingest/src/__tests__/api-openapi.test.ts b/services/ingest/src/__tests__/api-openapi.test.ts index 3f13498ad..56d936915 100644 --- a/services/ingest/src/__tests__/api-openapi.test.ts +++ b/services/ingest/src/__tests__/api-openapi.test.ts @@ -3,8 +3,11 @@ import { productionRegistry } from "@openconditions/model-registry"; import Fastify from "fastify"; import type postgres from "postgres"; import { describe, expect, it } from "vitest"; -import { API_ROUTES, openApiDocument } from "../api/openapi.js"; +import { API_ROUTES, openApiDocument, PUBLISH_ROUTES } from "../api/openapi.js"; import { registerApiRoutes } from "../api/routes.js"; +import { FeedStatusStore } from "../feed-status.js"; +import { registerPublishRoutes } from "../publish-routes.js"; +import { REPO_CATALOG } from "./helpers/catalog.js"; const CHECKED_IN = new URL("../../openapi.json", import.meta.url); @@ -46,6 +49,66 @@ describe("the OpenAPI document", () => { await app.close(); }); + it("documents exactly the routing, speed and status routes the service publishes", async () => { + const app = Fastify(); + const registered: string[] = []; + app.addHook("onRoute", (route) => { + if (route.method === "GET" || (Array.isArray(route.method) && route.method.includes("GET"))) { + registered.push(route.url); + } + }); + registerPublishRoutes(app, {} as postgres.Sql, new FeedStatusStore(), REPO_CATALOG); + await app.ready(); + expect([...new Set(registered)].sort()).toEqual(PUBLISH_ROUTES.map((r) => r.path).sort()); + expect(PUBLISH_ROUTES.map((r) => r.path).sort()).toEqual([ + "/feeds/status", + "/segments.geojson", + "/segments/conditions.json", + "/segments/profiles.json", + "/segments/speed.csv", + "/valhalla/exclusions.json", + ]); + await app.close(); + }); + + it("documents the publish routes' filters, media types and scope", () => { + const doc = openApiDocument(); + const op = (path: string) => + ( + doc.paths[path] as { + get: { + parameters: { name: string; required: boolean }[]; + security: Record[]; + responses: Record }>; + }; + } + ).get; + const required = (path: string) => + op(path) + .parameters.filter((p) => p.required) + .map((p) => p.name); + expect(required("/valhalla/exclusions.json")).toEqual(["bbox"]); + expect(op("/valhalla/exclusions.json").parameters.map((p) => p.name)).toEqual(["bbox", "at"]); + expect(required("/segments.geojson")).toEqual(["bbox"]); + expect(required("/segments/conditions.json")).toEqual([]); + expect(op("/segments/conditions.json").parameters.map((p) => p.name)).toEqual(["bbox", "at"]); + expect(op("/segments/speed.csv").parameters).toEqual([]); + expect(Object.keys(op("/segments/speed.csv").responses["200"]!.content!)).toEqual(["text/csv"]); + expect(Object.keys(op("/segments.geojson").responses["200"]!.content!)).toEqual([ + "application/geo+json", + ]); + for (const route of PUBLISH_ROUTES) { + expect(op(route.path).security, route.path).toEqual([{}, { operatorToken: [] }]); + expect(op(route.path).responses["429"], route.path).toBeDefined(); + } + }); + + it("states that paths never break and that a breaking change takes a new path", () => { + const { description } = openApiDocument().info; + expect(description).toMatch(/Paths never break/); + expect(description).toMatch(/A breaking change gets a new path/); + }); + it("describes the feature, offer and observation routes with their own filters", () => { const doc = openApiDocument(); const names = (path: string) => diff --git a/services/ingest/src/__tests__/grants.integration.test.ts b/services/ingest/src/__tests__/grants.integration.test.ts index 45e79f10a..cbb993a08 100644 --- a/services/ingest/src/__tests__/grants.integration.test.ts +++ b/services/ingest/src/__tests__/grants.integration.test.ts @@ -68,6 +68,7 @@ const CONTRIBUTIONS_GRANTS = [ "feature_canonical", "feature_component", "federation_subscription", + "instance_identity", "observation", "observation_rollup_progress", "offer", diff --git a/services/ingest/src/__tests__/helpers/facilities.ts b/services/ingest/src/__tests__/helpers/facilities.ts index 082306bc8..94a0b3d4a 100644 --- a/services/ingest/src/__tests__/helpers/facilities.ts +++ b/services/ingest/src/__tests__/helpers/facilities.ts @@ -203,6 +203,7 @@ export async function landEvseReport( facilitiesRegistry, { claim: { + v: 1, claimClass: "observation", subject: { featureId: opts.canonicalId, componentKey: opts.componentKey }, property: "charging.evse_status", @@ -242,6 +243,7 @@ export async function landPlacePriceReport( facilitiesRegistry, { claim: { + v: 1, claimClass: "observation", subject: { location: opts.location }, property: "fuel.price", diff --git a/services/ingest/src/api/openapi.ts b/services/ingest/src/api/openapi.ts index 8d773a136..33e47a1eb 100644 --- a/services/ingest/src/api/openapi.ts +++ b/services/ingest/src/api/openapi.ts @@ -229,6 +229,76 @@ export const API_ROUTES: readonly ApiRoute[] = [ }, ]; +const PublishBbox = z + .string() + .describe("west,south,east,north in WGS84 degrees, west not greater than east"); +const PublishAt = z + .string() + .describe("The ISO 8601 instant the effects are evaluated at; default now"); + +/** How a routing or speed product credits its sources, appended to its summary. */ +const LICENSE_HEADER = + " `X-Data-License` lists the licences of the rows served (`unknown` when there are none)."; + +/** + * The routing, speed and status products: every route here is registered by + * `registerPublishRoutes`. Each reads in the request's scope: the public + * scope drops a restricted source's rows and rows whose licence is not + * public, the operator scope serves every row. + */ +export const PUBLISH_ROUTES: readonly ApiRoute[] = [ + { + path: "/feeds/status", + operationId: "getFeedStatus", + summary: + "The feeds of the catalogue with their operational status: `{ schemaVersion, instanceId, collectedAt, graph, feeds }`. `graph` is the road graph's `{ generation, status, regions }` (`status` one of `ready`, `partial`, `missing`, `unknown`). Each feed has its id, name, domain, credential flags (`hasCredentials`, `missingEnv`), `selectionState`, cadence, freshness window and rights, its durable poll status, and `binding` metrics where its events bind to the road graph; discovered catalogue children and disabled feeds (`state: disabled`, `disabledReason`) are listed too.", + produces: ["application/json"], + }, + { + path: "/valhalla/exclusions.json", + operationId: "getValhallaExclusions", + summary: + "The bound closures in effect at `at` inside `bbox` as Valhalla exclusions, with the routing evidence they come from (`routing_evidence`, as `/segments/conditions.json` serves it). Only `exact` and `likely` bindings are read. `Cache-Control` lasts until the earliest freshness, expiry, validity end or transition of a served condition, at most 90 s." + + LICENSE_HEADER, + query: z.object({ bbox: PublishBbox, at: PublishAt.optional() }), + produces: ["application/json"], + }, + { + path: "/segments.geojson", + operationId: "listSegmentsGeoJson", + summary: + "The directed road segments inside `bbox` (at most 20,000) as a GeoJSON FeatureCollection, each with its current fused speed, level of service and confidence where it has one, and per field the sources and contributors behind it. In the public scope a speed any restricted source contributed to is withheld: the segment keeps its geometry without speed properties." + + LICENSE_HEADER, + query: z.object({ bbox: PublishBbox }), + produces: ["application/geo+json"], + }, + { + path: "/segments/speed.csv", + operationId: "getSegmentSpeedCsv", + summary: + "One CSV row per directed segment that has a current fused speed: OSM way id, direction, current and free-flow speed and level of service, for routing. A segment without a speed is left out, and in the public scope so is a speed any restricted source contributed to." + + LICENSE_HEADER, + produces: ["text/csv"], + }, + { + path: "/segments/profiles.json", + operationId: "getSegmentProfiles", + summary: + "The weekly speed profile of every directed segment that has one: `[{ way_id, dir, free_flow_kph, constrained_kph, hourly, lineage_version, native_sources, contributors, lineage_complete }]`. `hourly[dow * 24 + hour]` is the speed in km/h (null where no bucket exists), Sunday first, in the segment's region-local time. In the public scope a segment is left out whole when any of its buckets was built from a restricted source or from no recorded source." + + LICENSE_HEADER, + produces: ["application/json"], + }, + { + path: "/segments/conditions.json", + operationId: "getSegmentConditions", + summary: + "The bound effects in effect at `at`, optionally inside `bbox`, one row per effect keyed by directed OSM way spans, with each row's routing evidence (source, licence, attribution, rights, freshness and validity). Only `exact` and `likely` bindings are read." + + LICENSE_HEADER, + query: z.object({ bbox: PublishBbox.optional(), at: PublishAt.optional() }), + produces: ["application/json"], + }, +]; + /** A zod schema's request-side JSON Schema, without the meta keys a parameter does not take. */ function inputSchema(schema: z.ZodType): Record { const { $schema: _, ...rest } = z.toJSONSchema(schema, { io: "input", unrepresentable: "any" }); @@ -262,10 +332,13 @@ function parameters(route: ApiRoute): unknown[] { /** The record API's version: it changes with the API, not with each release of the service. */ export const API_VERSION = "1.0.0"; -/** The OpenAPI 3.1 document of the record API, generated from the routes' own request schemas. */ +/** + * The OpenAPI 3.1 document of the record API and the routing, speed and + * status products, generated from the record routes' own request schemas. + */ export function openApiDocument() { const paths: Record = {}; - for (const route of API_ROUTES) { + for (const route of [...API_ROUTES, ...PUBLISH_ROUTES]) { paths[route.path] = { get: { operationId: route.operationId, @@ -307,7 +380,7 @@ export function openApiDocument() { title: "OpenConditions", version: API_VERSION, description: - "Road conditions as model records. Collections are paginated by a keyset cursor: a walk is complete when `next` is null. TraFF is instead one complete bounded feed, or 413 when filters must be narrowed. A request without a bearer token reads in the public scope, which withholds restricted sources and licences that are not public; the operator token reads in the operator scope, which withholds nothing. The emitters always read in the public scope.", + "Road conditions as model records, and the routing, speed and status products built from them. Collections are paginated by a keyset cursor: a walk is complete when `next` is null. TraFF is instead one complete bounded feed, or 413 when filters must be narrowed. A request without a bearer token reads in the public scope, which withholds restricted sources and licences that are not public; the operator token reads in the operator scope, which withholds nothing. The emitters always read in the public scope. Paths never break: a path keeps its meaning, and its responses gain members but never lose or change one. A breaking change gets a new path, and the old path keeps its contract.", }, components: { securitySchemes: { diff --git a/services/ingest/src/index.ts b/services/ingest/src/index.ts index 582f6edb2..47a56143e 100644 --- a/services/ingest/src/index.ts +++ b/services/ingest/src/index.ts @@ -2,6 +2,7 @@ import { assertStoredCodesRegistered, resolveInstanceId, runMigrations, + sealInstanceId, } from "@openconditions/core/server"; import { resolveCrowdCredit } from "@openconditions/ingest-framework"; import { productionRegistry } from "@openconditions/model-registry"; @@ -47,12 +48,17 @@ async function boot() { // the check row, the stored grants and the stored private keys were sealed // with. const secretsKey = readIngestSecretsKey(process.env); - const crowd = resolveCrowdCredit(process.env, resolveInstanceId()); - console.info(`[ingest] instance id ${resolveInstanceId()}, role ${role}`); + // Required: a missing or malformed id fails boot before the database is + // touched, and, after the migrations, so does one other than the id the + // first ingest process sealed. + const instanceId = resolveInstanceId(); + const crowd = resolveCrowdCredit(process.env, instanceId); + console.info(`[ingest] instance id ${instanceId}, role ${role}`); console.info("[ingest] applying database migrations…"); await runMigrations(DATABASE_URL); console.info("[ingest] migrations applied"); await checkIngestSecrets(sql, secretsKey); + await sealInstanceId(sql, instanceId); const model = productionRegistry(); const catalog = await loadIngestCatalog(); const plan = planIngest(catalog); @@ -97,7 +103,7 @@ async function boot() { catalog, fetch: undiciFetch as unknown as typeof fetch, deadlineMs: onDemandDeadlineMsFromEnv(), - instanceId: resolveInstanceId(), + instanceId, inFlight, }, }); @@ -111,7 +117,7 @@ async function boot() { }); const stopRecordJobs = startRecordJobs(sql, maintenanceSql, { registry: model, - instanceId: resolveInstanceId(), + instanceId, feeds: catalog.feeds, primary, }); @@ -125,7 +131,7 @@ async function boot() { const fusedRefresh = startFusedRefresh((opts) => refreshOutdatedFusions(sql, { registry: model, - instanceId: resolveInstanceId(), + instanceId, now: () => new Date().toISOString(), ...opts, }), diff --git a/services/ingest/src/ops/smoke-road-restrictions.ts b/services/ingest/src/ops/smoke-road-restrictions.ts index b51274c1d..700a11669 100644 --- a/services/ingest/src/ops/smoke-road-restrictions.ts +++ b/services/ingest/src/ops/smoke-road-restrictions.ts @@ -17,7 +17,7 @@ import { isVehicleSpecific, situationEffects } from "@openconditions/model"; import { fetch as undiciFetch } from "undici"; import { domainOf, loadIngestCatalog } from "../domains.js"; import { parseMainPayloads } from "../pipeline/parse.js"; -import { stampAttribution, writeModel } from "../pipeline/publish.js"; +import { defaultWriteRegistry, stampAttribution } from "../pipeline/publish.js"; import { resolveOpenLr } from "../pipeline/resolve.js"; import { type RestrictionTally, tallyRestrictions } from "../pipeline/restriction-tally.js"; import { inspectSnapshotCompleteness } from "../pipeline/snapshot-inspection.js"; @@ -226,7 +226,8 @@ export async function runRestrictionSmoke( if (located.failed > 0) throw new Error("smoke location resolution failed"); const situations = located.resolved.map((draft) => stampAttribution(draft, feed)); - const { registry } = writeModel(); + // Validation only: the smoke writes nothing, so it needs no instance id. + const registry = defaultWriteRegistry(); for (const situation of situations) { const checked = registry.validateDraft(situation); if (!checked.ok) { diff --git a/services/ingest/src/pipeline/publish.ts b/services/ingest/src/pipeline/publish.ts index 5e1077c23..3323d0d0a 100644 --- a/services/ingest/src/pipeline/publish.ts +++ b/services/ingest/src/pipeline/publish.ts @@ -42,11 +42,19 @@ export interface WriteModel { let defaultRegistry: Registry | undefined; -/** The production registry and this instance's id, unless the caller supplies its own. */ -export function writeModel(over: Partial = {}): WriteModel { +/** The production registry polls seal their records against, built once. */ +export function defaultWriteRegistry(): Registry { defaultRegistry ??= productionRegistry(); + return defaultRegistry; +} + +/** + * The production registry and this instance's id, unless the caller supplies + * its own. The id is the one the service validated at boot. + */ +export function writeModel(over: Partial = {}): WriteModel { return { - registry: over.registry ?? defaultRegistry, + registry: over.registry ?? defaultWriteRegistry(), instanceId: over.instanceId ?? resolveInstanceId(), }; } diff --git a/services/ingest/src/publish-routes.ts b/services/ingest/src/publish-routes.ts index 770aa9192..e6a31caf1 100644 --- a/services/ingest/src/publish-routes.ts +++ b/services/ingest/src/publish-routes.ts @@ -293,6 +293,7 @@ export function registerFeedStatusRoute( sourceStatus?: SourceStatusReader, graphStatus?: FeedGraphStatusReader, ): void { + // The service validated it at boot, before any route was registered. const instanceId = resolveInstanceId(); app.get("/feeds/status", async () => { const collectedAt = new Date().toISOString(); diff --git a/vitest.config.ts b/vitest.config.ts index bdcdab4b0..88ff342f0 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,5 +1,10 @@ import { defineConfig } from "vitest/config"; +// Every service requires an instance id, and a poll writes as the one in its +// environment, as the service validated it at boot. Tests that check a +// missing or another id pass their own environment. +const env = { OPENCONDITIONS_INSTANCE_ID: "test.example.org" }; + // Explicit projects keep quick unit runs separate from disposable database suites. export default defineConfig({ test: { @@ -22,6 +27,7 @@ export default defineConfig({ test: { name: "unit", environment: "node", + env, globals: true, testTimeout: 15_000, include: ["packages/**/*.test.ts", "services/**/*.test.ts", "scripts/**/*.test.ts"], @@ -37,6 +43,7 @@ export default defineConfig({ test: { name: "integration", environment: "node", + env, globals: true, // After the unit project and two files at a time: the database // suites are the heavy ones.