Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions apps/backend/tests/openapi.federate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// SPDX-FileCopyrightText: 2025-2026 Alphin Tom / Mycel UG (haftungsbeschränkt)
// SPDX-License-Identifier: MIT

import { describe, expect, it } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import Fastify from 'fastify';
import { registerLoopProtocolParsers } from '../src/protocol';
import { registerFederateRoutes } from '../src/routes/federate';
import { apiKeyHeader, useTestApiKey } from './testApiKey';

useTestApiKey();

// protocol/openapi.json is the reference contract. The federation routes
// enforce the SPECIFICATION.md §9.2 headers, so the contract must declare each
// of them as a required header and list every status the route can answer;
// it used to declare neither, so a generated client always got an
// undocumented 401.
const openapiPath = join(import.meta.dir, '..', '..', '..', 'protocol', 'openapi.json');
const hasProtocol = existsSync(openapiPath);

type Operation = {
parameters?: { $ref?: string }[];
responses: Record<string, unknown>;
};

const openapi = hasProtocol
? (JSON.parse(readFileSync(openapiPath, 'utf8')) as {
paths: Record<string, { post: Operation }>;
components: { parameters: Record<string, { name: string; in: string; required?: boolean }> };
})
: undefined;

const requiredHeaders = (operation: Operation) =>
(operation.parameters ?? [])
.map((parameter) => openapi!.components.parameters[(parameter.$ref ?? '').split('/').pop() ?? ''])
.filter((parameter) => parameter?.in === 'header' && parameter.required)
.map((parameter) => parameter.name.toLowerCase());

const cases = [
{
path: '/api/v1/federate/announce',
payload: {
'@context': 'https://loop.urbnia.com/projects/loop-protocol/contexts/loop-v0.2.0.jsonld',
'@type': 'MaterialAnnouncement',
material: 'MAT-DE-MUC-2025-FOOD-B847F3',
origin: 'munich.loop',
available: true,
},
},
{
path: '/api/v1/federate/offer',
payload: {
'@context': 'https://loop.urbnia.com/projects/loop-protocol/contexts/loop-v0.2.0.jsonld',
'@type': 'MaterialOffer',
material: 'MAT-DE-MUC-2025-FOOD-B847F3',
from: 'vienna.loop',
base_price: 60,
loop_cost: 104,
valid_until: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
},
},
];

const nodeHeaders = () => ({
'x-node-id': 'munich.loop',
'x-node-signature': 'lab-signature-placeholder',
'x-timestamp': new Date().toISOString(),
});

async function post(path: string, payload: Record<string, unknown>, headers: Record<string, string>) {
const app = Fastify({ logger: false });
registerLoopProtocolParsers(app);
await registerFederateRoutes(app, {
insertLoopEvent: async () => ({ id: 1, created_at: new Date().toISOString() }),
getLoopMaterial: async (id: string) => ({ id }),
broadcastLoopEvent: () => undefined,
});
try {
return await app.inject({ method: 'POST', url: path, headers: { ...apiKeyHeader, ...headers }, payload });
} finally {
await app.close();
}
}

describe.skipIf(!hasProtocol)('openapi.json documents the §9.2 federation headers the routes enforce', () => {
for (const { path, payload } of cases) {
it(`${path} declares X-Node-ID, X-Node-Signature and X-Timestamp as required headers`, () => {
expect(requiredHeaders(openapi!.paths[path]!.post).sort()).toEqual(['x-node-id', 'x-node-signature', 'x-timestamp']);
});

it(`${path} rejects a request missing any declared header, with a documented status`, async () => {
const operation = openapi!.paths[path]!.post;
expect((await post(path, payload, nodeHeaders())).statusCode).toBe(202);
for (const header of requiredHeaders(operation)) {
const headers: Record<string, string> = nodeHeaders();
delete headers[header];
const response = await post(path, payload, headers);
expect([400, 401]).toContain(response.statusCode);
expect(Object.keys(operation.responses)).toContain(String(response.statusCode));
}
const stale = await post(path, payload, { ...nodeHeaders(), 'x-timestamp': new Date(Date.now() - 10 * 60 * 1000).toISOString() });
expect(stale.statusCode).toBe(401);
expect(Object.keys(operation.responses)).toContain('401');
});
}
});
11 changes: 11 additions & 0 deletions apps/site/public/projects/loop-protocol/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

