diff --git a/.env.example b/.env.example index dda7eb784..ae9a49be7 100644 --- a/.env.example +++ b/.env.example @@ -44,6 +44,24 @@ export HTTP_API_PORT= export VALIDATE_UNSIGNED_DDO= export JWT_SECRET= export NODE_OWNER_INFO= +## Scoped auth tokens (see docs/env.md). Left COMMENTED OUT with their defaults on purpose: a bare +## `export KEY=` reaches the schema as '' — which coerces to 0 (silently overriding a numeric +## default) or fails the enum (TOKEN_REVOCATION_FALLBACK) / min(1) (MAX_TOKEN_LIFETIME) check and +## breaks config load. Uncomment a line only to OVERRIDE the default shown. +# Hard cap on auth-token lifetime, in SECONDS. Default 86400 (24h). No never-expiring tokens. +# export MAX_TOKEN_LIFETIME=86400 +# Unreachable-issuer policy for foreign tokens: closed | cache | open. Default cache. +# export TOKEN_REVOCATION_FALLBACK=cache +# Soft-fail grace (seconds), consulted only in cache mode. 0 = fail-closed. Default 300. +# export TOKEN_SOFTFAIL_GRACE=300 +# Seconds a positive revocation verdict suppresses re-dialing. 0 = every request. Default 60. +# export TOKEN_REVALIDATE_INTERVAL=60 +# Honor FOREIGN (other-issuer) tokens at all (lever B). Default false. +# export ALLOW_CROSS_NODE_TOKENS=false +# JSON array of issuer peerIds to federate with; REQUIRED non-empty if cross-node is on. Default []. +# export TRUSTED_TOKEN_ISSUERS=["16Uiu2HAm..."] +# OJ-03 status challenge-signing rate limit (req/min/caller, separate bucket). 0 = disabled. Default 10. +# export STATUS_CHALLENGE_RATE_LIMIT=10 export UNSAFE_URLS= export ALLOWED_PRIVATE_URL_RANGES= diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index a9f9c3b0a..c8d566048 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -9,10 +9,7 @@ on: pull_request: branches: - 'main' - - 'next-4' - - 'deps/node_v24' - - 'feature/user_input_subsidy' - - 'feature/subsidy_provider' + - 'rc_*' env: DOCKERHUB_IMAGE: ${{ 'oceanprotocol/ocean-node' }} diff --git a/config.json b/config.json index cdc54aa97..89e018f0e 100644 --- a/config.json +++ b/config.json @@ -1,162 +1,162 @@ { - "authorizedDecrypters": [], - "authorizedDecryptersList": null, - "allowedValidators": [], - "allowedValidatorsList": null, - "authorizedPublishers": [], - "authorizedPublishersList": null, - "keys": {}, - "hasIndexer": true, - "hasHttp": true, - "hasP2P": true, - "p2pConfig": { - "bootstrapTimeout": 20000, - "bootstrapTagName": "bootstrap", - "bootstrapTagValue": 50, - "bootstrapTTL": 0, - "enableIPV4": true, - "enableIPV6": true, - "ipV4BindAddress": "0.0.0.0", - "ipV4BindTcpPort": 9000, - "ipV4BindWsPort": 9001, - "ipV4BindWssPort": 9005, - "ipV6BindAddress": "::", - "ipV6BindTcpPort": 9002, - "ipV6BindWsPort": 9003, - "announceAddresses": [], - "dhtMaxInboundStreams": 500, - "dhtMaxOutboundStreams": 500, - "dhtFilter": "filterPrivate", - "mDNSInterval": 20000, - "connectionsMaxParallelDials": 50, - "connectionsDialTimeout": 15000, - "upnp": true, - "autoNat": true, - "enableCircuitRelayServer": false, - "enableCircuitRelayClient": false, - "circuitRelays": 0, - "announcePrivateIp": false, - "filterAnnouncedAddresses": [ - "127.0.0.0/8", - "10.0.0.0/8", - "172.16.0.0/12", - "192.168.0.0/16", - "100.64.0.0/10", - "169.254.0.0/16", - "192.0.0.0/24", - "192.0.2.0/24", - "198.51.100.0/24", - "203.0.113.0/24", - "224.0.0.0/4", - "240.0.0.0/4" - ], - "minConnections": 1, - "maxConnections": 300, - "autoDialPeerRetryThreshold": 7200000, - "autoDialConcurrency": 5, - "maxPeerAddrsToDial": 30, - "autoDialInterval": 5000, - "enableNetworkStats": false - }, - "httpPort": 8001, - "dbConfig": { - "url": "http://localhost:8108/?apiKey=xyz", - "username": "", - "password": "", - "dbType": "typesense" - }, - "supportedNetworks": { - "8996": { - "rpc": "http://127.0.0.1:8545", - "chainId": 8996, - "network": "development", - "chunkSize": 100 - } - }, - "feeStrategy": {}, - "c2dClusters": [], - "ipfsGateway": "https://ipfs.io/", - "arweaveGateway": "https://arweave.net/", - "accountPurgatoryUrl": null, - "assetPurgatoryUrl": null, - "allowedAdmins": [], - "allowedAdminsList": null, - "rateLimit": 30, - "maxConnections": 120, - "trustProxy": false, - "denyList": { - "peers": [], - "ips": [] - }, - "unsafeURLs": [], - "isBootstrap": false, - "claimDurationTimeout": 3600, - "validateUnsignedDDO": true, - "jwtSecret": "ocean-node-secret", - "enableBenchmark": false, - "serviceTemplatesPath": "databases/serviceTemplates/", - "dockerComputeEnvironments": [ - { - "socketPath": "/var/run/docker.sock", - "resources": [ - { - "id": "disk", - "total": 1 + "authorizedDecrypters": [], + "authorizedDecryptersList": null, + "allowedValidators": [], + "allowedValidatorsList": null, + "authorizedPublishers": [], + "authorizedPublishersList": null, + "keys": {}, + "hasIndexer": true, + "hasHttp": true, + "hasP2P": true, + "p2pConfig": { + "bootstrapTimeout": 20000, + "bootstrapTagName": "bootstrap", + "bootstrapTagValue": 50, + "bootstrapTTL": 0, + "enableIPV4": true, + "enableIPV6": true, + "ipV4BindAddress": "0.0.0.0", + "ipV4BindTcpPort": 9000, + "ipV4BindWsPort": 9001, + "ipV4BindWssPort": 9005, + "ipV6BindAddress": "::", + "ipV6BindTcpPort": 9002, + "ipV6BindWsPort": 9003, + "announceAddresses": [], + "dhtMaxInboundStreams": 500, + "dhtMaxOutboundStreams": 500, + "dhtFilter": "filterPrivate", + "mDNSInterval": 20000, + "connectionsMaxParallelDials": 50, + "connectionsDialTimeout": 15000, + "upnp": true, + "autoNat": true, + "enableCircuitRelayServer": false, + "enableCircuitRelayClient": false, + "circuitRelays": 0, + "announcePrivateIp": false, + "filterAnnouncedAddresses": [ + "127.0.0.0/8", + "10.0.0.0/8", + "172.16.0.0/12", + "192.168.0.0/16", + "100.64.0.0/10", + "169.254.0.0/16", + "192.0.0.0/24", + "192.0.2.0/24", + "198.51.100.0/24", + "203.0.113.0/24", + "224.0.0.0/4", + "240.0.0.0/4" + ], + "minConnections": 1, + "maxConnections": 300, + "autoDialPeerRetryThreshold": 7200000, + "autoDialConcurrency": 5, + "maxPeerAddrsToDial": 30, + "autoDialInterval": 5000, + "enableNetworkStats": false + }, + "httpPort": 8001, + "dbConfig": { + "url": "http://localhost:8108/?apiKey=xyz", + "username": "", + "password": "", + "dbType": "typesense" + }, + "supportedNetworks": { + "8996": { + "rpc": "http://127.0.0.1:8545", + "chainId": 8996, + "network": "development", + "chunkSize": 100 } - ], - "environments": [ + }, + "feeStrategy": {}, + "c2dClusters": [], + "ipfsGateway": "https://ipfs.io/", + "arweaveGateway": "https://arweave.net/", + "accountPurgatoryUrl": null, + "assetPurgatoryUrl": null, + "allowedAdmins": [], + "allowedAdminsList": null, + "rateLimit": 30, + "maxConnections": 200, + "trustProxy": false, + "denyList": { + "peers": [], + "ips": [] + }, + "unsafeURLs": [], + "isBootstrap": false, + "claimDurationTimeout": 3600, + "validateUnsignedDDO": true, + "jwtSecret": "ocean-node-secret", + "enableBenchmark": false, + "serviceTemplatesPath": "databases/serviceTemplates/", + "dockerComputeEnvironments": [ { - "storageExpiry": 604800, - "maxJobDuration": 3600, - "minJobDuration": 60, - "resources": [ - { - "id": "cpu" - }, - { - "id": "ram" - }, - { - "id": "disk", - "max": 1 - } - ], - "access": { - "addresses": [], - "accessLists": [] - }, - "fees": { - "8996": [ - { - "prices": [ - { - "id": "cpu", - "price": 1 - } - ] - } - ] - }, - "free": { - "maxJobDuration": 3600, - "maxJobs": 3, + "socketPath": "/var/run/docker.sock", "resources": [ - { - "id": "cpu", - "max": 1 - }, - { - "id": "ram", - "max": 1 - }, - { - "id": "disk", - "max": 1 - } + { + "id": "disk", + "total": 1 + } + ], + "environments": [ + { + "storageExpiry": 604800, + "maxJobDuration": 3600, + "minJobDuration": 60, + "resources": [ + { + "id": "cpu" + }, + { + "id": "ram" + }, + { + "id": "disk", + "max": 1 + } + ], + "access": { + "addresses": [], + "accessLists": [] + }, + "fees": { + "8996": [ + { + "prices": [ + { + "id": "cpu", + "price": 1 + } + ] + } + ] + }, + "free": { + "maxJobDuration": 3600, + "maxJobs": 3, + "resources": [ + { + "id": "cpu", + "max": 1 + }, + { + "id": "ram", + "max": 1 + }, + { + "id": "disk", + "max": 1 + } + ] + } + } ] - } } - ] - } - ] -} + ] +} \ No newline at end of file diff --git a/docs/API.md b/docs/API.md index 6a0a487c9..4daca5175 100644 --- a/docs/API.md +++ b/docs/API.md @@ -476,8 +476,8 @@ returns log by id. Admin only. Works only with `LOG_DB` and an available log dat | --------- | ------ | -------- | ----------------------------------------------------- | | logId | string | v | id of the log entry (read from the body) | | address | string | v | admin address (must be in `ALLOWED_ADMINS`) | -| signature | string | v | signed message (auth tokens are not accepted for admin commands) | -| nonce | string | v | nonce used for the signature | +| signature | string | (v) | signed message — required unless an auth token is sent (read-only admin; token goes in the `Authorization` header) | +| nonce | string | (v) | nonce used for the signature | #### Response @@ -501,7 +501,7 @@ returns log by id. Admin only. Works only with `LOG_DB` and an available log dat #### Description -returns list of logs, newest first. Admin only: send `address`, `signature` and `nonce` (auth tokens are not accepted for admin commands). The default window is the last 7 days. +returns list of logs, newest first. Admin only: send `address`, `signature` and `nonce`. `getLogs` is a **read-only admin command**, so it also accepts a scoped **auth token** (send it in `authorization`) scoped to `getLogs` — the `ALLOWED_ADMINS` gate still applies to the token's authenticated address. (Mutating admin commands still reject tokens.) The default window is the last 7 days. Source: the log database when `LOG_DB` is on and the log database is available; otherwise the rotating files in `logs/` (see [Logs.md](Logs.md)). Entries read from files have no `id` and only include levels at or above `LOG_FILES_LEVEL`. When nothing matches, the response is `200` with `[]`. An invalid `startTime`/`endTime` returns `400`. @@ -510,8 +510,9 @@ Source: the log database when `LOG_DB` is on and the log database is available; | name | type | required | description | | ---------- | ------ | -------- | ------------------------------------------------------------------------ | | address | string | v | admin address (must be in `ALLOWED_ADMINS`) | -| signature | string | v | signed message (auth tokens are not accepted for admin commands) | -| nonce | string | v | nonce used for the signature | +| signature | string | (v) | signed message — required unless an `authorization` token is sent | +| authorization | string | | scoped auth token (alternative to signature; read-only admin command) | +| nonce | string | (v) | nonce used for the signature | | startTime | string | | filter logs from date (ISO 8601 or epoch ms). Default: 7 days before end | | endTime | string | | filter logs to date (ISO 8601 or epoch ms). Default: now | | maxLogs | number | | logs per page. Default `100`, maximum `1000` | @@ -915,6 +916,73 @@ returns list of providers from which ddo can be obtained --- +## Auth Tokens + +### `HTTP` POST /api/services/auth/token + +### `P2P` command: createAuthToken + +#### Description + +Mints a JWT auth token, re-usable in place of a per-request signature. The token's authority is the +embedded **consumer signature** over the create-auth-token message (re-verified on every node), not +`JWT_SECRET`. + +A token can be **self-limited** along three axes, all folded into the signed message so no +intermediary can broaden them (a stolen "download-only token for node B" cannot be replayed as +compute on node C): + +- **audience** — list of node peerIds the token may be used at (omitted ⇒ any node). +- **scope** — list of protocol-command names the token may perform (omitted ⇒ any command). +- **validUntil** — absolute expiry (epoch ms). Capped by `MAX_TOKEN_LIFETIME`; the node **rejects** + (never clamps) an over-cap value. A request with no `validUntil` gets a server-set default expiry + of `createdAt + MAX_TOKEN_LIFETIME` (no never-expiring tokens). + +Providing any of `audience` / `scope` / `validUntil` makes it a **v2** token: `validUntil` is then +**required** and must be signed. Omit a field for "unrestricted"; an explicit `[]` is rejected. +`decryptDDO` and mutating-admin commands are **not** allowed in `scope` (and reject tokens entirely +at consumption — they require a fresh request signature). `fetchConfig` / `getLogs` (read-only admin) +are scopable. + +The signed message for a v2 token is: + +``` +address + nonce + "createAuthToken" + issuerPeerId + + "|v:2" + + "|aud:" + sort(dedup(audience)).join(",") + + "|cmd:" + sort(dedup(scope)).join(",") + + "|exp:" + validUntil +``` + +(omitted audience/scope ⇒ empty segment). A legacy request (none of the three fields) signs the +byte-identical `address + nonce + "createAuthToken" + issuerPeerId`. + +#### Parameters + +| name | type | required | description | +| ---------- | -------- | -------- | ------------------------------------------------------------------ | +| address | string | v | consumer address | +| signature | string | v | consumer signature over the message above | +| nonce | string | v | nonce | +| validUntil | number | (v2) | epoch ms; required whenever audience/scope is set | +| audience | string[] | | node peerIds the token may be used at; omit for unrestricted | +| scope | string[] | | protocol-command names the token may perform; omit for unrestricted | +| chainId | string | | chain id for smart-account (ERC-1271) signature validation | + +> **Smart-account (ERC-1271) tokens and cross-node use:** to be validated at a **different** node +> (federation), a smart-account token MUST carry a non-null `chainId` — the consuming node will not +> fan out an on-chain `isValidSignature` check across every network for a bearer token (DoS cap). An +> EOA token needs no `chainId`. A smart-account token minted without a `chainId` works only at its +> issuing node and must be reissued with one for cross-node use. + +#### Response + +```json +{ "token": "eyJ..." } +``` + +--- + ## Status ### `HTTP` POST /directCommand @@ -927,20 +995,57 @@ returns status of node #### Parameters -| name | type | required | description | -| ------- | ------ | -------- | ------------------------------------ | -| command | string | v | command name | -| node | string | | if not present it means current node | +| name | type | required | description | +| --------------- | ------ | -------- | --------------------------------------------------------------------------------- | +| command | string | v | command name | +| node | string | | if not present it means current node | +| clientChallenge | string | | OJ-03: when present, the node returns `signedChallenge` proving its peerId (below) | #### Request ```json { "command": "status", - "node": "PeerId" + "node": "PeerId", + "clientChallenge": "a-fresh-random-hex-string" +} +``` + +#### OJ-03 — authenticated issuer identity + +When a `clientChallenge` is supplied, the response includes `signedChallenge`: the node's **libp2p +identity-key** signature (0x-hex) over `utf8("ocean-node-status-challenge-v1:" + clientChallenge)`. +A client verifies it against the public key embedded in the node's `id` (peerId) to prove the +endpoint controls the key its peerId commits to — defeating a malicious endpoint that spoofs another +node's peerId (used by ocean.js before minting an auth token). The challenge-signing path has its own +rate limit (`STATUS_CHALLENGE_RATE_LIMIT`). This proves **identity**, not confidentiality — use TLS +(HTTP) / Noise (P2P) so a relay cannot skim the issued token. `signedChallenge` is computed per +request and is never cached. + +#### Auth-token policy (`authTokenPolicy`) + +The response also carries a static `authTokenPolicy` block so clients know what the node +requires/accepts before minting or presenting an auth token: + +```json +{ + "authTokenPolicy": { + "maxTokenLifetime": 86400, + "crossNode": "disabled", + "revocationFallback": "cache", + "softFailGrace": 300, + "challengeSupported": true + } } ``` +- `maxTokenLifetime` (seconds) — clients cap `validUntil` to this. +- `crossNode` — `disabled` (self-issued tokens only) or `allowlist` (foreign tokens honored only from + `trustedIssuers`, which is then also present). +- `revocationFallback` — `closed` | `cache` | `open` (behaviour when a token's issuer is unreachable); + `softFailGrace` (seconds) is present only in `cache` mode. +- `challengeSupported` — the node implements the `clientChallenge` / `signedChallenge` proof. + #### Response ``` @@ -1465,12 +1570,17 @@ The verified `consumerAddress` is the one forwarded to the PolicyServer; the cal returns current node configuration with sensitive data hidden (admin only) +`fetchConfig` is a **read-only admin command**, so in addition to a signature it also accepts a scoped +**auth token** in the `Authorization` header (scope it to `fetchConfig`). The `ALLOWED_ADMINS` gate +still applies to the token's authenticated address. (Mutating admin commands reject tokens.) + #### Parameters -| name | type | required | description | -| --------------- | ------ | -------- | -------------------------------------------- | -| expiryTimestamp | number | v | expiry timestamp for the request | -| signature | string | v | signed message to authenticate admin request | +| name | type | required | description | +| --------------- | ------ | -------- | -------------------------------------------------- | +| expiryTimestamp | number | v | expiry timestamp for the request | +| signature | string | (v) | signed message — required unless an auth token is sent | +| Authorization | header | | scoped auth token (alternative to signature) | #### Request diff --git a/docs/Ocean Node.postman_collection.json b/docs/Ocean Node.postman_collection.json index a4bbcfdfa..91a43ffb5 100644 --- a/docs/Ocean Node.postman_collection.json +++ b/docs/Ocean Node.postman_collection.json @@ -65,6 +65,21 @@ "key": "owner", "value": "0x0000000000000000000000000000000000000000", "type": "string" + }, + { + "key": "validUntil", + "value": "0", + "type": "string" + }, + { + "key": "issuerPeerId", + "value": "", + "type": "string" + }, + { + "key": "clientChallenge", + "value": "", + "type": "string" } ], "item": [ @@ -1725,7 +1740,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"address\": \"{{consumerAddress}}\",\n \"signature\": \"{{signature}}\",\n \"nonce\": \"{{nonce}}\",\n \"validUntil\": null,\n \"chainId\": {{chainId}}\n}" + "raw": "{\n \"address\": \"{{consumerAddress}}\",\n \"signature\": \"{{signature}}\",\n \"nonce\": \"{{nonce}}\",\n \"validUntil\": {{validUntil}},\n \"chainId\": {{chainId}},\n \"audience\": [\"{{issuerPeerId}}\"],\n \"scope\": [\"download\"]\n}" }, "url": { "raw": "{{baseUrl}}/api/services/auth/token", @@ -1739,7 +1754,7 @@ "token" ] }, - "description": "Create an auth token (returned token can be used as the Authorization header on authenticated routes)." + "description": "Create an auth token (returned token can be used as the Authorization header on authenticated routes).\n\nScoped tokens (v2): a token can be self-limited by `audience` (node peerIds it may be used at), `scope` (protocol-command names), and `validUntil` (absolute expiry, epoch ms). All three are folded into the consumer signature, so `{{signature}}` must be computed over the v2 message:\n\naddress + nonce + \"createAuthToken\" + issuerPeerId + \"|v:2\" + \"|aud:\" + sort(dedup(audience)).join(\",\") + \"|cmd:\" + sort(dedup(scope)).join(\",\") + \"|exp:\" + validUntil\n\n(omitted audience/scope => empty segment). Any of the three makes the token v2; validUntil is then required and capped by the node's MAX_TOKEN_LIFETIME (over-cap => 400, not clamped). Explicit [] is rejected -- omit the field for unrestricted. decryptDDO and mutating-admin commands are not allowed in scope.\n\nLegacy token: omit audience, scope and validUntil and sign the byte-identical legacy message address + nonce + \"createAuthToken\" + issuerPeerId; the node assigns a server default expiry. Check status.authTokenPolicy (max lifetime, cross-node federation) before minting." } }, { @@ -2300,7 +2315,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"command\": \"status\"\n}" + "raw": "{\n \"command\": \"status\",\n \"clientChallenge\": \"{{clientChallenge}}\"\n}" }, "url": { "raw": "{{baseUrl}}/directCommand", @@ -2311,7 +2326,7 @@ "directCommand" ] }, - "description": "Get node status. Use \"command\": \"detailedStatus\" for the extended report." + "description": "Get node status. Use \"command\": \"detailedStatus\" for the extended report.\n\nOJ-03: include a fresh random \"clientChallenge\" to get back \"signedChallenge\" -- the node's libp2p identity-key signature over utf8(\"ocean-node-status-challenge-v1:\" + clientChallenge). Verify it against the public key embedded in the node's \"id\" (peerId) to prove the endpoint controls its peerId before minting an auth token for it. Omit clientChallenge for today's response.\n\nThe response also carries a static \"authTokenPolicy\" { maxTokenLifetime, crossNode: \"disabled\"|\"allowlist\", trustedIssuers?, revocationFallback: \"closed\"|\"cache\"|\"open\", softFailGrace?, challengeSupported } describing what the node accepts before you mint/present an auth token." } }, { diff --git a/docs/env.md b/docs/env.md index 48d821ec8..216bc3ab2 100644 --- a/docs/env.md +++ b/docs/env.md @@ -35,8 +35,15 @@ Environmental variables are also tracked in `ENVIRONMENT_VARIABLES` within `src/ - `AUTHORIZED_PUBLISHERS`: Authorized list of publishers. If present, Node will only index assets published by the accounts in the list. Example: `"[\"0x967da4048cD07aB37855c090aAF366e4ce1b9F48\",\"0x388C818CA8B9251b393131C08a736A67ccB19297\"]"` - `AUTHORIZED_PUBLISHERS_LIST`: AccessList contract addresses (per chain). If present, Node will only index assets published by the accounts present on the given access lists. Example: `"{ \"8996\": [\"0x967da4048cD07aB37855c090aAF366e4ce1b9F48\",\"0x388C818CA8B9251b393131C08a736A67ccB19297\"] }"` - `VALIDATE_UNSIGNED_DDO`: If set to `false`, the node will not validate unsigned DDOs and will request a signed message with the publisher address, nonce and signature. Default is `true`. Example: `false` -- `JWT_SECRET`: Secret used to sign JWT tokens. Default is `ocean-node-secret`. Example: `"my-secret-jwt-token"` +- `JWT_SECRET`: Secret used to sign JWT tokens. Default is `ocean-node-secret`. **Note:** the shipped default is a published static string — operators should override it in production. The authority of an auth token is the embedded consumer signature (re-verified on every node), so `JWT_SECRET` is near-vestigial for cross-node validation, but you should still set a unique value. Example: `"my-secret-jwt-token"` - `NODE_OWNER_INFO`: Optional JSON object with the node owner's legal/contact info, returned as `ownerInfo` by the `status` command (HTTP and P2P). Free-form; omitted from status when unset or not a JSON object. Example: `'{"imprint":{"legalName":"Acme Ltd","email":"legal@acme.com","url":"https://acme.com","address":"1 Main St"},"termsAndConditions":{"url":"https://acme.com/terms"},"privacyPolicy":{"url":"https://acme.com/privacy"}}'` +- `MAX_TOKEN_LIFETIME`: Hard cap on auth-token lifetime, in **seconds**. Default `86400` (24h). The node **rejects** (does not clamp) a requested `validUntil` beyond `now + MAX_TOKEN_LIFETIME` (+60s skew). A token minted with no `validUntil` (legacy-style request) is given a server-set expiry of `createdAt + MAX_TOKEN_LIFETIME` — **there are no never-expiring tokens**. This cap also binds **foreign** tokens on the consuming side: a revocation verdict returned by another issuer (and every cached / soft-fail / fail-open acceptance derived from it) is capped at `now + MAX_TOKEN_LIFETIME`, so a federated issuer configured with a longer lifetime can never extend a token's life on this node. Example: `43200` +- `TOKEN_REVOCATION_FALLBACK`: What the node does when a **foreign** token's issuer is unreachable for the revocation dial. One of `closed` | `cache` | `open`. Default `cache`. `closed` = reject always (revocation intact during outages); `cache` = accept only if a still-valid positive cache entry exists within `TOKEN_SOFTFAIL_GRACE`; `open` = accept any signature-valid, unexpired token (logged as a loud warning at startup — revoked tokens may be honored during an outage). All bounded by `MAX_TOKEN_LIFETIME`. Example: `closed` +- `TOKEN_SOFTFAIL_GRACE`: Seconds a cached positive verdict may be honored during an issuer outage, consulted **only** in `cache` mode. Default `300` (5 min). `0` makes `cache` behave like `closed`. Example: `60` +- `TOKEN_REVALIDATE_INTERVAL`: Seconds a positive revocation verdict suppresses re-dialing the issuer (success-path freshness, all fallback modes). Default `60`. `0` = re-dial on every request (freshest revocation, most dials). Example: `120` +- `ALLOW_CROSS_NODE_TOKENS`: Master switch (lever B) for honoring **foreign** (other-issuer) auth tokens. Default `false` — a stock node honors only tokens it issued itself. Self-issued tokens are always honored regardless of this setting. **Breaking** for anyone relying on open cross-node validation: set `true` **and** list issuers in `TRUSTED_TOKEN_ISSUERS`. Enabling it with an empty allowlist is a startup error (the node refuses to start). Example: `true` +- `TRUSTED_TOKEN_ISSUERS`: JSON array of issuer peerIds this node will honor foreign tokens from (the federation allowlist). Required non-empty when `ALLOW_CROSS_NODE_TOKENS=true`. Malformed entries are logged and dropped. One-directional (Y trusting X does not require X to trust Y). Example: `["16Uiu2HAm...","16Uiu2HAm..."]` +- `STATUS_CHALLENGE_RATE_LIMIT`: OJ-03. Dedicated per-caller rate limit (requests/minute, separate bucket) for the status **challenge-signing** path — only enforced when a `clientChallenge` is present. Default `10`. `0` disables it. Example: `20` - `PERSISTENT_STORAGE`: Persistent storage config. See [persistent storage](persistentStorage.md). - `UNSAFE_URLS`: JSON array of regular expressions. A caller-supplied URL (the `url` / `ftp` file objects used by fileInfo, download, encrypt, compute inputs and compute-output upload) matching any of them is rejected. The entries are **added to** the built-in defaults (the cloud metadata endpoints such as `169.254.169.254` and `metadata.google.internal`, and `127.0.0.1`), so setting this variable never drops the defaults. Example: `["^https?://internal\\.example\\.com"]` - `ALLOWED_PRIVATE_URL_RANGES`: By default the node refuses to contact URLs whose host is, or resolves to, a private, loopback, link-local, CGNAT, multicast or otherwise reserved address, IPv4 or IPv6. This applies to caller-supplied file URLs (`url`, `ftp` and `s3` file objects used by fileInfo / download / compute), on-chain `decryptorURL` fields (the Indexer posts decrypt requests to them), and all outbound requests made during Docker manifest checks for compute images (the initial manifest fetch, the token-endpoint fetch from the `www-authenticate` realm, and the authenticated re-fetch). The check fires at connect time on every connection and every redirect, closing DNS-rebinding and redirect-chain vectors. **Localhost Docker registries** (`localhost:5000/myalgo`, etc.) are also blocked by this default and require listing `127.0.0.1/8` and/or `::1/128` here. This JSON array of CIDRs or single IPs lists exceptions, for example an object store, a private decryptor node, or a localhost registry on the node's LAN. Default is `[]`. Example: `["10.0.5.20/32","192.168.10.0/24","127.0.0.1/8"]` diff --git a/src/@types/KeyManager.ts b/src/@types/KeyManager.ts index 516d358fa..3712bd4ac 100644 --- a/src/@types/KeyManager.ts +++ b/src/@types/KeyManager.ts @@ -93,6 +93,17 @@ export interface IKeyProvider { * @returns Signature */ signMessage(message: string): Promise + /** + * OJ-03: sign raw bytes with the libp2p IDENTITY key (the key the peerId commits to), using + * libp2p's native `.sign()` (secp256k1: SHA-256 + DER), verifiable in ocean.js with + * `@libp2p/crypto` `publicKey.verify`. This is NOT the EVM signer: under every KMS provider the + * EVM key lives in KMS while the libp2p identity key is software-resident, so this MUST be + * implemented as a software-local op over `getLibp2pPrivateKey().sign(...)` (free, synchronous, + * no paid remote Sign call). Used only to answer the status identity challenge. + * @param data - raw bytes to sign (already domain-separated by the caller) + * @returns the libp2p signature bytes + */ + signWithIdentityKey(data: Uint8Array): Promise | Uint8Array /** * Cleanup resources if needed (e.g., close connections) */ diff --git a/src/@types/OceanNode.ts b/src/@types/OceanNode.ts index e34515483..53777e7c6 100644 --- a/src/@types/OceanNode.ts +++ b/src/@types/OceanNode.ts @@ -218,6 +218,21 @@ export interface OceanNodeConfig { isBootstrap?: boolean validateUnsignedDDO?: boolean jwtSecret?: string + // Scoped auth tokens (plan §8). Seconds unless noted. + // Hard cap on token lifetime (default 86400 = 24h); the node rejects an over-cap validUntil + // and defaults legacy (omitted-validUntil) tokens to createdAt + this. + maxTokenLifetime?: number + // Unreachable-issuer policy for the foreign-token revocation dial (plan §7/§8.1). + tokenRevocationFallback?: 'closed' | 'cache' | 'open' + // Soft-fail grace window (seconds); only consulted in `cache` mode. 0 = fail-closed. + tokenSoftFailGrace?: number + // How long a positive revocation verdict suppresses re-dialing (seconds). 0 = always re-dial. + tokenRevalidateInterval?: number + // Operator federation — lever B (plan §17.1). + allowCrossNodeTokens?: boolean + trustedTokenIssuers?: string[] + // OJ-03 (plan §14.4): per-caller rate limit (req/min) for the status challenge-signing path. + statusChallengeRateLimit?: number httpCertPath?: string httpKeyPath?: string enableBenchmark?: boolean @@ -285,6 +300,24 @@ export interface OceanNodeP2PStatus { dhtMode?: string } +// OJ-03 + scoped-token policy exposed in `status` (plan §17.2). This is static config, safe to +// include in the cached status object. `signedChallenge` (below) is per-request and never cached. +export interface AuthTokenPolicyStatus { + // from MAX_TOKEN_LIFETIME — clients cap validUntil to this (seconds) + maxTokenLifetime: number + // 'disabled' when foreign tokens are rejected; 'allowlist' when honored only from trustedIssuers. + // ('open' is intentionally unreachable: enabling with an empty allowlist fails at startup.) + crossNode: 'disabled' | 'allowlist' + // present only when crossNode === 'allowlist' + trustedIssuers?: string[] + // behaviour when a token's issuer is unreachable (plan §8.1) + revocationFallback: 'closed' | 'cache' | 'open' + // seconds; present only when revocationFallback === 'cache' + softFailGrace?: number + // OJ-03: node supports the status clientChallenge / signedChallenge proof-of-possession + challengeSupported: true +} + export interface OceanNodeStatus { id: string publicKey: string @@ -293,6 +326,12 @@ export interface OceanNodeStatus { version: string http: boolean p2p: boolean + // OJ-03 (plan §14): present only when the request included a `clientChallenge`; the node's + // libp2p-identity-key signature over utf8(STATUS_CHALLENGE_DOMAIN + clientChallenge). Computed + // per request and NEVER stored in the cached status object. + signedChallenge?: string + // Node auth-token policy (plan §17.2). Static config, part of the cached status object. + authTokenPolicy?: AuthTokenPolicyStatus // whether a Policy Server is configured (POLICY_SERVER_URL); clients use it to decide // whether to run the credential (SSI) flow before download/compute isPSConfigured: boolean diff --git a/src/@types/commands.ts b/src/@types/commands.ts index b4045b92a..bee0fb550 100644 --- a/src/@types/commands.ts +++ b/src/@types/commands.ts @@ -109,6 +109,10 @@ export interface ValidateDDOCommand extends Command { export interface StatusCommand extends Command { detailed?: boolean + // OJ-03 (plan §14.1): optional client-chosen random challenge. When present, the node answers + // with `signedChallenge` (its libp2p-identity-key signature over the domain-separated digest), + // proving it controls the key the peerId commits to. Backward compatible: omitted ⇒ no change. + clientChallenge?: string } export interface DetailedStatusCommand extends StatusCommand {} export interface EchoCommand extends Command {} diff --git a/src/components/Auth/index.ts b/src/components/Auth/index.ts index bc69e9fa2..971a8d6ee 100644 --- a/src/components/Auth/index.ts +++ b/src/components/Auth/index.ts @@ -9,11 +9,16 @@ import { OceanNode } from '../../OceanNode.js' import { OceanP2P } from '../P2P/index.js' import { CommonValidation } from '../../utils/validators.js' import { OceanNodeConfig } from '../../@types/OceanNode.js' -import { PROTOCOL_COMMANDS } from '../../utils/constants.js' +import { PROTOCOL_COMMANDS, TOKEN_INELIGIBLE_COMMANDS } from '../../utils/constants.js' +import { AUTH_TOKEN_VERSION } from '../../utils/crypt.js' import { peerIdFromString } from '@libp2p/peer-id' import { Readable } from 'node:stream' +import { CORE_LOGGER } from '../../utils/logging/common.js' const MAX_VERDICT_BYTES = 4096 +// Bound the positive-verdict cache so a flood of distinct foreign tokens cannot grow it without +// limit. Simple cap with lazy expired-eviction + oldest-first eviction on insert (plan §7.1). +const MAX_VERDICT_CACHE_ENTRIES = 10_000 /** * Reads a bounded validation verdict off a P2P response body. @@ -56,11 +61,40 @@ export interface AuthValidation { dataNftAddress?: string } +// Decoded v2 scoped-token claims (plan §4). Omitted fields stay absent. +interface DecodedTokenClaims { + v?: number + address?: string + nonce?: string + signature?: string + createdAt?: number + issuerPeerId?: string + chainId?: string | null + audience?: string[] + scope?: string[] + validUntil?: number +} + +// A positive foreign-dial verdict (plan §7.1). Only successful verdicts are cached. +interface CachedVerdict { + validUntil: number + lastConfirmedAt: number +} + export class Auth { private authTokenDatabase: AuthTokenDatabase private jwtSecret: string private config: OceanNodeConfig private getP2PNode: () => OceanP2P | undefined + // Scoped-token policy knobs (plan §8). + private maxTokenLifetimeMs: number + private revocationFallback: 'closed' | 'cache' | 'open' + private softFailGraceMs: number + private revalidateIntervalMs: number + private allowCrossNodeTokens: boolean + private trustedTokenIssuers: Set + // In-memory, per-process positive-verdict cache for foreign tokens (plan §7.1). + private verdictCache: Map = new Map() public constructor( authTokenDatabase: AuthTokenDatabase, @@ -71,12 +105,31 @@ export class Auth { this.jwtSecret = config.jwtSecret this.config = config this.getP2PNode = getP2PNode + this.maxTokenLifetimeMs = (config.maxTokenLifetime ?? 86400) * 1000 + this.revocationFallback = config.tokenRevocationFallback ?? 'cache' + this.softFailGraceMs = (config.tokenSoftFailGrace ?? 300) * 1000 + this.revalidateIntervalMs = (config.tokenRevalidateInterval ?? 60) * 1000 + this.allowCrossNodeTokens = config.allowCrossNodeTokens ?? false + this.trustedTokenIssuers = new Set(config.trustedTokenIssuers ?? []) + // Loud startup warning when revocation is fail-OPEN (plan §8.1): revoked tokens may be honored + // during an issuer outage. 'closed'/'cache' are quiet. + if (this.revocationFallback === 'open') { + CORE_LOGGER.warn( + 'auth-token revocation is fail-OPEN (TOKEN_REVOCATION_FALLBACK=open): any signature-valid, ' + + 'unexpired token may be honored while its issuer is unreachable, including never-before-seen ' + + 'tokens. Revoked tokens may be accepted during an outage (bounded by MAX_TOKEN_LIFETIME).' + ) + } } public getJwtSecret(): string { return this.jwtSecret } + public getMaxTokenLifetimeMs(): number { + return this.maxTokenLifetimeMs + } + // eslint-disable-next-line require-await async getJWTToken( address: string, @@ -84,21 +137,39 @@ export class Auth { createdAt: number, signature?: string, issuerPeerId?: string, - chainId?: string | null + chainId?: string | null, + // v2 scoped-token claims (plan §4). Passing `version === 2` emits the v2 claim set; omitting + // it keeps today's EXACT legacy claim set (no `v`, no audience/scope/validUntil claims). + scopedClaims?: { + version?: number + audience?: string[] + scope?: string[] + validUntil?: number + } ): Promise { - const jwtToken = jwt.sign( - { - address, - nonce, - createdAt, - signature, - issuerPeerId, - chainId - }, - this.getJwtSecret() - ) - - return jwtToken + // Claim ⇄ signed-field invariant (plan §3.3): every signed field is stored verbatim; the + // server never derives/defaults/clamps a signed field. Legacy tokens carry no `v`. + const payload: Record = { + address, + nonce, + createdAt, + signature, + issuerPeerId, + chainId + } + if (scopedClaims?.version === AUTH_TOKEN_VERSION) { + payload.v = AUTH_TOKEN_VERSION + // audience/scope present only when a non-empty list was signed (omitted ⇒ unrestricted). + if (scopedClaims.audience && scopedClaims.audience.length) { + payload.audience = scopedClaims.audience + } + if (scopedClaims.scope && scopedClaims.scope.length) { + payload.scope = scopedClaims.scope + } + // validUntil is required (signed) in v2. + payload.validUntil = scopedClaims.validUntil + } + return jwt.sign(payload, this.getJwtSecret()) } async insertToken( @@ -118,6 +189,8 @@ export class Auth { } async invalidateToken(jwtToken: string): Promise { + // Evict any cached positive verdict so a revoked token stops being soft-fail-eligible. + this.verdictCache.delete(jwtToken) await this.authTokenDatabase.invalidateToken(jwtToken) } @@ -133,19 +206,53 @@ export class Auth { return await this.authTokenDatabase.validateToken(token) } + // Lazily drop expired entries and keep the cache bounded (plan §7.1). + private pruneVerdictCache(now: number): void { + for (const [key, entry] of this.verdictCache) { + if (now >= entry.validUntil) { + this.verdictCache.delete(key) + } + } + while (this.verdictCache.size >= MAX_VERDICT_CACHE_ENTRIES) { + const oldest = this.verdictCache.keys().next().value + if (oldest === undefined) break + this.verdictCache.delete(oldest) + } + } + + private buildAuthTokenFromCache( + token: string, + address: string, + createdAt?: number, + validUntilMs?: number + ): AuthToken { + const createdNum = Number(createdAt) + return { + token, + address, + created: Number.isFinite(createdNum) ? new Date(createdNum) : new Date(), + validUntil: new Date(validUntilMs), + isValid: true + } + } + private async validateRemoteToken(token: string): Promise { const decoded = jwt.decode(token) if (!decoded || typeof decoded !== 'object') { return null } - const { address, nonce, signature, createdAt, issuerPeerId, chainId } = decoded as { - address?: string - nonce?: string - signature?: string - createdAt?: number - issuerPeerId?: string - chainId?: string | null - } + const { + address, + nonce, + signature, + createdAt, + issuerPeerId, + chainId, + v, + audience, + scope, + validUntil: signedValidUntil + } = decoded as DecodedTokenClaims if ( typeof address !== 'string' || typeof nonce !== 'string' || @@ -154,6 +261,67 @@ export class Auth { ) { return null } + + // A version we do not implement must be rejected outright — never interpret an unknown format + // (plan §3.4). Legacy tokens (no `v`) are allowed. + if (v != null && v !== AUTH_TOKEN_VERSION) { + CORE_LOGGER.debug(`Rejecting foreign token: unsupported version ${v}`) + return null + } + + // Strict v2 semantics: a token that CLAIMS v2 MUST carry a signed numeric `validUntil`. Without + // this, a v2 claim with no `validUntil` would make the signature check fall back to the legacy + // message builder (isV2CreateAuthToken ⇒ false), letting a legacy token's signature be replayed + // as a malformed "v2" token. Not a privilege escalation (legacy is already unrestricted) but it + // breaks the claim⇄signed invariant and is loose under the `open` revocation fallback — reject. + if ( + v === AUTH_TOKEN_VERSION && + (typeof signedValidUntil !== 'number' || !Number.isFinite(signedValidUntil)) + ) { + CORE_LOGGER.debug('Rejecting foreign token: v2 token missing/invalid validUntil') + return null + } + + // ── Lever B federation gate (plan §17.1) — FIRST, before any crypto or dial. Only foreign + // tokens reach here (self-issued tokens are served from the local DB path). Also the ON-03(3) + // DoS mitigation: non-federated / junk tokens are rejected on a cheap check. + if (!this.allowCrossNodeTokens) { + CORE_LOGGER.debug( + 'Rejecting foreign token: cross-node tokens disabled on this node' + ) + return null + } + if (!this.trustedTokenIssuers.has(issuerPeerId)) { + CORE_LOGGER.debug( + `Rejecting foreign token: cross-node issuer not federated (${issuerPeerId})` + ) + return null + } + + // ── Cheap parse + self / no-P2P guards BEFORE the expensive ECDSA/dial (plan §6.3). + try { + peerIdFromString(issuerPeerId) + } catch { + return null + } + const p2p = this.getP2PNode() + if (!p2p || p2p.isTargetPeerSelf(issuerPeerId)) { + return null + } + + // ── Audience BEFORE dial (plan §18.4): an out-of-audience foreign token must never cost a + // dial (or an ECDSA verify). §6.1 still enforces audience on the local path. + if (v === AUTH_TOKEN_VERSION && Array.isArray(audience) && audience.length) { + const selfPeerId = OceanNode.getInstance().getKeyManager().getPeerIdString() + if (!audience.includes(selfPeerId)) { + CORE_LOGGER.debug('Rejecting foreign token: node not in audience') + return null + } + } + + // ── Consumer signature, rebuilt from the SAME claims (plan §6.2). For v2 the rebuilt message + // includes version/audience/scope/exp, so a tampered claim fails verification. ERC-1271 + // fan-out is capped on the token path when chainId is null (plan §18.4). const signatureValid = await verifyConsumerSignature( address, nonce, @@ -161,66 +329,159 @@ export class Auth { issuerPeerId, PROTOCOL_COMMANDS.CREATE_AUTH_TOKEN, this.config, - chainId + chainId, + v === AUTH_TOKEN_VERSION + ? { audience, scope, validUntil: signedValidUntil } + : undefined, + true // tokenPath: cap the ERC-1271 multi-network fan-out ) if (!signatureValid) { return null } - try { - peerIdFromString(issuerPeerId) - } catch { + + // Defense in depth: a v2 token's signed validUntil also bounds it here. + if ( + v === AUTH_TOKEN_VERSION && + typeof signedValidUntil === 'number' && + signedValidUntil <= Date.now() + ) { return null } - const p2p = this.getP2PNode() - if (!p2p || p2p.isTargetPeerSelf(issuerPeerId)) { - return null + + const now = Date.now() + + // ── Fast path: a recent positive confirmation suppresses the dial (plan §7.2). + const cached = this.verdictCache.get(token) + if ( + cached && + now < cached.validUntil && + now - cached.lastConfirmedAt < this.revalidateIntervalMs + ) { + return this.buildAuthTokenFromCache(token, address, createdAt, cached.validUntil) } + + // ── Revocation / liveness dial. let response + let unreachable = false try { response = await p2p.sendTo( issuerPeerId, JSON.stringify({ command: PROTOCOL_COMMANDS.VALIDATE_AUTH_TOKEN, token }) ) } catch { - return null + unreachable = true } - if (response?.status?.httpStatus !== 200 || !response.stream) { - return null + if (!unreachable && (response?.status?.httpStatus !== 200 || !response.stream)) { + unreachable = true } - let verdict: { valid?: boolean; validUntil?: number | string | null } - try { - verdict = JSON.parse(await readBounded(response.stream as Readable)) - } catch { - return null + + let verdict: { valid?: boolean; validUntil?: number | string | null } | null = null + if (!unreachable) { + try { + verdict = JSON.parse(await readBounded(response.stream as Readable)) + } catch { + unreachable = true + } } - if (!verdict.valid) { - return null + + // Re-read the clock AFTER the dial (plan review): `sendTo` above can take seconds, so the + // grace / expiry decisions and the cached `lastConfirmedAt` must reflect when the verdict + // actually settled, not when this function started. + const settled = Date.now() + + if (unreachable) { + // Outcome 3 — issuer unreachable: apply the configured fallback (plan §7.2). + switch (this.revocationFallback) { + case 'open': + // fail-open: trust the consumer signature. A v2 token carries a SIGNED `validUntil` → + // honor it (bounded by this node's MAX_TOKEN_LIFETIME). A legacy token has NO signed + // expiry and its `createdAt` is UNSIGNED, so we never fabricate an expiry from it — + // fall back to a still-valid cached confirmation, else reject. + CORE_LOGGER.debug('Issuer unreachable; applying fail-OPEN revocation policy') + if (typeof signedValidUntil === 'number') { + return this.buildAuthTokenFromClaims( + token, + address, + createdAt, + signedValidUntil + ) + } + if (cached && settled < cached.validUntil) { + return this.buildAuthTokenFromCache( + token, + address, + createdAt, + cached.validUntil + ) + } + return null + case 'cache': + if ( + cached && + settled < cached.validUntil && + settled - cached.lastConfirmedAt < this.softFailGraceMs + ) { + return this.buildAuthTokenFromCache( + token, + address, + createdAt, + cached.validUntil + ) + } + return null + case 'closed': + default: + return null + } } - if (verdict.validUntil == null) { + + // Outcome 2 — issuer reachable but says invalid / unparseable verdict: reject hard + evict. + if (!verdict || !verdict.valid || verdict.validUntil == null) { + this.verdictCache.delete(token) return null } const validUntilMs = Number(verdict.validUntil) - if (!Number.isFinite(validUntilMs) || validUntilMs <= Date.now()) { + if (!Number.isFinite(validUntilMs) || validUntilMs <= settled) { + this.verdictCache.delete(token) return null } - const createdNum = Number(createdAt) - return { - token, - address, - created: Number.isFinite(createdNum) ? new Date(createdNum) : new Date(), - validUntil: new Date(validUntilMs), - isValid: true - } + + // Outcome 1 — issuer confirms valid: cache + return, but NEVER let a foreign verdict outlive + // this node's MAX_TOKEN_LIFETIME (plan §7.3). A federated issuer with a larger cap must not + // extend a token's life here; the cap flows through the fast-path and `cache`/`open` fallbacks + // because they read `cached.validUntil`. + const cappedValidUntil = Math.min(validUntilMs, settled + this.maxTokenLifetimeMs) + this.pruneVerdictCache(settled) + this.verdictCache.set(token, { + validUntil: cappedValidUntil, + lastConfirmedAt: settled + }) + return this.buildAuthTokenFromCache(token, address, createdAt, cappedValidUntil) + } + + // `open`-mode only: build the AuthToken from a token's SIGNED `validUntil` (v2), WITHOUT touching + // the positive cache (an unconfirmed token must never later satisfy `cache` mode). Legacy tokens + // have NO signed expiry (and an unsigned `createdAt`), so the caller never passes one here — it + // requires a still-valid cached verdict instead. Always bounded by this node's MAX_TOKEN_LIFETIME + // (plan §7.3). + private buildAuthTokenFromClaims( + token: string, + address: string, + createdAt?: number, + signedValidUntil?: number + ): AuthToken | null { + const now = Date.now() + if (typeof signedValidUntil !== 'number' || signedValidUntil <= now) return null + const validUntilMs = Math.min(signedValidUntil, now + this.maxTokenLifetimeMs) + if (validUntilMs <= now) return null + return this.buildAuthTokenFromCache(token, address, createdAt, validUntilMs) } /** * Validates the authentication or token - * You need to provider either a token or an address, signature and message - * @param {string} token - The token to validate - * @param {string} address - The address to validate - * @param {string} signature - The signature to validate - * @param {string} message - The message to validate - * @returns The validation result + * You need to provide either a token or an address, signature and nonce. + * For v2 tokens this ALSO enforces audience / scope / expiry from the signed claims, and + * rejects a token presented for a token-ineligible command (plan §6.1, §18.1). */ async validateAuthenticationOrToken( authValidation: AuthValidation @@ -245,18 +506,33 @@ export class Auth { return { valid: false, error: nonceCheckResult.error } } - if (nonceCheckResult.valid) { - return { valid: true, error: '', address } - } + return { valid: true, error: '', address } } if (token) { + // HIGH (plan §18.1): a bearer token is NEVER accepted for a token-ineligible command, + // even an unrestricted one. These require a fresh single-use nonce-bound signature. + if (command && TOKEN_INELIGIBLE_COMMANDS.includes(command)) { + return { + valid: false, + error: 'this command requires a request signature, not an auth token' + } + } + const authToken = await this.validateToken(token) - if (authToken) { - return { valid: true, error: '', address: authToken.address } + if (!authToken) { + return { valid: false, error: 'Invalid token' } + } + + // Enforce v2 audience / scope / expiry from the signed claims (plan §6.1). The claims are + // trustworthy: for self/local tokens the exact JWT string is the DB key (tamper ⇒ miss); + // for foreign tokens validateRemoteToken re-verified the signature over these claims. + const scopeCheck = this.enforceScopedClaims(token, command) + if (!scopeCheck.valid) { + return scopeCheck } - return { valid: false, error: 'Invalid token' } + return { valid: true, error: '', address: authToken.address } } return { @@ -268,4 +544,46 @@ export class Auth { return { valid: false, error: `Error during authentication validation: ${e}` } } } + + // Enforce the v2 claims (audience / scope / expiry) from the token itself (plan §6.1). Distinct + // error strings per gate for debuggability (plan §10). + private enforceScopedClaims( + token: string, + command?: string + ): CommonValidation & { address?: string } { + const decoded = jwt.decode(token) as DecodedTokenClaims | null + if (!decoded || typeof decoded !== 'object') { + return { valid: true, error: '' } + } + // Unknown / unsupported version ⇒ reject outright (never interpret an unknown format). + if (decoded.v != null && decoded.v !== AUTH_TOKEN_VERSION) { + return { valid: false, error: 'unsupported token version' } + } + if (decoded.v === AUTH_TOKEN_VERSION) { + // Strict v2 semantics (belt to validateRemoteToken's suspenders): a v2 token MUST carry a + // signed numeric validUntil. A self/local v2 token always does (the issuer sets it); this + // also rejects any malformed v2 claim that reaches the chokepoint. + if (typeof decoded.validUntil !== 'number') { + return { valid: false, error: 'invalid v2 token (missing validUntil)' } + } + // audience + if (Array.isArray(decoded.audience) && decoded.audience.length) { + const selfPeerId = OceanNode.getInstance().getKeyManager().getPeerIdString() + if (!decoded.audience.includes(selfPeerId)) { + return { valid: false, error: 'token not valid at this node (audience)' } + } + } + // scope + if (Array.isArray(decoded.scope) && decoded.scope.length) { + if (!command || !decoded.scope.includes(command)) { + return { valid: false, error: 'token not permitted for this command (scope)' } + } + } + // expiry (defense in depth; DB/dial already enforce, but the claim is signed) + if (typeof decoded.validUntil === 'number' && decoded.validUntil <= Date.now()) { + return { valid: false, error: 'token expired' } + } + } + return { valid: true, error: '' } + } } diff --git a/src/components/KeyManager/index.ts b/src/components/KeyManager/index.ts index 407dffaf1..e99ecf470 100644 --- a/src/components/KeyManager/index.ts +++ b/src/components/KeyManager/index.ts @@ -212,6 +212,14 @@ export class KeyManager { return await this.keyProvider.signMessage(message) } + /** + * OJ-03: sign raw bytes with the libp2p IDENTITY key (software-local under every provider, + * including KMS). Used to answer the status identity challenge. See IKeyProvider. + */ + async signWithIdentityKey(data: Uint8Array): Promise { + return await this.keyProvider.signWithIdentityKey(data) + } + /** * Cleanup resources (delegates to key provider if it has cleanup method) */ diff --git a/src/components/KeyManager/providers/RawPrivateKeyProvider.ts b/src/components/KeyManager/providers/RawPrivateKeyProvider.ts index ffa2837a2..a5ca4422e 100644 --- a/src/components/KeyManager/providers/RawPrivateKeyProvider.ts +++ b/src/components/KeyManager/providers/RawPrivateKeyProvider.ts @@ -84,6 +84,15 @@ export class RawPrivateKeyProvider implements IKeyProvider { return this.privateKey.raw } + /** + * OJ-03: sign raw bytes with the libp2p IDENTITY key (software-local, never the EVM signer). + * libp2p secp256k1 `.sign()` is SHA-256 + DER, matching `@libp2p/crypto` `publicKey.verify`. + */ + // eslint-disable-next-line require-await + async signWithIdentityKey(data: Uint8Array): Promise { + return this.privateKey.sign(data) + } + /** * This method encrypts data according to a given algorithm using node keys * @param data data to encrypt diff --git a/src/components/core/admin/adminHandler.ts b/src/components/core/admin/adminHandler.ts index c9b0a0b0b..937da9ec4 100644 --- a/src/components/core/admin/adminHandler.ts +++ b/src/components/core/admin/adminHandler.ts @@ -17,13 +17,18 @@ import { ReadableString } from '../../P2P/handleProtocolCommands.js' import { CommonValidation } from '../../../utils/validators.js' import { CORE_LOGGER } from '../../../utils/logging/common.js' import { errorSummary } from '../../../utils/logging/redact.js' -import { normalizeCommandAddresses } from '../../../utils/evmAddress.js' +import { normalizeCommandAddresses, sameAddress } from '../../../utils/evmAddress.js' import { isAddress } from 'ethers' export abstract class AdminCommandHandler extends BaseHandler implements IValidateAdminCommandHandler { + // Whether this admin command accepts a bearer auth token (plan §16.2/§16.3). Default: NO — + // every mutating admin command is signature-only (a fresh single-use nonce-bound signature). + // Only the two read-only admin handlers (FetchConfig / GetLogs) override this to true. + protected readonly allowAuthToken: boolean = false + async verifyParamsAndRateLimits(task: SignedCommand): Promise { // Same ingress normalization as CommandHandler: the admin `address` is matched against // ALLOWED_ADMINS / access lists, so its casing must not decide whether a call is admin. @@ -49,7 +54,10 @@ export abstract class AdminCommandHandler nonce: string, signature: string, command: string, - chainId?: string + chainId?: string, + // The bearer token, forwarded only for read-only admin commands (allowAuthToken). For every + // mutating admin command this stays null and the request MUST be signature-authenticated. + authorization?: string ): Promise { const oceanNode = this.getOceanNode() const auth = oceanNode.getAuth() @@ -59,8 +67,17 @@ export abstract class AdminCommandHandler error: 'Auth not configured' } } + // Mutating admin commands never accept a token (plan §16.2): if one is presented, reject + // explicitly rather than silently ignoring it. + if (!this.allowAuthToken && authorization) { + return { + valid: false, + error: 'this admin command requires a request signature, not an auth token' + } + } + const token = this.allowAuthToken ? authorization : null const isAuthRequestValid = await auth.validateAuthenticationOrToken({ - token: null, + token, address, nonce, signature, @@ -73,13 +90,25 @@ export abstract class AdminCommandHandler error: isAuthRequestValid.error } } + // SECURITY (plan §16.3/§18.2): the ALLOWED_ADMINS gate must run against the AUTHENTICATED + // address, not the raw `address` param. For the token path these can differ: a valid token + // for a non-admin Z could be presented while `address` names admin A. Require BOTH — bind the + // authenticated address to the claimed `address` AND evaluate the admin gate against the + // authenticated address. (The signature path returns the address it verified, so it matches.) + const authenticatedAddress = isAuthRequestValid.address ?? address + if (address && !sameAddress(authenticatedAddress, address)) { + return { + valid: false, + error: 'Authenticated address does not match the requested address' + } + } try { const allowedAdmins = oceanNode.getAdminAddresses() const { addresses, accessLists } = allowedAdmins let allowed = await checkSingleCredential( { type: CREDENTIALS_TYPES.ADDRESS, values: addresses }, - address, + authenticatedAddress, null ) if (allowed) { @@ -116,7 +145,7 @@ export abstract class AdminCommandHandler allowed = await checkCredentialOnAccessList( { [chainId]: validContracts }, chainId, - address, + authenticatedAddress, signer ) } catch (error) { @@ -152,11 +181,14 @@ export abstract class AdminCommandHandler } async validate(command: SignedCommand): Promise { - const commandValidation = validateCommandParameters(command, [ - 'nonce', - 'address', - 'signature' - ]) + // A read-only admin command authorized by a bearer token (allowAuthToken) carries no + // signature/nonce, so those params must NOT be required on the token path — otherwise the + // request is rejected here before it can reach validateTokenOrSignature. The signature path + // still requires nonce/address/signature. (The admin gate + §18.2 address binding run later.) + const usingToken = + this.allowAuthToken && !!command.authorization && !command.signature + const requiredParams = usingToken ? [] : ['nonce', 'address', 'signature'] + const commandValidation = validateCommandParameters(command, requiredParams) if (!commandValidation.valid) { return buildInvalidRequestMessage(commandValidation.reason) } @@ -164,7 +196,9 @@ export abstract class AdminCommandHandler command.address, command.nonce, command.signature, - command.command + command.command, + undefined, + command.authorization ) if (!isAuthRequestValid.valid) { return buildInvalidRequestMessage( diff --git a/src/components/core/admin/fetchConfigHandler.ts b/src/components/core/admin/fetchConfigHandler.ts index c5d2061a6..bd7e18024 100644 --- a/src/components/core/admin/fetchConfigHandler.ts +++ b/src/components/core/admin/fetchConfigHandler.ts @@ -9,6 +9,10 @@ import { ReadableString } from '../../P2P/handleProtocolCommands.js' import { loadConfigFromFile } from '../../../utils/config/index.js' export class FetchConfigHandler extends AdminCommandHandler { + // Read-only admin command: may be authorized by a bearer auth token (scopable), not only a + // signature (plan §16.2). The ALLOWED_ADMINS gate still applies at consumption. + protected readonly allowAuthToken: boolean = true + async validate(command: AdminFetchConfigCommand): Promise { return await super.validate(command) } diff --git a/src/components/core/admin/getLogsHandler.ts b/src/components/core/admin/getLogsHandler.ts index be9918192..cddf30e15 100644 --- a/src/components/core/admin/getLogsHandler.ts +++ b/src/components/core/admin/getLogsHandler.ts @@ -52,6 +52,10 @@ function jsonResponse(body: unknown): P2PCommandResponse { } export class GetLogsHandler extends AdminCommandHandler { + // Read-only admin command: token-authorizable and scopable (plan §16.2). ALLOWED_ADMINS still + // gates at consumption. + protected readonly allowAuthToken: boolean = true + async validate(command: AdminGetLogsCommand): Promise { return await super.validate(command) } diff --git a/src/components/core/handler/authHandler.ts b/src/components/core/handler/authHandler.ts index eb281efc7..3faff159e 100644 --- a/src/components/core/handler/authHandler.ts +++ b/src/components/core/handler/authHandler.ts @@ -11,6 +11,14 @@ import { checkNonce, NonceResponse } from '../utils/nonceHandler.js' import jwt from 'jsonwebtoken' import { CORE_LOGGER } from '../../../utils/logging/common.js' import { errorSummary } from '../../../utils/logging/redact.js' +import { + DISALLOWED_TOKEN_SCOPE_COMMANDS, + MAX_TOKEN_AUDIENCE_ENTRIES, + MAX_TOKEN_SCOPE_ENTRIES, + SUPPORTED_PROTOCOL_COMMANDS +} from '../../../utils/constants.js' +import { AUTH_TOKEN_VERSION } from '../../../utils/crypt.js' +import { peerIdFromString } from '@libp2p/peer-id' export interface AuthMessage { address: string @@ -21,6 +29,113 @@ export interface AuthMessage { export interface CreateAuthTokenCommand extends AuthMessage, Command { validUntil?: number | null chainId?: string | null + // v2 scoped auth tokens (plan §5.1). node peerIds / PROTOCOL_COMMANDS values. Omitted ⇒ + // unrestricted; explicit [] is rejected (§5.3). + audience?: string[] + scope?: string[] +} + +// Small positive skew allowed on the validUntil cap: the client signs an absolute timestamp +// against its own clock (plan §5.2 / §13). +const VALID_UNTIL_SKEW_MS = 60_000 + +// Validates audience/scope/validUntil for a create-auth-token request and resolves the stored +// expiry. Returns `{ error }` (→ HTTP 400) on any violation, otherwise the derived shape. +function validateScopedTokenRequest( + task: CreateAuthTokenCommand, + createdAt: number, + maxLifetimeMs: number +): + | { error: string } + | { + isV2: boolean + audience?: string[] + scope?: string[] + signedValidUntil?: number + storedValidUntil: number + } { + const { audience, scope } = task + + // Reject explicit empty arrays — "unrestricted" is the field being ABSENT, never [] (§5.3). + if (audience !== undefined) { + if (!Array.isArray(audience) || audience.length === 0) { + return { + error: 'empty audience is not allowed; omit the field for unrestricted' + } + } + if (audience.length > MAX_TOKEN_AUDIENCE_ENTRIES) { + return { error: `audience exceeds the maximum of ${MAX_TOKEN_AUDIENCE_ENTRIES}` } + } + for (const peer of audience) { + if (typeof peer !== 'string') { + return { error: 'audience entries must be peerId strings' } + } + try { + peerIdFromString(peer) + } catch { + return { error: `audience entry is not a valid peerId: ${peer}` } + } + } + } + + if (scope !== undefined) { + if (!Array.isArray(scope) || scope.length === 0) { + return { error: 'empty scope is not allowed; omit the field for unrestricted' } + } + if (scope.length > MAX_TOKEN_SCOPE_ENTRIES) { + return { error: `scope exceeds the maximum of ${MAX_TOKEN_SCOPE_ENTRIES}` } + } + for (const cmd of scope) { + if (typeof cmd !== 'string' || !SUPPORTED_PROTOCOL_COMMANDS.includes(cmd)) { + return { error: `command ${cmd} is not a recognized protocol command` } + } + if (DISALLOWED_TOKEN_SCOPE_COMMANDS.includes(cmd)) { + return { error: `command ${cmd} not allowed in token scope` } + } + } + } + + const hasAudience = Array.isArray(audience) && audience.length > 0 + const hasScope = Array.isArray(scope) && scope.length > 0 + const validUntilProvided = task.validUntil !== undefined && task.validUntil !== null + // Any of the three triggers v2 (plan §5.3). + const isV2 = hasAudience || hasScope || validUntilProvided + + if (validUntilProvided) { + const validUntil = task.validUntil as number + if (!Number.isInteger(validUntil)) { + return { error: 'validUntil must be an integer epoch-milliseconds timestamp' } + } + if (validUntil <= createdAt) { + return { error: 'validUntil must be in the future' } + } + // Reject (never clamp) an over-cap lifetime, so signed == stored == claim (plan §3.3/§5.2). + if (validUntil > createdAt + maxLifetimeMs + VALID_UNTIL_SKEW_MS) { + return { + error: `validUntil exceeds the maximum token lifetime (${Math.floor( + maxLifetimeMs / 1000 + )}s)` + } + } + return { + isV2: true, + audience: hasAudience ? audience : undefined, + scope: hasScope ? scope : undefined, + signedValidUntil: validUntil, + storedValidUntil: validUntil + } + } + + // validUntil omitted. If audience/scope were provided, v2 requires a signed validUntil (§5.3). + if (isV2) { + return { error: 'validUntil is required when audience or scope is set' } + } + + // Legacy-style request: server sets an UNSIGNED default expiry (kills never-expiring tokens). + return { + isV2: false, + storedValidUntil: createdAt + maxLifetimeMs + } } export interface InvalidateAuthTokenCommand extends AuthMessage, Command { @@ -42,6 +157,26 @@ export class CreateAuthTokenHandler extends CommandHandler { } try { + const auth = this.getOceanNode().getAuth() + const createdAt = Date.now() + + // Validate audience / scope / validUntil and resolve the stored expiry (plan §5.2–5.3). + const scoped = validateScopedTokenRequest( + task, + createdAt, + auth.getMaxTokenLifetimeMs() + ) + if ('error' in scoped) { + return { + stream: null, + status: { httpStatus: 400, error: scoped.error } + } + } + + const issuerPeerId = this.getOceanNode().getKeyManager().getPeerIdString() + + // For v2, the signed message folds in version/audience/scope/exp — thread them into the + // signature check so the consumer-signed bytes match. Legacy keeps the byte-identical path. const nonceCheckResult: NonceResponse = await checkNonce( this.getOceanNode().getConfig(), nonceDb, @@ -49,7 +184,14 @@ export class CreateAuthTokenHandler extends CommandHandler { parseInt(nonce), signature, task.command, - task.chainId + task.chainId, + scoped.isV2 + ? { + audience: scoped.audience, + scope: scoped.scope, + validUntil: scoped.signedValidUntil + } + : undefined ) if (!nonceCheckResult.valid) { @@ -59,22 +201,30 @@ export class CreateAuthTokenHandler extends CommandHandler { } } - const createdAt = Date.now() - const issuerPeerId = this.getOceanNode().getKeyManager().getPeerIdString() - const jwtToken = await this.getOceanNode() - .getAuth() - .getJWTToken( - task.address, - task.nonce, - createdAt, - signature, - issuerPeerId, - task.chainId - ) - - await this.getOceanNode() - .getAuth() - .insertToken(task.address, jwtToken, task.validUntil, createdAt, task.chainId) + const jwtToken = await auth.getJWTToken( + task.address, + task.nonce, + createdAt, + signature, + issuerPeerId, + task.chainId, + scoped.isV2 + ? { + version: AUTH_TOKEN_VERSION, + audience: scoped.audience, + scope: scoped.scope, + validUntil: scoped.signedValidUntil + } + : undefined + ) + + await auth.insertToken( + task.address, + jwtToken, + scoped.storedValidUntil, + createdAt, + task.chainId + ) return { stream: Readable.from(JSON.stringify({ token: jwtToken })), diff --git a/src/components/core/handler/ddoHandler.ts b/src/components/core/handler/ddoHandler.ts index 8bcd1d412..63da016b8 100644 --- a/src/components/core/handler/ddoHandler.ts +++ b/src/components/core/handler/ddoHandler.ts @@ -207,8 +207,12 @@ export class DecryptDdoHandler extends CommandHandler { // the exact resource (chainId + txId + dataNftAddress), so a signature harvested from one // node/asset cannot be replayed against another. dataNftAddress was already checksum- // normalized by verifyParamsAndRateLimits; the Indexer signer checksums it to match. + // HIGH (plan §18.1): DECRYPT_DDO is token-INELIGIBLE. A reusable bearer token would skip the + // ON-02 txId/dataNftAddress/peerId binding and become a universal decrypt for that address, + // defeating ON-02. Force the signature-only path by passing `null` for the token (the central + // chokepoint also rejects a token for this command, but this makes it explicit here). const isAuthRequestValid = await this.validateTokenOrSignature( - task.authorization, + null, task.decrypterAddress, task.nonce, task.signature, diff --git a/src/components/core/handler/statusHandler.ts b/src/components/core/handler/statusHandler.ts index 76aeeadd6..ce7348a7c 100644 --- a/src/components/core/handler/statusHandler.ts +++ b/src/components/core/handler/statusHandler.ts @@ -1,6 +1,6 @@ import { CommandHandler } from './handler.js' import { status } from '../utils/statusHandler.js' -import { P2PCommandResponse } from '../../../@types/OceanNode.js' +import { OceanNodeStatus, P2PCommandResponse } from '../../../@types/OceanNode.js' import { DetailedStatusCommand, StatusCommand } from '../../../@types/commands.js' import { Readable } from 'stream' import { @@ -8,12 +8,67 @@ import { validateCommandParameters } from '../../httpRoutes/validateCommands.js' import { CORE_LOGGER } from '../../../utils/logging/common.js' +import { STATUS_CHALLENGE_DOMAIN } from '../../../utils/crypt.js' +import { toUtf8Bytes, hexlify } from 'ethers' + +// OJ-03 (plan §14.2): bound the public signing oracle — reject an oversized challenge. +const MAX_CLIENT_CHALLENGE_BYTES = 256 +// Dedicated rate-limit bucket for the challenge-signing path (plan §14.4), separate from the +// global per-caller limiter. +const STATUS_CHALLENGE_BUCKET = 'status-challenge' export class StatusHandler extends CommandHandler { validate(command: StatusCommand): ValidateParams { return validateCommandParameters(command, []) } + /** + * OJ-03: sign the client challenge with the node's libp2p IDENTITY key over a domain-separated + * digest, so the signature proves control of the key the peerId commits to and can never + * collide with anything else that key signs. Returns the 0x-hex signature, or a status response + * when the request must be rejected (oversized challenge / rate limit). Never caches the result. + */ + private async signClientChallenge( + task: StatusCommand + ): Promise<{ signedChallenge?: string; reject?: P2PCommandResponse }> { + const { clientChallenge } = task + if (clientChallenge == null) { + return {} + } + if ( + typeof clientChallenge !== 'string' || + Buffer.byteLength(clientChallenge, 'utf8') > MAX_CLIENT_CHALLENGE_BYTES + ) { + return { + reject: { + stream: null, + status: { httpStatus: 400, error: 'Invalid clientChallenge' } + } + } + } + // Dedicated, stricter per-caller limit for the sign path only (counted in its own bucket), + // enforced BEFORE doing any signing. Over the limit ⇒ reject without signing. + const rate = this.getOceanNode().getConfig().statusChallengeRateLimit + const underLimit = await this.checkRateLimitForBucket( + task.caller, + rate, + STATUS_CHALLENGE_BUCKET + ) + if (!underLimit) { + return { + reject: { + stream: null, + status: { httpStatus: 429, error: 'Too many status challenge requests' } + } + } + } + const message = STATUS_CHALLENGE_DOMAIN + clientChallenge + const signatureBytes = await this.getOceanNode() + .getKeyManager() + .signWithIdentityKey(toUtf8Bytes(message)) + return { signedChallenge: hexlify(signatureBytes) } + } + async handle(task: StatusCommand): Promise { const checks = await this.verifyParamsAndRateLimits(task) if (checks.status.httpStatus !== 200 || checks.status.error !== null) { @@ -27,8 +82,23 @@ export class StatusHandler extends CommandHandler { status: { httpStatus: 404, error: 'Status Not Found' } } } + // OJ-03: compute signedChallenge per request and merge it into a SHALLOW COPY so the shared + // (cached) status object never carries it (plan §14.4). + let responseStatus: OceanNodeStatus = statusResult + const { signedChallenge, reject } = await this.signClientChallenge(task) + if (reject) { + return reject + } + if (signedChallenge) { + // OJ-03 correctness: the client verifies `signedChallenge` against the public key embedded + // in `id`. The cached `nodeStatus.id` can hold a caller-supplied `node` from an earlier + // request, which would not match the identity key that signs the challenge. Pin `id` to + // THIS node's own peerId for any challenged response so the two always agree. + const selfPeerId = this.getOceanNode().getKeyManager().getPeerIdString() + responseStatus = { ...statusResult, id: selfPeerId, signedChallenge } + } return { - stream: Readable.from(JSON.stringify(statusResult, null, 4)), + stream: Readable.from(JSON.stringify(responseStatus, null, 4)), status: { httpStatus: 200 } } } catch (error) { diff --git a/src/components/core/utils/nonceHandler.ts b/src/components/core/utils/nonceHandler.ts index 81d4a6e96..644db32e0 100644 --- a/src/components/core/utils/nonceHandler.ts +++ b/src/components/core/utils/nonceHandler.ts @@ -10,7 +10,22 @@ import { NonceCommand } from '../../../@types/commands.js' import { streamToString } from '../../../utils/util.js' import { Readable } from 'node:stream' import { addressCasingVariants } from '../../../utils/evmAddress.js' -import { buildDecryptDDOSignatureMessage } from '../../../utils/crypt.js' +import { + buildDecryptDDOSignatureMessage, + buildCreateAuthTokenSignatureMessage +} from '../../../utils/crypt.js' + +// Extra fields folded into the signed message for specific commands. +// - ON-02 (DECRYPT_DDO): txId / dataNftAddress resource binding. +// - v2 scoped auth tokens (CREATE_AUTH_TOKEN): audience / scope / validUntil (plan §3.2). A +// non-undefined `validUntil` is what promotes CREATE_AUTH_TOKEN to the v2 message format. +export interface ExtraSignedFields { + txId?: string + dataNftAddress?: string + audience?: string[] + scope?: string[] + validUntil?: number +} export function getDefaultErrorResponse(errorMessage: string): P2PCommandResponse { return { @@ -114,7 +129,7 @@ export async function checkNonce( command: string, chainId?: string | null, // ON-02: resource-binding fields, appended to the signed message ONLY for DECRYPT_DDO. - extraSignedFields?: { txId?: string; dataNftAddress?: string } + extraSignedFields?: ExtraSignedFields ): Promise { try { // get nonce from db @@ -174,7 +189,7 @@ async function validateNonceAndSignature( command: string = null, config: OceanNodeConfig, chainId?: string | null, - extraSignedFields?: { txId?: string; dataNftAddress?: string } + extraSignedFields?: ExtraSignedFields ): Promise { if (nonce <= existingNonce) { return { @@ -217,7 +232,10 @@ export async function verifyConsumerSignature( command: string = null, config?: OceanNodeConfig, chainId?: string | null, - extraSignedFields?: { txId?: string; dataNftAddress?: string } + extraSignedFields?: ExtraSignedFields, + // plan §18.4: when verifying a bearer token (validateRemoteToken) and no chainId is pinned, + // skip the per-network ERC-1271 fan-out so a single junk token cannot trigger N `eth_call`s. + tokenPath: boolean = false ): Promise { // The signed message embeds the consumer address as a STRING, so its casing is part of what // was signed. Addresses are checksum-normalized on ingress (utils/evmAddress.ts), which would @@ -233,7 +251,8 @@ export async function verifyConsumerSignature( command, config, chainId, - extraSignedFields + extraSignedFields, + tokenPath ) ) { return true @@ -250,11 +269,18 @@ async function verifySignatureForConsumer( command: string = null, config?: OceanNodeConfig, chainId?: string | null, - extraSignedFields?: { txId?: string; dataNftAddress?: string } + extraSignedFields?: ExtraSignedFields, + tokenPath: boolean = false ): Promise { // ON-02: DECRYPT_DDO uses a resource- and destination-bound message built by the SHARED // helper that the Indexer signer also uses, so signer and verifier cannot drift. Every other // command keeps its byte-for-byte original message (consumer + nonce + command + issuerPeerId). + // v2 scoped auth token (plan §3.2): a CREATE_AUTH_TOKEN whose request carries a `validUntil` + // signs the versioned, audience/scope/exp-bound message via the SHARED helper. A legacy + // CREATE_AUTH_TOKEN (no validUntil) keeps the byte-identical concat below. + const isV2CreateAuthToken = + command === PROTOCOL_COMMANDS.CREATE_AUTH_TOKEN && + extraSignedFields?.validUntil !== undefined const message = command === PROTOCOL_COMMANDS.DECRYPT_DDO ? buildDecryptDDOSignatureMessage({ @@ -265,7 +291,18 @@ async function verifySignatureForConsumer( txId: extraSignedFields?.txId ?? '', dataNftAddress: extraSignedFields?.dataNftAddress ?? '' }) - : String(String(consumer) + String(nonce) + String(command) + String(issuerPeerId)) + : isV2CreateAuthToken + ? buildCreateAuthTokenSignatureMessage({ + address: String(consumer), + nonce, + issuerPeerId: String(issuerPeerId), + audience: extraSignedFields?.audience, + scope: extraSignedFields?.scope, + validUntil: extraSignedFields?.validUntil + }) + : String( + String(consumer) + String(nonce) + String(command) + String(issuerPeerId) + ) const consumerMessage = ethers.solidityPackedKeccak256( ['bytes'], [ethers.hexlify(ethers.toUtf8Bytes(message))] @@ -295,10 +332,15 @@ async function verifySignatureForConsumer( // Continue to smart account check } - // An explicit chain restricts validation; otherwise try every configured network. + // An explicit chain restricts validation; otherwise try every configured network. On the token + // path with no pinned chain, skip the ERC-1271 fan-out entirely (plan §18.4) — a smart-account + // (ERC-1271) token must carry a chainId to be validated cross-node; EOA tokens are unaffected + // (verified above without any RPC). const targetChainIds = chainId ? [chainId] - : Object.keys(config?.supportedNetworks || {}) + : tokenPath + ? [] + : Object.keys(config?.supportedNetworks || {}) for (const targetChainId of targetChainIds) { const network = config?.supportedNetworks?.[targetChainId] if (!network) continue diff --git a/src/components/core/utils/statusHandler.ts b/src/components/core/utils/statusHandler.ts index faeba8023..d1a1d6d94 100644 --- a/src/components/core/utils/statusHandler.ts +++ b/src/components/core/utils/statusHandler.ts @@ -4,7 +4,8 @@ import { OceanNodeProvider, OceanNodeIndexer, StorageTypes, - OceanNodeConfig + OceanNodeConfig, + AuthTokenPolicyStatus } from '../../../@types/OceanNode.js' import { CORE_LOGGER } from '../../../utils/logging/common.js' import { OceanNode } from '../../../OceanNode.js' @@ -35,6 +36,29 @@ const platformInfo = { node: process.version } +// Node auth-token policy exposed in `status` (plan §17.2). Static config; safe in the cached +// status object. `crossNode: 'open'` is intentionally unreachable (enabling with an empty +// allowlist fails at startup), so an operator who wants to trust everyone must still enumerate. +function buildAuthTokenPolicy(config: OceanNodeConfig): AuthTokenPolicyStatus { + const fallback = config.tokenRevocationFallback ?? 'cache' + const crossNode = config.allowCrossNodeTokens ? 'allowlist' : 'disabled' + const policy: AuthTokenPolicyStatus = { + maxTokenLifetime: config.maxTokenLifetime ?? 86400, + crossNode, + revocationFallback: fallback, + challengeSupported: true + } + // trustedIssuers exposed (user decision, plan §18.5 L2) — only meaningful in allowlist mode. + if (crossNode === 'allowlist') { + policy.trustedIssuers = config.trustedTokenIssuers ?? [] + } + // softFailGrace is only consulted in 'cache' mode. + if (fallback === 'cache') { + policy.softFailGrace = config.tokenSoftFailGrace ?? 300 + } + return policy +} + function getProviderInfo(config: OceanNodeConfig): OceanNodeProvider[] { const providers: OceanNodeProvider[] = [] for (const [key, supportedNetwork] of Object.entries(config.supportedNetworks)) { @@ -150,6 +174,10 @@ export async function status( nodeStatus.subsidyProviderFilter = config.subsidyProviderFilter ?? false // Per-subsidy-address docker image allowlist; empty map when unset (no gating). nodeStatus.subsidyProviderAllowedImages = config.subsidyProviderAllowedImages ?? {} + // Auth-token policy (plan §17.2). Static config; set every request (like subsidyProviders) so a + // config reload never leaves a stale value. `signedChallenge` is added per-request by the + // handler and is deliberately NOT part of this cached object. + nodeStatus.authTokenPolicy = buildAuthTokenPolicy(config) // getConfig() refreshes it from POLICY_SERVER_URL, so the cached status never goes stale. nodeStatus.isPSConfigured = config.isPSConfigured // Re-read on every request so the cached status follows NODE_OWNER_INFO changes. diff --git a/src/components/httpRoutes/adminConfig.ts b/src/components/httpRoutes/adminConfig.ts index 52bce2dbe..b15214b05 100644 --- a/src/components/httpRoutes/adminConfig.ts +++ b/src/components/httpRoutes/adminConfig.ts @@ -10,13 +10,18 @@ export const adminConfigRoutes = express.Router() adminConfigRoutes.get('/api/admin/config', express.json(), async (req, res) => { try { - const { nonce, signature, address } = req.body + // A token-authorized (header-only) request may carry no JSON body, leaving req.body undefined; + // default to {} so destructuring never throws and the token still reaches the validator. + const { nonce, signature, address } = req.body || {} const response = await new FetchConfigHandler(req.oceanNode).handle({ command: PROTOCOL_COMMANDS.FETCH_CONFIG, nonce, signature, address, + // read-only admin: a scoped auth token may be presented via the Authorization header + // instead of a signature (plan §16.3). The ALLOWED_ADMINS gate still applies. + authorization: req.headers?.authorization as string, caller: req.caller }) diff --git a/src/components/httpRoutes/auth.ts b/src/components/httpRoutes/auth.ts index 389954b4a..9f5ce6a7e 100644 --- a/src/components/httpRoutes/auth.ts +++ b/src/components/httpRoutes/auth.ts @@ -15,7 +15,7 @@ authRoutes.post( express.json(), async (req, res) => { try { - const { signature, address, nonce, validUntil, chainId } = req.body + const { signature, address, nonce, validUntil, chainId, audience, scope } = req.body if (!signature || !address) { return res.status(400).json({ error: 'Missing required parameters' }) @@ -28,6 +28,9 @@ authRoutes.post( nonce, validUntil, chainId, + // v2 scoped auth tokens (plan §5.1). Forwarded as sent; the handler validates & caps. + audience, + scope, caller: req.caller }) diff --git a/src/components/httpRoutes/logs.ts b/src/components/httpRoutes/logs.ts index 1a314df91..8ebb1128c 100644 --- a/src/components/httpRoutes/logs.ts +++ b/src/components/httpRoutes/logs.ts @@ -14,7 +14,9 @@ function parseQueryInt(value: unknown): number | undefined { logRoutes.post('/logs', express.json(), async (req, res) => { try { - const { signature, address, nonce } = req.body + // A token-authorized (header-only) request may carry no JSON body; default to {} so + // destructuring never throws and the token still reaches the validator. + const { signature, address, nonce } = req.body || {} // NaN (missing or not a number) becomes undefined: the handler defaults to 100 logs // (max 1000) and to the first page @@ -29,6 +31,9 @@ logRoutes.post('/logs', express.json(), async (req, res) => { signature, nonce, address, + // read-only admin: a scoped auth token may be presented via the Authorization header + // instead of a signature (plan §16.3). The ALLOWED_ADMINS gate still applies. + authorization: req.headers?.authorization as string, startTime: req.query.startTime as string, endTime: req.query.endTime as string, maxLogs, @@ -57,7 +62,7 @@ logRoutes.post('/logs', express.json(), async (req, res) => { logRoutes.post('/log/:id', express.json(), async (req, res) => { try { - const { signature, nonce, address, logId } = req.body + const { signature, nonce, address, logId } = req.body || {} if (!logId) { res.status(400).send('id is missing') return @@ -67,6 +72,8 @@ logRoutes.post('/log/:id', express.json(), async (req, res) => { signature, nonce, address, + // read-only admin: scoped auth token accepted via the Authorization header (plan §16.3). + authorization: req.headers?.authorization as string, logId, // trusted transport caller (request IP), never a body-supplied value — keys the limiter caller: req.caller diff --git a/src/test/integration/auth.test.ts b/src/test/integration/auth.test.ts index 905bbfe75..4955c4072 100644 --- a/src/test/integration/auth.test.ts +++ b/src/test/integration/auth.test.ts @@ -22,7 +22,12 @@ import { streamToObject } from '../../utils/util.js' import { Readable } from 'stream' import { expect } from 'chai' import { ValidateDDOHandler } from '../../components/core/handler/ddoHandler.js' -import { createHashForSignature, safeSign } from '../utils/signature.js' +import { + createHashForSignature, + createHashForMessage, + safeSign +} from '../utils/signature.js' +import { buildCreateAuthTokenSignatureMessage } from '../../utils/crypt.js' describe('********** Auth Token Integration Tests', () => { let config: OceanNodeConfig @@ -148,15 +153,19 @@ describe('********** Auth Token Integration Tests', () => { const consumerAddress = await consumerAccount.getAddress() const nonce = getRandomNonce() - const messageHash = createHashForSignature( - consumerAddress, - nonce, - PROTOCOL_COMMANDS.CREATE_AUTH_TOKEN, - oceanNode.getKeyManager().getPeerIdString() + // Passing validUntil makes this a v2 (scoped) token, so the signature must be over the v2 + // message (plan §3.2 / §5.3), not the legacy concat. + const validUntil = Date.now() + 1000 + const messageHash = createHashForMessage( + buildCreateAuthTokenSignatureMessage({ + address: consumerAddress, + nonce, + issuerPeerId: oceanNode.getKeyManager().getPeerIdString(), + validUntil + }) ) const signature = await safeSign(consumerAccount, messageHash) - const validUntil = Date.now() + 1000 const handlerResponse = await new CreateAuthTokenHandler(oceanNode).handle({ command: PROTOCOL_COMMANDS.CREATE_AUTH_TOKEN, address: consumerAddress, diff --git a/src/test/unit/auth/scopedAuthToken.test.ts b/src/test/unit/auth/scopedAuthToken.test.ts new file mode 100644 index 000000000..9287def31 --- /dev/null +++ b/src/test/unit/auth/scopedAuthToken.test.ts @@ -0,0 +1,272 @@ +import { expect } from 'chai' +import jwt from 'jsonwebtoken' +import { Wallet } from 'ethers' +import { + buildCreateAuthTokenSignatureMessage, + AUTH_TOKEN_VERSION, + STATUS_CHALLENGE_DOMAIN +} from '../../../utils/crypt.js' +import { + DISALLOWED_TOKEN_SCOPE_COMMANDS, + TOKEN_INELIGIBLE_COMMANDS, + PROTOCOL_COMMANDS +} from '../../../utils/constants.js' +import { Auth } from '../../../components/Auth/index.js' +import { AuthTokenDatabase } from '../../../components/database/AuthTokenDatabase.js' +import { OceanNode } from '../../../OceanNode.js' +import { getConfiguration } from '../../../utils/index.js' +import { Database } from '../../../components/database/index.js' +import { KeyManager } from '../../../components/KeyManager/index.js' +import { BlockchainRegistry } from '../../../components/BlockchainRegistry/index.js' + +// ────────────────────────────────────────────────────────────────────────────────────────── +// GOLDEN VECTORS — these MUST be byte-identical to the ocean.js test of the same name. If one +// byte changes here, change both repos (shared wire contract, plan §3.2 / §11). +// ────────────────────────────────────────────────────────────────────────────────────────── +const V = { + ADDR: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', + NONCE: '42', + PEER: '16Uiu2HAmTEST', + EXP: 1893456000000 +} +const GOLDEN = { + expOnly: + '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc242createAuthToken16Uiu2HAmTEST|v:2|aud:|cmd:|exp:1893456000000', + audOnly: + '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc242createAuthToken16Uiu2HAmTEST|v:2|aud:16Uiu2HAmAAA,16Uiu2HAmBBB|cmd:|exp:1893456000000', + scopeOnly: + '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc242createAuthToken16Uiu2HAmTEST|v:2|aud:|cmd:download,query|exp:1893456000000', + bothDedup: + '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc242createAuthToken16Uiu2HAmTEST|v:2|aud:16Uiu2HAmAAA,16Uiu2HAmBBB|cmd:download,startCompute|exp:1893456000000', + single: + '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc242createAuthToken16Uiu2HAmTEST|v:2|aud:16Uiu2HAmONLY|cmd:download|exp:1893456000000' +} + +describe('scoped auth token — signed message (golden vectors)', () => { + const base = { + address: V.ADDR, + nonce: V.NONCE, + issuerPeerId: V.PEER, + validUntil: V.EXP + } + + it('exp only (no aud/scope)', () => { + expect(buildCreateAuthTokenSignatureMessage({ ...base })).to.equal(GOLDEN.expOnly) + }) + it('audience only — dedup + sort', () => { + expect( + buildCreateAuthTokenSignatureMessage({ + ...base, + audience: ['16Uiu2HAmBBB', '16Uiu2HAmAAA'] + }) + ).to.equal(GOLDEN.audOnly) + }) + it('scope only — sort order', () => { + expect( + buildCreateAuthTokenSignatureMessage({ ...base, scope: ['query', 'download'] }) + ).to.equal(GOLDEN.scopeOnly) + }) + it('both, with dedup', () => { + expect( + buildCreateAuthTokenSignatureMessage({ + ...base, + audience: ['16Uiu2HAmBBB', '16Uiu2HAmAAA', '16Uiu2HAmBBB'], + scope: ['startCompute', 'download', 'download'] + }) + ).to.equal(GOLDEN.bothDedup) + }) + it('single element each', () => { + expect( + buildCreateAuthTokenSignatureMessage({ + ...base, + audience: ['16Uiu2HAmONLY'], + scope: ['download'] + }) + ).to.equal(GOLDEN.single) + }) + it('AUTH_TOKEN_VERSION is 2 and embedded in the bytes', () => { + expect(AUTH_TOKEN_VERSION).to.equal(2) + expect(GOLDEN.expOnly).to.contain('|v:2|') + }) + it('STATUS_CHALLENGE_DOMAIN matches the shared contract', () => { + expect(STATUS_CHALLENGE_DOMAIN).to.equal('ocean-node-status-challenge-v1:') + }) +}) + +describe('scoped auth token — disallowed-scope / ineligible constants', () => { + it('DECRYPT_DDO and mutating admin are disallowed in scope', () => { + for (const c of [ + PROTOCOL_COMMANDS.DECRYPT_DDO, + PROTOCOL_COMMANDS.STOP_NODE, + PROTOCOL_COMMANDS.STOP_JOB, + PROTOCOL_COMMANDS.HANDLE_INDEXING_THREAD, + PROTOCOL_COMMANDS.SET_MAINTENANCE, + PROTOCOL_COMMANDS.CREATE_AUTH_TOKEN, + PROTOCOL_COMMANDS.VALIDATE_AUTH_TOKEN + ]) { + expect(DISALLOWED_TOKEN_SCOPE_COMMANDS).to.include(c) + } + }) + it('fetchConfig / getLogs are NOT disallowed in scope', () => { + expect(DISALLOWED_TOKEN_SCOPE_COMMANDS).to.not.include(PROTOCOL_COMMANDS.FETCH_CONFIG) + expect(DISALLOWED_TOKEN_SCOPE_COMMANDS).to.not.include(PROTOCOL_COMMANDS.GET_LOGS) + }) + it('DECRYPT_DDO + mutating admin are token-INELIGIBLE at consumption', () => { + expect(TOKEN_INELIGIBLE_COMMANDS).to.include(PROTOCOL_COMMANDS.DECRYPT_DDO) + expect(TOKEN_INELIGIBLE_COMMANDS).to.include(PROTOCOL_COMMANDS.STOP_NODE) + // read-only admin and ordinary read commands are eligible + expect(TOKEN_INELIGIBLE_COMMANDS).to.not.include(PROTOCOL_COMMANDS.GET_LOGS) + expect(TOKEN_INELIGIBLE_COMMANDS).to.not.include(PROTOCOL_COMMANDS.DOWNLOAD) + }) +}) + +describe('scoped auth token — claims + enforcement', () => { + let authTokenDatabase: AuthTokenDatabase + let auth: Auth + let wallet: Wallet + let selfPeerId: string + const nonce = () => Math.floor(Math.random() * 1e9).toString() + + before(async () => { + const config = await getConfiguration(true) + authTokenDatabase = await AuthTokenDatabase.create(config.dbConfig) + auth = new Auth(authTokenDatabase, config) + wallet = new Wallet(process.env.PRIVATE_KEY) + // SQLite-core-only DB (no metadata DB needed for auth); build a minimal OceanNode so the + // enforcement path (which reads the node's own peerId) has a singleton. + const db = await Database.init({ + url: 'http://localhost:9999', + dbType: 'none' + } as any) + const keyManager = new KeyManager(config) + const blockchainRegistry = new BlockchainRegistry(keyManager, config) + OceanNode.getInstance( + config, + db, + undefined, + undefined, + undefined, + keyManager, + blockchainRegistry, + true + ) + selfPeerId = keyManager.getPeerIdString() + }) + + async function mintLocalToken(scoped?: { + audience?: string[] + scope?: string[] + validUntil?: number + }) { + const createdAt = Date.now() + const validUntil = scoped?.validUntil ?? createdAt + 60_000 + const token = await auth.getJWTToken( + wallet.address, + nonce(), + createdAt, + 'sig', + selfPeerId, + null, + scoped + ? { + version: AUTH_TOKEN_VERSION, + audience: scoped.audience, + scope: scoped.scope, + validUntil + } + : undefined + ) + await auth.insertToken(wallet.address, token, validUntil, createdAt, null) + return token + } + + it('legacy getJWTToken emits NO v/audience/scope/validUntil claims', async () => { + const token = await auth.getJWTToken(wallet.address, nonce(), Date.now()) + const claims: any = jwt.decode(token) + expect(claims.v).to.equal(undefined) + expect(claims.audience).to.equal(undefined) + expect(claims.scope).to.equal(undefined) + expect(claims.validUntil).to.equal(undefined) + }) + + it('v2 getJWTToken emits v=2 + the signed fields verbatim', async () => { + const token = await mintLocalToken({ + audience: [selfPeerId], + scope: ['download'], + validUntil: Date.now() + 60_000 + }) + const claims: any = jwt.decode(token) + expect(claims.v).to.equal(2) + expect(claims.audience).to.deep.equal([selfPeerId]) + expect(claims.scope).to.deep.equal(['download']) + expect(typeof claims.validUntil).to.equal('number') + }) + + it('accepts a v2 token used IN audience', async () => { + const token = await mintLocalToken({ audience: [selfPeerId] }) + const res = await auth.validateAuthenticationOrToken({ + token, + command: PROTOCOL_COMMANDS.DOWNLOAD + }) + expect(res.valid).to.equal(true) + }) + + it('rejects a v2 token used OUT of audience', async () => { + const token = await mintLocalToken({ audience: ['16Uiu2HAmNOTME'] }) + const res = await auth.validateAuthenticationOrToken({ + token, + command: PROTOCOL_COMMANDS.DOWNLOAD + }) + expect(res.valid).to.equal(false) + expect(res.error).to.contain('audience') + }) + + it('accepts a command IN scope and rejects one OUT of scope', async () => { + const token = await mintLocalToken({ scope: ['download'] }) + const ok = await auth.validateAuthenticationOrToken({ + token, + command: PROTOCOL_COMMANDS.DOWNLOAD + }) + expect(ok.valid).to.equal(true) + const bad = await auth.validateAuthenticationOrToken({ + token, + command: PROTOCOL_COMMANDS.QUERY + }) + expect(bad.valid).to.equal(false) + expect(bad.error).to.contain('scope') + }) + + it('rejects a v2-claimed token that omits validUntil (strict v2 semantics)', async () => { + // Craft a malformed v2 token directly: v=2 but NO validUntil (the issuer never mints this). + const createdAt = Date.now() + const malformed = jwt.sign( + { + v: 2, + address: wallet.address, + nonce: nonce(), + createdAt, + issuerPeerId: selfPeerId + }, + auth.getJwtSecret() + ) + // Make it pass the DB lookup (local token) so enforcement is what rejects it. + await auth.insertToken(wallet.address, malformed, createdAt + 60_000, createdAt, null) + const res = await auth.validateAuthenticationOrToken({ + token: malformed, + command: PROTOCOL_COMMANDS.DOWNLOAD + }) + expect(res.valid).to.equal(false) + expect(res.error).to.contain('validUntil') + }) + + it('rejects ANY token (even unrestricted) for a token-ineligible command', async () => { + // unrestricted v2 token (v=2, validUntil, but no scope/audience) + const token = await mintLocalToken({ validUntil: Date.now() + 60_000 }) + const res = await auth.validateAuthenticationOrToken({ + token, + command: PROTOCOL_COMMANDS.DECRYPT_DDO + }) + expect(res.valid).to.equal(false) + expect(res.error).to.contain('requires a request signature') + }) +}) diff --git a/src/test/unit/auth/statusChallenge.test.ts b/src/test/unit/auth/statusChallenge.test.ts new file mode 100644 index 000000000..3f9cd48a1 --- /dev/null +++ b/src/test/unit/auth/statusChallenge.test.ts @@ -0,0 +1,65 @@ +import { expect } from 'chai' +import { toUtf8Bytes } from 'ethers' +import { peerIdFromString } from '@libp2p/peer-id' +import { KeyManager } from '../../../components/KeyManager/index.js' +import { getConfiguration } from '../../../utils/index.js' +import { STATUS_CHALLENGE_DOMAIN } from '../../../utils/crypt.js' + +// OJ-03 (plan §14): the node answers a status challenge by signing a DOMAIN-SEPARATED digest with +// its libp2p IDENTITY key. ocean.js verifies with the public key extracted from the peerId. These +// tests prove the roundtrip and the domain separation locally. +describe('OJ-03 status identity challenge', () => { + let keyManager: KeyManager + let peerIdStr: string + + before(async () => { + const config = await getConfiguration(true) + keyManager = new KeyManager(config) + peerIdStr = keyManager.getPeerIdString() + }) + + it('signWithIdentityKey output verifies against the peerId public key', async () => { + const challenge = 'deadbeefcafe0001' + const message = STATUS_CHALLENGE_DOMAIN + challenge + const sig = await keyManager.signWithIdentityKey(toUtf8Bytes(message)) + const pub = peerIdFromString(peerIdStr).publicKey + expect(pub).to.not.equal(undefined) + const ok = await pub.verify(toUtf8Bytes(message), sig) + expect(ok).to.equal(true) + }) + + it('domain separation: signature does NOT verify as a bare-challenge signature', async () => { + const challenge = 'deadbeefcafe0002' + const sig = await keyManager.signWithIdentityKey( + toUtf8Bytes(STATUS_CHALLENGE_DOMAIN + challenge) + ) + const pub = peerIdFromString(peerIdStr).publicKey + const okBare = await pub.verify(toUtf8Bytes(challenge), sig) + expect(okBare).to.equal(false) + }) + + it('a different challenge yields a different signature', async () => { + const a = await keyManager.signWithIdentityKey( + toUtf8Bytes(STATUS_CHALLENGE_DOMAIN + 'aaaa') + ) + const b = await keyManager.signWithIdentityKey( + toUtf8Bytes(STATUS_CHALLENGE_DOMAIN + 'bbbb') + ) + expect(Buffer.from(a).toString('hex')).to.not.equal(Buffer.from(b).toString('hex')) + }) + + it('signWithIdentityKey is NOT the EVM signer (different key/scheme)', async () => { + // The EVM signer signs an ethers message; its output must not verify as a libp2p signature. + const challenge = 'feed0003' + const message = STATUS_CHALLENGE_DOMAIN + challenge + const evmSig = await keyManager.signMessage(message) // 0x... 65-byte r||s||v hex + const pub = peerIdFromString(peerIdStr).publicKey + let ok = false + try { + ok = await pub.verify(toUtf8Bytes(message), Buffer.from(evmSig.slice(2), 'hex')) + } catch { + ok = false + } + expect(ok).to.equal(false) + }) +}) diff --git a/src/test/unit/auth/token.test.ts b/src/test/unit/auth/token.test.ts index f6c44d172..3da03409c 100644 --- a/src/test/unit/auth/token.test.ts +++ b/src/test/unit/auth/token.test.ts @@ -6,7 +6,15 @@ import { Auth } from '../../../components/Auth/index.js' import { AuthTokenDatabase } from '../../../components/database/AuthTokenDatabase.js' import { OceanP2P } from '../../../components/P2P/index.js' import { Readable } from 'node:stream' -import { createHashForSignature, safeSign } from '../../utils/signature.js' +import { + createHashForSignature, + createHashForMessage, + safeSign +} from '../../utils/signature.js' +import { + buildCreateAuthTokenSignatureMessage, + AUTH_TOKEN_VERSION +} from '../../../utils/crypt.js' describe('Auth Token Tests', () => { let wallet: Wallet @@ -130,11 +138,45 @@ describe('Auth cross-node delegated validation', () => { before(async () => { const baseConfig = await getConfiguration(true) - config = { ...baseConfig, supportedNetworks: {} } + // Lever B (plan §17.1): cross-node validation is opt-in. Federate with the test issuer (and + // SELF for the self-check test) so these tests exercise the dial/cache path, not the gate. + config = { + ...baseConfig, + supportedNetworks: {}, + allowCrossNodeTokens: true, + trustedTokenIssuers: [ISSUER_PEER_ID, SELF_PEER_ID] + } authTokenDatabase = await AuthTokenDatabase.create(baseConfig.dbConfig) consumer = Wallet.createRandom() }) + it('rejects a foreign token when cross-node federation is OFF (default)', async () => { + const { p2p, tracker } = makeFakeP2P({ + verdict: { valid: true, validUntil: Date.now() + 60_000 } + }) + const closedConfig = { + ...config, + allowCrossNodeTokens: false, + trustedTokenIssuers: [] as string[] + } + const auth = new Auth(authTokenDatabase, closedConfig, () => p2p) + const token = await mintToken(auth, consumer, consumer.address) + expect(await auth.validateToken(token)).to.equal(null) + // rejected on the cheap federation gate — no dial + expect(tracker.calls).to.equal(0) + }) + + it('rejects a foreign token from a non-federated issuer', async () => { + const { p2p, tracker } = makeFakeP2P({ + verdict: { valid: true, validUntil: Date.now() + 60_000 } + }) + const otherIssuer = { ...config, trustedTokenIssuers: [SELF_PEER_ID] } + const auth = new Auth(authTokenDatabase, otherIssuer, () => p2p) + const token = await mintToken(auth, consumer, consumer.address) // issued by ISSUER_PEER_ID + expect(await auth.validateToken(token)).to.equal(null) + expect(tracker.calls).to.equal(0) + }) + it('accepts when the signature matches AND the issuer says valid', async () => { const { p2p, tracker } = makeFakeP2P({ verdict: { valid: true, validUntil: Date.now() + 60_000 } @@ -235,4 +277,69 @@ describe('Auth cross-node delegated validation', () => { expect(await auth.getLocalToken(token)).to.equal(null) expect(tracker.calls).to.equal(callsBefore) }) + + async function mintV2Token( + auth: Auth, + signWith: HDNodeWallet, + claimAddress: string, + validUntil: number + ): Promise { + const nonce = '77' + Math.floor(Math.random() * 1e6).toString() + const message = buildCreateAuthTokenSignatureMessage({ + address: claimAddress, + nonce, + issuerPeerId: ISSUER_PEER_ID, + validUntil + }) + const signature = await safeSign(signWith, createHashForMessage(message)) + return auth.getJWTToken( + claimAddress, + nonce, + Date.now(), + signature, + ISSUER_PEER_ID, + null, + { + version: AUTH_TOKEN_VERSION, + validUntil + } + ) + } + + it('caps a foreign verdict validUntil at this node MAX_TOKEN_LIFETIME (plan §7.3)', async () => { + const farFuture = Date.now() + 10 * 24 * 60 * 60_000 // 10 days + const { p2p } = makeFakeP2P({ verdict: { valid: true, validUntil: farFuture } }) + const cfg = { ...config, maxTokenLifetime: 3600 } // local cap: 1h + const auth = new Auth(authTokenDatabase, cfg, () => p2p) + const token = await mintToken(auth, consumer, consumer.address) + const result = await auth.validateToken(token) + expect(result).to.not.equal(null) + // honored only up to now + 1h, NOT the issuer's 10-day verdict + expect(result.validUntil.getTime()).to.be.at.most(Date.now() + 3600_000 + 2000) + expect(result.validUntil.getTime()).to.be.below(farFuture) + }) + + it('open fallback REJECTS a legacy token (no signed expiry) with no cache when issuer is unreachable', async () => { + const { p2p } = makeFakeP2P({ httpStatus: 404 }) + const cfg = { ...config, tokenRevocationFallback: 'open' as const } + const auth = new Auth(authTokenDatabase, cfg, () => p2p) + const token = await mintToken(auth, consumer, consumer.address) // legacy: createdAt is unsigned + expect(await auth.validateToken(token)).to.equal(null) + }) + + it('open fallback honors a v2 token (signed expiry) when issuer is unreachable, capped at local max', async () => { + const { p2p } = makeFakeP2P({ httpStatus: 404 }) + const validUntil = Date.now() + 2 * 60 * 60_000 // 2h (signed) + const cfg = { + ...config, + tokenRevocationFallback: 'open' as const, + maxTokenLifetime: 3600 // local cap: 1h + } + const auth = new Auth(authTokenDatabase, cfg, () => p2p) + const token = await mintV2Token(auth, consumer, consumer.address, validUntil) + const result = await auth.validateToken(token) + expect(result).to.not.equal(null) + // capped at 1h even though the signed validUntil is 2h + expect(result.validUntil.getTime()).to.be.at.most(Date.now() + 3600_000 + 2000) + }) }) diff --git a/src/utils/config/constants.ts b/src/utils/config/constants.ts index fff50cb93..646905f57 100644 --- a/src/utils/config/constants.ts +++ b/src/utils/config/constants.ts @@ -28,6 +28,16 @@ export const ENV_TO_CONFIG_MAPPING = { ESCROW_CLAIM_TIMEOUT: 'claimDurationTimeout', VALIDATE_UNSIGNED_DDO: 'validateUnsignedDDO', JWT_SECRET: 'jwtSecret', + // Scoped auth tokens (plan §8) + MAX_TOKEN_LIFETIME: 'maxTokenLifetime', + TOKEN_REVOCATION_FALLBACK: 'tokenRevocationFallback', + TOKEN_SOFTFAIL_GRACE: 'tokenSoftFailGrace', + TOKEN_REVALIDATE_INTERVAL: 'tokenRevalidateInterval', + // Operator federation — lever B (plan §17.1) + ALLOW_CROSS_NODE_TOKENS: 'allowCrossNodeTokens', + TRUSTED_TOKEN_ISSUERS: 'trustedTokenIssuers', + // OJ-03 status identity challenge (plan §14.4) + STATUS_CHALLENGE_RATE_LIMIT: 'statusChallengeRateLimit', MAX_REQ_PER_MINUTE: 'rateLimit', MAX_CONNECTIONS_PER_MINUTE: 'maxConnections', TRUST_PROXY: 'trustProxy', diff --git a/src/utils/config/schemas.ts b/src/utils/config/schemas.ts index d759d29b1..d09e1d1d8 100644 --- a/src/utils/config/schemas.ts +++ b/src/utils/config/schemas.ts @@ -1746,11 +1746,59 @@ export const OceanNodeConfigSchema = z isBootstrap: booleanFromString.optional().default(false), validateUnsignedDDO: booleanFromString.optional().default(true), jwtSecret: z.string(), + // Scoped auth tokens (plan §8). All seconds. + // Hard cap on token lifetime — kills never-expiring tokens. Default 24h. + maxTokenLifetime: z.coerce.number().int().min(1).optional().default(86400), + // Behaviour when a foreign token's issuer is unreachable for the revocation dial (plan §7/§8.1). + tokenRevocationFallback: z + .enum(['closed', 'cache', 'open']) + .optional() + .default('cache'), + // Soft-fail grace: how long a still-valid positive cache entry is honored during an issuer + // outage, in `cache` mode only. 0 = fail-closed in cache mode. Default 5 min. + tokenSoftFailGrace: z.coerce.number().int().min(0).optional().default(300), + // How long a positive verdict suppresses re-dialing the issuer (success-path freshness). + // 0 = re-dial every request. Default 60s. + tokenRevalidateInterval: z.coerce.number().int().min(0).optional().default(60), + // Operator federation — lever B (plan §17.1). Master switch for honoring FOREIGN tokens. + allowCrossNodeTokens: booleanFromString.optional().default(false), + // Federation allowlist of issuer peerIds. Malformed entries are logged and dropped. + trustedTokenIssuers: jsonFromString(z.array(z.string()), 'trustedTokenIssuers') + .transform((val) => { + if (val === undefined) return [] + if (!Array.isArray(val) || !val.every((v) => typeof v === 'string')) { + CONFIG_LOGGER.error( + 'Invalid TRUSTED_TOKEN_ISSUERS: expected a JSON array of peerId strings, dropping to []' + ) + return [] + } + return val + }) + .optional() + .default([]), + // OJ-03 (plan §14.4): dedicated per-caller rate limit (req/min) for the status + // challenge-signing path, separate bucket. 0 = disabled. Default small. + statusChallengeRateLimit: z.coerce.number().int().min(0).optional().default(10), httpCertPath: z.string().optional(), httpKeyPath: z.string().optional() }) .passthrough() .superRefine((data, ctx) => { + // Lever B (plan §17.1): enabling cross-node tokens with an EMPTY allowlist is a clear + // misconfiguration (it would honor any foreign issuer) — fail fast, the node must not start. + if ( + data.allowCrossNodeTokens === true && + (!Array.isArray(data.trustedTokenIssuers) || data.trustedTokenIssuers.length === 0) + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: + 'ALLOW_CROSS_NODE_TOKENS is true but TRUSTED_TOKEN_ISSUERS is empty. Enabling cross-node ' + + 'token validation requires a non-empty allowlist of issuer peerIds. Set TRUSTED_TOKEN_ISSUERS ' + + 'or disable ALLOW_CROSS_NODE_TOKENS.', + path: ['trustedTokenIssuers'] + }) + } if (!data.hasHttp && !data.hasP2P) { ctx.addIssue({ code: z.ZodIssueCode.custom, diff --git a/src/utils/constants.ts b/src/utils/constants.ts index 4a38bb5cd..9eefb3857 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -135,6 +135,66 @@ export const SUPPORTED_PROTOCOL_COMMANDS: string[] = [ PROTOCOL_COMMANDS.SET_MAINTENANCE ] +// ────────────────────────────────────────────────────────────────────────────────────────── +// Scoped auth tokens (plan §5.3 / §15.2 / §16 / §18.1) +// ────────────────────────────────────────────────────────────────────────────────────────── + +// Commands that may NOT appear in an auth-token `scope`. A client scoping to one of these is +// rejected at creation (§5.3). This is a client-UX / belt-and-suspenders gate — the real +// protection for DECRYPT_DDO and mutating-admin is TOKEN_INELIGIBLE_COMMANDS below. +// +// NOTE: the mirror of this list lives in ocean.js (`TOKEN_SCOPE_DISALLOWED`). There is no shared +// package, so the two are kept in sync by hand — change both together. +// +// fetchConfig / getLogs are the two READ-ONLY admin commands and are intentionally NOT here: +// they are scopable (an admin can mint `[getLogs, fetchConfig]` for a monitoring tool); the +// ALLOWED_ADMINS gate still applies at consumption. +export const DISALLOWED_TOKEN_SCOPE_COMMANDS: string[] = [ + // per-resource ON-02 signature model, never a reusable bearer grant + PROTOCOL_COMMANDS.DECRYPT_DDO, + // mutating admin — destructive / fund-moving / config-changing + PROTOCOL_COMMANDS.STOP_NODE, + PROTOCOL_COMMANDS.STOP_JOB, + PROTOCOL_COMMANDS.REINDEX_TX, + PROTOCOL_COMMANDS.REINDEX_CHAIN, + PROTOCOL_COMMANDS.HANDLE_INDEXING_THREAD, + PROTOCOL_COMMANDS.COLLECT_FEES, + PROTOCOL_COMMANDS.PUSH_CONFIG, + PROTOCOL_COMMANDS.SET_MAINTENANCE, + // auth-management: a token must not be able to mint / revoke / validate tokens + PROTOCOL_COMMANDS.CREATE_AUTH_TOKEN, + PROTOCOL_COMMANDS.INVALIDATE_AUTH_TOKEN, + PROTOCOL_COMMANDS.VALIDATE_AUTH_TOKEN +] + +// The two read-only admin commands that MAY carry an auth token (and be scoped). Every other +// admin command is signature-only (§16.2). +export const TOKEN_READONLY_ADMIN_COMMANDS: string[] = [ + PROTOCOL_COMMANDS.FETCH_CONFIG, + PROTOCOL_COMMANDS.GET_LOGS +] + +// HIGH (§18.1): commands for which a bearer auth token is NEVER accepted at consumption, even an +// UNRESTRICTED token (no scope claim). DECRYPT_DDO must keep its per-resource ON-02 signature +// binding; the mutating-admin commands must require a fresh single-use nonce-bound signature. +// Enforced centrally in `Auth.validateAuthenticationOrToken`. DISALLOWED_TOKEN_SCOPE_COMMANDS is +// the scope-time belt; this set is the consumption-time suspenders. +export const TOKEN_INELIGIBLE_COMMANDS: string[] = [ + PROTOCOL_COMMANDS.DECRYPT_DDO, + PROTOCOL_COMMANDS.STOP_NODE, + PROTOCOL_COMMANDS.STOP_JOB, + PROTOCOL_COMMANDS.REINDEX_TX, + PROTOCOL_COMMANDS.REINDEX_CHAIN, + PROTOCOL_COMMANDS.HANDLE_INDEXING_THREAD, + PROTOCOL_COMMANDS.COLLECT_FEES, + PROTOCOL_COMMANDS.PUSH_CONFIG, + PROTOCOL_COMMANDS.SET_MAINTENANCE +] + +// Creation-time list caps for a scoped token (bounds token size and signing cost, plan §5.3). +export const MAX_TOKEN_AUDIENCE_ENTRIES = 16 +export const MAX_TOKEN_SCOPE_ENTRIES = 32 + // Maintenance (drain) mode. When enabled, the node refuses NEW commitment (compute/service // starts, initialize, extend) but keeps serving already-committed work. The flag persists in // the SQLite config DB under this key and is cached in memory on the OceanNode singleton. @@ -843,6 +903,49 @@ export const ENVIRONMENT_VARIABLES: Record = { name: 'NODE_METRICS_RETENTION_DAYS', value: process.env.NODE_METRICS_RETENTION_DAYS, required: false + }, + // Scoped auth tokens (plan §8) + MAX_TOKEN_LIFETIME: { + // hard cap on auth-token lifetime in SECONDS (default 86400 = 24h). No infinite tokens. + name: 'MAX_TOKEN_LIFETIME', + value: process.env.MAX_TOKEN_LIFETIME, + required: false + }, + TOKEN_REVOCATION_FALLBACK: { + // 'closed' | 'cache' | 'open' — behaviour when a foreign token's issuer is unreachable. + name: 'TOKEN_REVOCATION_FALLBACK', + value: process.env.TOKEN_REVOCATION_FALLBACK, + required: false + }, + TOKEN_SOFTFAIL_GRACE: { + // seconds; soft-fail grace window, consulted only in 'cache' mode. 0 = fail-closed. + name: 'TOKEN_SOFTFAIL_GRACE', + value: process.env.TOKEN_SOFTFAIL_GRACE, + required: false + }, + TOKEN_REVALIDATE_INTERVAL: { + // seconds; how long a positive revocation verdict suppresses re-dialing. 0 = every request. + name: 'TOKEN_REVALIDATE_INTERVAL', + value: process.env.TOKEN_REVALIDATE_INTERVAL, + required: false + }, + ALLOW_CROSS_NODE_TOKENS: { + // lever B master switch (default false): honor FOREIGN (other-issuer) tokens at all. + name: 'ALLOW_CROSS_NODE_TOKENS', + value: process.env.ALLOW_CROSS_NODE_TOKENS, + required: false + }, + TRUSTED_TOKEN_ISSUERS: { + // JSON array of issuer peerIds; federation allowlist. Required non-empty if cross-node is on. + name: 'TRUSTED_TOKEN_ISSUERS', + value: process.env.TRUSTED_TOKEN_ISSUERS, + required: false + }, + STATUS_CHALLENGE_RATE_LIMIT: { + // OJ-03: req/min/caller for the status challenge-signing path (separate bucket). 0 = disabled. + name: 'STATUS_CHALLENGE_RATE_LIMIT', + value: process.env.STATUS_CHALLENGE_RATE_LIMIT, + required: false } } export const CONNECTION_HISTORY_DELETE_THRESHOLD = 300 diff --git a/src/utils/crypt.ts b/src/utils/crypt.ts index 48a8ef39e..af1a71f1a 100644 --- a/src/utils/crypt.ts +++ b/src/utils/crypt.ts @@ -53,6 +53,78 @@ export function buildDecryptDDOSignatureMessage(fields: { ) } +/** + * Scoped auth tokens — SHARED wire contract with ocean.js (companion plan §3). + * + * The signer (ocean.js `buildCreateAuthTokenSignatureMessage`) and the verifier (this repo, via + * `verifySignatureForConsumer`) MUST build byte-identical messages. If one byte of the format + * below changes, both repos change together (see the plan headers). The golden vectors in the + * unit tests of BOTH repos pin these exact bytes. + * + * Current token format version. It is embedded in the SIGNED bytes (`|v:`) AND carried as the + * `v` JWT claim, so token versions are cryptographically domain-separated: a v2 signature can + * never verify as a future v3, and a verifier rejects any `v` it does not implement. + */ +export const AUTH_TOKEN_VERSION = 2 + +/** + * Build the v2 scoped-auth-token signed message (plan §3.2). Shared single source of truth, used + * at creation (`verifySignatureForConsumer`) and at foreign re-verification (`validateRemoteToken`). + * + * message = + * address + nonce + "createAuthToken" + issuerPeerId + * + "|v:" + V + * + "|aud:" + AUD (canonical: dedup via Set, default ascending string sort, comma-joined) + * + "|cmd:" + CMD (same canonicalization over scope command names) + * + "|exp:" + EXP (String(validUntil), epoch-ms integer, required in v2) + * + * Omitted audience/scope collapse to the empty string (unrestricted). Callers never pass `[]` + * (rejected at creation), so an empty segment always means "omitted / unrestricted". + */ +export function buildCreateAuthTokenSignatureMessage(fields: { + address: string + nonce: string | number + issuerPeerId: string + audience?: string[] + scope?: string[] + validUntil: number +}): string { + const aud = + fields.audience && fields.audience.length + ? Array.from(new Set(fields.audience)).sort().join(',') + : '' + const cmd = + fields.scope && fields.scope.length + ? Array.from(new Set(fields.scope)).sort().join(',') + : '' + const V = String(AUTH_TOKEN_VERSION) + return ( + String(fields.address) + + String(fields.nonce) + + String(PROTOCOL_COMMANDS.CREATE_AUTH_TOKEN) + + String(fields.issuerPeerId ?? '') + + '|v:' + + V + + '|aud:' + + aud + + '|cmd:' + + cmd + + '|exp:' + + String(fields.validUntil) + ) +} + +/** + * OJ-03 — domain-separation prefix for the status identity challenge (shared with ocean.js). + * + * The node signs `utf8(STATUS_CHALLENGE_DOMAIN + clientChallenge)` with its libp2p IDENTITY key. + * The fixed prefix guarantees these bytes can never collide with anything else the identity key + * signs (Noise handshakes, future attestations). ocean.js reconstructs the identical + * `prefix + challenge` and verifies with `@libp2p/crypto` `publicKey.verify`. Mirror this exact + * string in ocean.js — do not re-spell it. + */ +export const STATUS_CHALLENGE_DOMAIN = 'ocean-node-status-challenge-v1:' + // convert from string format to EncryptMethod (case insensitive) export function getEncryptMethodFromString(str: string): EncryptMethod { if (!str || str.length === 0) return EncryptMethod.AES // default