### Fixed
- `openapi.json`: `POST /api/v1/federate/announce` and `/federate/offer`
declare the three headers SPECIFICATION.md §9.2 makes mandatory
(`X-Node-ID`, `X-Node-Signature`, `X-Timestamp`) as required header
parameters (shared under `components.parameters`), and list their `400`
(invalid body, missing or malformed `X-Timestamp`) and `401` (missing node
headers or credentials, stale timestamp) responses. They declared neither,
so a client generated from the contract always received an undocumented
`401`.
- SPECIFICATION.md §8.2: the federate request examples show all three §9.2
headers; they carried only `X-Node-Signature`. The Core-DP normative
manifest is re-pinned for the shifted line numbers (no clause changed).
- `openapi.json`: `POST /api/v1/transaction` documents that a `Settlement` or
`TransactionStatus` updates the existing transaction named by
`transaction_id` (SPECIFICATION.md §3.6), and lists the `400`, `404`
Expand Down
4 changes: 4 additions & 0 deletions apps/site/public/projects/loop-protocol/SPECIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -1069,7 +1069,9 @@ For node-to-node communication:

```http
POST /api/v1/federate/announce
X-Node-ID: {requesting-node-id}
X-Node-Signature: {signature}
X-Timestamp: {ISO 8601 request time}

{
"@context": "https://loop.urbnia.com/projects/loop-protocol/contexts/loop-v0.1.1.jsonld",
Expand All @@ -1084,7 +1086,9 @@ X-Node-Signature: {signature}

```http
POST /api/v1/federate/offer
X-Node-ID: {requesting-node-id}
X-Node-Signature: {signature}
X-Timestamp: {ISO 8601 request time}

{
"@context": "https://loop.urbnia.com/projects/loop-protocol/contexts/loop-v0.1.1.jsonld",
Expand Down
65 changes: 65 additions & 0 deletions apps/site/public/projects/loop-protocol/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,29 @@
}
],
"components": {
"parameters": {
"XNodeId": {
"name": "X-Node-ID",
"in": "header",
"required": true,
"description": "Identifier of the requesting node (SPECIFICATION.md §9.2), e.g. munich.loop.",
"schema": { "type": "string", "minLength": 1 }
},
"XNodeSignature": {
"name": "X-Node-Signature",
"in": "header",
"required": true,
"description": "Signature over the request by the requesting node (SPECIFICATION.md §9.2).",
"schema": { "type": "string", "minLength": 1 }
},
"XTimestamp": {
"name": "X-Timestamp",
"in": "header",
"required": true,
"description": "Request time (SPECIFICATION.md §9.2); a request more than 5 minutes from the receiving node's clock is rejected.",
"schema": { "type": "string", "format": "date-time" }
}
},
"securitySchemes": {
"BearerAuth": {
"type": "http",
Expand Down Expand Up @@ -511,6 +534,11 @@
"post": {
"tags": ["Federation"],
"summary": "Announce material availability",
"parameters": [
{ "$ref": "#/components/parameters/XNodeId" },
{ "$ref": "#/components/parameters/XNodeSignature" },
{ "$ref": "#/components/parameters/XTimestamp" }
],
"requestBody": {
"required": true,
"content": {
Expand All @@ -527,6 +555,22 @@
"schema": { "$ref": "#/components/schemas/FederateAcceptedResponse" }
}
}
},
"400": {
"description": "Invalid request body, or a missing or malformed X-Timestamp",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" }
}
}
},
"401": {
"description": "Missing credentials, missing X-Node-ID or X-Node-Signature, or an X-Timestamp outside the ±5 minute tolerance",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" }
}
}
}
}
}
Expand All @@ -535,6 +579,11 @@
"post": {
"tags": ["Federation"],
"summary": "Send offer to a node",
"parameters": [
{ "$ref": "#/components/parameters/XNodeId" },
{ "$ref": "#/components/parameters/XNodeSignature" },
{ "$ref": "#/components/parameters/XTimestamp" }
],
"requestBody": {
"required": true,
"content": {
Expand All @@ -551,6 +600,22 @@
"schema": { "$ref": "#/components/schemas/FederateAcceptedResponse" }
}
}
},
"400": {
"description": "Invalid request body, or a missing or malformed X-Timestamp",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" }
}
}
},
"401": {
"description": "Missing credentials, missing X-Node-ID or X-Node-Signature, or an X-Timestamp outside the ±5 minute tolerance",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" }
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,7 @@
"id": "REQ-92_NODE_AUTHENTICATION-MUST-66F1F0D8B55D",
"keyword": "MUST",
"source_path": "SPECIFICATION.md",
"source_line": 1155,
"source_line": 1159,
"source_anchor": "92-node-authentication",
"statement_hash": "66f1f0d8b55dfb4fbab3c1faafbf4a6248dece082d5b5dfbce0af10c38feedce",
"statement": "Node-to-node requests MUST include:",
Expand All @@ -759,7 +759,7 @@
"id": "REQ-101_TRANSPORT_SECURITY-MUST-8BCFFBF2D578",
"keyword": "MUST",
"source_path": "SPECIFICATION.md",
"source_line": 1184,
"source_line": 1188,
"source_anchor": "101-transport-security",
"statement_hash": "8bcffbf2d578b358e26b9bff178d4a7f0c50fe371b6536ecd5f992b1362a292e",
"statement": "All connections MUST use TLS 1.3 or higher",
Expand All @@ -773,7 +773,7 @@
"id": "REQ-101_TRANSPORT_SECURITY-MUST-2F77ED40BC8E",
"keyword": "MUST",
"source_path": "SPECIFICATION.md",
"source_line": 1185,
"source_line": 1189,
"source_anchor": "101-transport-security",
"statement_hash": "2f77ed40bc8e62517deb56fa0594c78297bd868f35eb248f75986485d3a0df8d",
"statement": "Nodes MUST validate certificates",
Expand All @@ -787,7 +787,7 @@
"id": "REQ-101_TRANSPORT_SECURITY-REQUIRED-6C7C2240A269",
"keyword": "REQUIRED",
"source_path": "SPECIFICATION.md",
"source_line": 1186,
"source_line": 1190,
"source_anchor": "101-transport-security",
"statement_hash": "6c7c2240a26974acc4072f11d7f1214fb705a8b06646c3bfc2680f0d7dec7d32",
"statement": "Perfect Forward Secrecy REQUIRED",
Expand All @@ -801,7 +801,7 @@
"id": "REQ-102_AUTHENTICATION-MUST-DFC9C0BB6D75",
"keyword": "MUST",
"source_path": "SPECIFICATION.md",
"source_line": 1192,
"source_line": 1196,
"source_anchor": "102-authentication",
"statement_hash": "dfc9c0bb6d75aa17d6de137fb8a91db02f0626ebbfca5ffb436c4fa15c51671c",
"statement": "API tokens MUST expire (recommended: 1 hour)",
Expand All @@ -815,7 +815,7 @@
"id": "REQ-103_DATA_PRIVACY-MUST_NOT-89BA34B57104",
"keyword": "MUST NOT",
"source_path": "SPECIFICATION.md",
"source_line": 1196,
"source_line": 1200,
"source_anchor": "103-data-privacy",
"statement_hash": "89ba34b57104f6a5837879d4f519ca442cff5aa0ccea4abedcf847d31a75cc9a",
"statement": "Personal data MUST NOT be included in MaterialDNA",
Expand All @@ -829,7 +829,7 @@
"id": "REQ-103_DATA_PRIVACY-MUST-498998D417E3",
"keyword": "MUST",
"source_path": "SPECIFICATION.md",
"source_line": 1198,
"source_line": 1202,
"source_anchor": "103-data-privacy",
"statement_hash": "498998d417e369ad110f86a7147bb39914a7d785a531f1ea7d98d080317e6866",
"statement": "Nodes MUST comply with local privacy laws (GDPR, etc.)",
Expand All @@ -843,7 +843,7 @@
"id": "REQ-105_AUDIT_TRAIL-MUST-EA473379C41F",
"keyword": "MUST",
"source_path": "SPECIFICATION.md",
"source_line": 1210,
"source_line": 1214,
"source_anchor": "105-audit-trail",
"statement_hash": "ea473379c41fbc35d332490aef80f6e1091047763ac41c04e104f6a2e32c0db1",
"statement": "Nodes MUST maintain immutable logs of:",
Expand All @@ -857,7 +857,7 @@
"id": "REQ-114_TESTING-MUST-6589C976930E",
"keyword": "MUST",
"source_path": "SPECIFICATION.md",
"source_line": 1247,
"source_line": 1251,
"source_anchor": "114-testing",
"statement_hash": "6589c976930e4966c6a77073403dd381829dbe00b1e98e161b73494af8867e22",
"statement": "Test suite MUST cover:",
Expand All @@ -871,7 +871,7 @@
"id": "REQ-APPENDIX_A_JSON_LD_CONTEXT-MUST-836FA4E4A387",
"keyword": "MUST",
"source_path": "SPECIFICATION.md",
"source_line": 1465,
"source_line": 1469,
"source_anchor": "appendix-a-json-ld-context",
"statement_hash": "836fa4e4a387dc6f6ca01368f59a9b6af925f36a8ec317ccb9121f966d99e850",
"statement": "Implementations MUST treat the published context files as the source of truth.",
Expand Down
11 changes: 11 additions & 0 deletions protocol/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

### Fixed
- `openapi.json`: `POST /api/v1/federate/announce` and `/federate/offer`
declare the three headers SPECIFICATION.md §9.2 makes mandatory
(`X-Node-ID`, `X-Node-Signature`, `X-Timestamp`) as required header
parameters (shared under `components.parameters`), and list their `400`
(invalid body, missing or malformed `X-Timestamp`) and `401` (missing node
headers or credentials, stale timestamp) responses. They declared neither,
so a client generated from the contract always received an undocumented
`401`.
- SPECIFICATION.md §8.2: the federate request examples show all three §9.2
headers; they carried only `X-Node-Signature`. The Core-DP normative
manifest is re-pinned for the shifted line numbers (no clause changed).
- `openapi.json`: `POST /api/v1/transaction` documents that a `Settlement` or
`TransactionStatus` updates the existing transaction named by
`transaction_id` (SPECIFICATION.md §3.6), and lists the `400`, `404`
Expand Down
4 changes: 4 additions & 0 deletions protocol/SPECIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -1069,7 +1069,9 @@ For node-to-node communication:

```http
POST /api/v1/federate/announce
X-Node-ID: {requesting-node-id}
X-Node-Signature: {signature}
X-Timestamp: {ISO 8601 request time}

{
"@context": "https://loop.urbnia.com/projects/loop-protocol/contexts/loop-v0.1.1.jsonld",
Expand All @@ -1084,7 +1086,9 @@ X-Node-Signature: {signature}

```http
POST /api/v1/federate/offer
X-Node-ID: {requesting-node-id}
X-Node-Signature: {signature}
X-Timestamp: {ISO 8601 request time}

{
"@context": "https://loop.urbnia.com/projects/loop-protocol/contexts/loop-v0.1.1.jsonld",
Expand Down
Loading
Loading