Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
83 commits
Select commit Hold shift + click to select a range
b389ff2
security: add explicit admin, peer auth and request limit middleware
csecrestjr Nov 3, 2026
f2a778d
security: add explicit admin, peer auth and request limit middleware
csecrestjr Nov 3, 2026
1eb26b8
security: add explicit admin, peer auth and request limit middleware
csecrestjr Nov 3, 2026
6e72ca6
security: enforce user and administrator access boundaries
csecrestjr Nov 3, 2026
33ff578
security: enforce user and administrator access boundaries
csecrestjr Nov 3, 2026
982bf91
security: enforce user and administrator access boundaries
csecrestjr Nov 3, 2026
5a98b03
security: enforce user and administrator access boundaries
csecrestjr Nov 3, 2026
4d5b990
security: authenticate federation peers and prevent user record overw…
csecrestjr Nov 3, 2026
6db7ea9
security: authenticate federation peers and prevent user record overw…
csecrestjr Nov 3, 2026
395beea
security: authenticate federation peers and prevent user record overw…
csecrestjr Nov 3, 2026
9b2107c
security: fail closed on unauthenticated streams and apply request li…
csecrestjr Nov 3, 2026
3ec6f33
build: add express-rate-limit dependency
csecrestjr Nov 3, 2026
9eb467c
build: lock express-rate-limit dependency
csecrestjr Nov 3, 2026
1516385
docs: document federation peer and CORS configuration
csecrestjr Nov 3, 2026
a9d843a
security: authenticate federation sync and support shared Redis reque…
csecrestjr Nov 3, 2026
eb9d6ef
security: support shared Redis-backed request limits
csecrestjr Nov 3, 2026
2b15f99
build: declare Redis client for distributed rate limits
csecrestjr Nov 3, 2026
32e8a65
build: synchronize Redis client lockfile dependency
csecrestjr Nov 3, 2026
21d8036
docs: add Redis rate-limit deployment configuration
csecrestjr Nov 3, 2026
bda40d0
test: expose limiter factory for isolated regression coverage
csecrestjr Nov 3, 2026
5a2db08
fix: preserve existing signup password compatibility
csecrestjr Nov 3, 2026
babfc72
fix: keep administrative provisioning compatible with existing passwo…
csecrestjr Nov 3, 2026
1fdb801
test: cover user creation authorization and response sanitization
csecrestjr Nov 3, 2026
37ef10c
test: cover federation user sanitization provenance and collisions
csecrestjr Nov 3, 2026
e446441
test: cover federation authentication and rate limiting
csecrestjr Nov 3, 2026
991c232
test: cover federation authentication and rate limiting
csecrestjr Nov 3, 2026
c1f33f4
security: sign and verify federation export responses
csecrestjr Nov 3, 2026
ef8dd74
security: sign allowlisted federation exports
csecrestjr Nov 3, 2026
1f2b3f8
security: verify authenticated federation peer responses
csecrestjr Nov 3, 2026
6f11ad4
fix: load environment before initializing distributed limiter
csecrestjr Nov 3, 2026
246b10f
security: disable unowned upload downloads until attachment authoriza…
csecrestjr Nov 3, 2026
7565903
security: rate limit conversations after authentication
csecrestjr Nov 3, 2026
cf55ff1
security: rate limit messages after authentication
csecrestjr Nov 3, 2026
a779553
test: verify admin route authorization and response allowlists
csecrestjr Nov 3, 2026
3b28d8a
test: verify federation export allowlists and authenticated provenance
csecrestjr Nov 3, 2026
6ff48cc
security: allow explicit API key preflight and remove obsolete path i…
csecrestjr Nov 3, 2026
89e9de3
security: scope federation limits by authenticated peer identity
csecrestjr Nov 3, 2026
8d2a867
security: authenticate federation peers before applying peer request …
csecrestjr Nov 3, 2026
34b4db9
security: route federation through peer auth before general account auth
csecrestjr Nov 3, 2026
99f14fc
security: use distinct credentials for each outbound federation peer
csecrestjr Nov 3, 2026
c7cb347
docs: document per-peer federation secrets
csecrestjr Nov 3, 2026
ef57f27
fix: correct upload shutdown and federation router order
csecrestjr Nov 3, 2026
6dfba1a
fix: remove federation response signing variable redeclaration
csecrestjr Nov 3, 2026
47ee4e7
test: correct federation route test module paths
csecrestjr Nov 3, 2026
c78d708
fix: finalize fail-closed legacy endpoints and single federation mount
csecrestjr Nov 3, 2026
7ff65fd
fix: validate federation response timestamp as ten decimal digits
csecrestjr Nov 3, 2026
5e00460
security: share limiter Redis client with concurrent stream reservations
csecrestjr Nov 3, 2026
ecd1ba9
docs: clarify Redis requirement for distributed streams and limits
csecrestjr Nov 3, 2026
7db451d
security: provide shared-store chat rate limiter for chat auth routes
csecrestjr Nov 3, 2026
7d90754
security: add shared active-stream cap with Redis reservations
csecrestjr Nov 3, 2026
a8fe74c
test: cover open stream limits and disconnect slot release
csecrestjr Nov 3, 2026
98654a6
security: place shared chat limiter after authentication
csecrestjr Nov 3, 2026
ff836d0
security: place shared message limiter after authentication
csecrestjr Nov 3, 2026
d088320
fix: retain stale stream reservations long enough to cover JWT lifetime
csecrestjr Nov 3, 2026
163a6df
docs: specify account federation and distributed limiter rollout
csecrestjr Nov 3, 2026
fc9c983
security: declare rate limiter explicitly on conversation routes
csecrestjr Nov 3, 2026
9a7aea5
security: declare rate limiter explicitly on communication routes
csecrestjr Nov 3, 2026
dab2fb3
ci: run backend tests and whitespace checks for security PRs
csecrestjr Nov 3, 2026
8db3eac
test: authenticate admin route fixtures and assert secret-free DTOs
csecrestjr Nov 3, 2026
d2a100e
test: exercise admin authorization in legacy route regression suite
csecrestjr Nov 3, 2026
21154da
test: verify signed federation sync and reject invalid peers
csecrestjr Nov 3, 2026
85abdb8
security: sanitize admin key records with explicit output allowlist
csecrestjr Nov 3, 2026
41b11df
fix: expose throttled account signup and login before API-key middleware
csecrestjr Nov 3, 2026
3c78d9a
security: rate limit public registration and login attempts by source IP
csecrestjr Nov 3, 2026
e82597a
test: update federation import regression to authenticated provenance…
csecrestjr Nov 3, 2026
709fd2f
security: bind rate limiting to every conversation route handler
csecrestjr Nov 3, 2026
1b659d9
security: bind rate limiting to every message route handler
csecrestjr Nov 3, 2026
fae72a2
security: require account bearer identity for private chat APIs
csecrestjr Nov 3, 2026
9a4c5e7
security: deny API-key-only access to private conversations
csecrestjr Nov 3, 2026
c14ffc8
security: deny API-key-only access to private messages
csecrestjr Nov 3, 2026
c342c9b
security: add IP-based federation authentication attempt budget
csecrestjr Nov 3, 2026
b829bde
security: throttle federation requests before and after peer authenti…
csecrestjr Nov 3, 2026
f738e14
test: ensure shared API keys cannot access private chat endpoints
csecrestjr Nov 3, 2026
45eb5ae
docs: document private chat identity and federation attempt limits
csecrestjr Nov 3, 2026
68dda7a
test: expect shared API keys to be rejected by private chat routes
csecrestjr Nov 3, 2026
dfd874d
test: expect 401 for missing private chat account token
csecrestjr Nov 3, 2026
c70162d
test: reject JWTs without user identity at chat auth boundary
csecrestjr Nov 3, 2026
e447827
security: inline per-account limiter on every conversation handler
csecrestjr Nov 3, 2026
776ce47
security: inline per-account limiter on every message handler
csecrestjr Nov 3, 2026
3161815
test: apply explicit rate limit to protected chat auth fixture
csecrestjr Nov 3, 2026
9a84ea5
security: throttle chat requests by IP before JWT authorization
csecrestjr Nov 3, 2026
9a218f9
security: throttle message requests by IP before JWT authorization
csecrestjr Nov 3, 2026
6b3e2fd
test: mirror pre-auth and per-account chat rate limits
csecrestjr Nov 3, 2026
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
34 changes: 34 additions & 0 deletions .github/workflows/security-hardening.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Security hardening regression

on:
pull_request:
branches: [main]
paths:
- 'backend/**'
- '.github/workflows/security-hardening.yml'

permissions:
contents: read

jobs:
backend-regression:
runs-on: ubuntu-latest
defaults:
run:
working-directory: backend
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
cache-dependency-path: backend/package-lock.json
- name: Install exact lockfile dependencies
run: npm ci
- name: Run complete backend test suite
run: npm test
- name: Check whitespace errors across the PR
working-directory: .
run: git diff --check origin/main...HEAD
14 changes: 14 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,17 @@ STRIPE_KEY=
UI_STRING=Fruitful_app
NODE_ID=backend-node-01
NODE_TYPE=backend

# Comma-separated exact browser origins allowed to call this API.
CORS_ALLOWED_ORIGINS=https://www.ntari.org

# Federation peer authentication (use random secrets of at least 32 characters).
# FEDERATION_LOCAL_NODE_ID=backend-node-01
# FEDERATION_OUTBOUND_PEERS_JSON={"peer-node-01":"replace-with-peer-specific-32-byte-secret"}
# FEDERATION_PEERS_JSON={"remote-node-01":"replace-with-that-peer's-32-byte-secret"}

# Shared store for distributed rate limits (required for multiple server instances).
# REDIS_URL=redis://localhost:6379
# Set true in multi-instance deployments to fail startup if Redis is missing.
# The same Redis instance backs request counters and concurrent stream reservations.
RATE_LIMIT_REDIS_REQUIRED=false
110 changes: 31 additions & 79 deletions backend/__tests__/message_retries.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,30 +148,35 @@ test('invalid keys are rejected before persistence or AI work', async () => {
assert.equal(aiCalls, 0);
});

for (const apiCaller of [false, true]) {
test(`parallel ${apiCaller ? 'API-key' : 'JWT'} retries cannot acquire a second send while the first AI response is running`, async () => {
const auth = apiCaller ? { apiKey: process.env.API_KEY } : {};
let started, finish;
const running = new Promise(resolve => { started = resolve; });
const release = new Promise(resolve => { finish = resolve; });
setClient({ chat: { completions: { create: async () => {
aiCalls++;
started();
await release;
return (async function* () { yield { choices: [{ delta: { content: 'Ready' } }] }; })();
} } } });
const first = send(auth).then(response => response);
await running;
const racing = await Promise.all(Array.from({ length: 8 }, () => send(auth)));
finish();
const done = await first;
assert.ok(racing.every(response => response.status === 409 && response.body.code === 'message_send_pending'));
assert.deepEqual((await send(auth)).body, done.body);
assert.equal(messages().length, 2);
assert.equal(aiCalls, 1);
assert.equal(emitted.length, 2);
});
}
test('parallel JWT retries cannot acquire a second send while the first AI response is running', async () => {
let started, finish;
const running = new Promise(resolve => { started = resolve; });
const release = new Promise(resolve => { finish = resolve; });
setClient({ chat: { completions: { create: async () => {
aiCalls++;
started();
await release;
return (async function* () { yield { choices: [{ delta: { content: 'Ready' } }] }; })();
} } } });
const first = send().then(response => response);
await running;
const racing = await Promise.all(Array.from({ length: 8 }, () => send()));
finish();
const done = await first;
assert.ok(racing.every(response => response.status === 409 && response.body.code === 'message_send_pending'));
assert.deepEqual((await send()).body, done.body);
assert.equal(messages().length, 2);
assert.equal(aiCalls, 1);
assert.equal(emitted.length, 2);
});

test('shared API-key-only callers are rejected before message or AI work', async () => {
const response = await send({ apiKey: process.env.API_KEY });
assert.equal(response.status, 401);
assert.equal(response.body.error, 'Account bearer token required');
assert.equal(messages().length, 0);
assert.equal(aiCalls, 0);
});

test('completed receipts survive reloading the request handler', async () => {
const first = await send();
Expand Down Expand Up @@ -203,59 +208,6 @@ test('changing sender label, recipient, type or attachment conflicts, without re
assert.equal(aiCalls, 1);
});

test('API-key callers replay within their credential scope and do not share JWT receipts', async () => {
const first = await send({ apiKey: process.env.API_KEY });
assert.deepEqual((await send({ apiKey: process.env.API_KEY })).body, first.body);
const user = await send();
assert.equal(user.status, 201);
assert.notEqual(user.body.message.id, first.body.message.id);
assert.equal(aiCalls, 2);
});

test('API-key receipts use the stable scrypt scope instead of a fast credential hash', async () => {
const first = await send({ apiKey: process.env.API_KEY });
assert.equal(first.status, 201);
const [receipt] = db.tables.get('MessageSends').values();
// Independent Python hashlib.scrypt fixture: password=test-only-api-key,
// salt=SHA256(JSON([message-send-api-key-v2, conversation-1, send-1])).hex,
// N=16384, r=8, p=5, dklen=32. Locks the durable replay namespace.
assert.equal(receipt.id, 'e54be044e9e970d309de6ebe2b3763f1cbb49c546d04c7379102ba52709867e6');
assert.ok(!JSON.stringify(receipt).includes(process.env.API_KEY));
delete require.cache[require.resolve('../services/retrySafeMessage')];
delete require.cache[require.resolve('../controllers/communication_controller')];
delete require.cache[require.resolve('../routes/communicationRoutes')];
app = makeApp();
assert.deepEqual((await send({ apiKey: process.env.API_KEY })).body, first.body);
assert.equal(aiCalls, 1);
});

test('API-key rotation, conversation and send keys have separate retry scopes', async () => {
const first = await send({ apiKey: process.env.API_KEY });
const otherConversation = await send({ apiKey: process.env.API_KEY, conversation: 'conversation-2' });
const otherSend = await send({ apiKey: process.env.API_KEY, key: 'send-2' });
process.env.API_KEY = 'rotated-test-api-key';
const rotated = await send({ apiKey: process.env.API_KEY });
for (const response of [first, otherConversation, otherSend, rotated]) assert.equal(response.status, 201);
assert.equal(new Set([first, otherConversation, otherSend, rotated].map(response => response.body.message.id)).size, 4);
assert.deepEqual((await send({ apiKey: process.env.API_KEY })).body, rotated.body);
assert.equal(aiCalls, 4);
});

test('WIX API-key retries work without a JWT secret', async () => {
const priorWixKey = process.env.WIX_API_KEY;
delete process.env.API_KEY;
delete process.env.JWT_SECRET;
process.env.WIX_API_KEY = 'test-only-wix-api-key';
try {
const first = await send({ apiKey: process.env.WIX_API_KEY });
assert.equal(first.status, 201);
assert.deepEqual((await send({ apiKey: process.env.WIX_API_KEY })).body, first.body);
assert.equal(aiCalls, 1);
} finally {
if (priorWixKey === undefined) delete process.env.WIX_API_KEY; else process.env.WIX_API_KEY = priorWixKey;
}
});

test('an invalid API-key header cannot alter a verified JWT retry scope', async () => {
const first = await send();
const retry = await request(app).post('/messages/conversation-1')
Expand All @@ -268,11 +220,11 @@ test('an invalid API-key header cannot alter a verified JWT retry scope', async
});

test('authentication failures and JWTs without a stable user ID create no receipts', async () => {
assert.equal((await request(app).post('/messages/conversation-1').set('Idempotency-Key', 'key').send(payload)).status, 403);
assert.equal((await request(app).post('/messages/conversation-1').set('Idempotency-Key', 'key').send(payload)).status, 401);
const noIdentity = await request(app).post('/messages/conversation-1')
.set('Authorization', `Bearer ${jwt.sign({ role: 'member' }, process.env.JWT_SECRET)}`)
.set('Idempotency-Key', 'key').send(payload);
assert.equal(noIdentity.status, 400);
assert.equal(noIdentity.status, 401);
assert.equal(db.tables.size, 0);
});

Expand Down
13 changes: 7 additions & 6 deletions backend/__tests__/routes/admin.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,21 @@ jest.mock('../../lib/dynamodbClient', () => ({ scan: jest.fn() }));
const docClient = require('../../lib/dynamodbClient');
const adminRouter = require('../../routes/admin');
const app = express();
app.use((req, _res, next) => { req.user = { userId: 'test-admin', role: 'admin' }; next(); });
app.use('/', adminRouter);

describe.each([
{ route: 'users', table: 'Users', item: { id: 'u1', username: 'Alice' } },
{ route: 'keys', table: 'Keys', item: { id: 'k1', key: 'abc' } },
])('admin GET /$route', ({ route, table, item }) => {
{ route: 'users', table: 'Users', item: { id: 'u1', username: 'Alice', email: 'alice@example.test', role: 'consumer' }, expected: { id: 'u1', username: 'Alice', email: 'alice@example.test', role: 'consumer' } },
{ route: 'keys', table: 'Keys', item: { id: 'k1', userId: 'u1', key: 'secret', usageCount: 2 }, expected: { id: 'k1', userId: 'u1', usageCount: 2 } },
])('admin GET /$route', ({ route, table, item, expected }) => {
beforeEach(() => docClient.scan.mockReset());

test('returns stored records from the expected table', async () => {
test('returns sanitized records from the expected table', async () => {
docClient.scan.mockReturnValue({ promise: async () => ({ Items: [item] }) });
const response = await request(app).get('/' + route);
expect(response.status).toBe(200);
expect(response.body).toEqual([item]);
expect(docClient.scan).toHaveBeenCalledWith({ TableName: table });
expect(response.body).toEqual([expected]);
expect(docClient.scan).toHaveBeenCalledWith(expect.objectContaining({ TableName: table, ProjectionExpression: expect.any(String) }));
});

test('returns 500 on a storage error', async () => {
Expand Down
63 changes: 63 additions & 0 deletions backend/docs/security-hardening.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Agrinet account, federation and request-limit hardening

This branch closes the account-overwrite and unprotected federation paths and prepares the chat PRs to use the same distributed limit store.

## Account and user-response boundaries

- POST /users is administrative provisioning only. It requires a verified JWT principal whose role is admin; the browser/API-key path does not create req.user and cannot pass this check.
- IDs are generated by the server. A supplied id is rejected. DynamoDB writes use attribute_not_exists(id) so a collision cannot replace a prior account.
- Public /users responses are a narrow directory DTO. /api/admin/users requires an administrator and returns an administrative DTO, not a raw DynamoDB row.
- Login responses use the authenticated-account DTO. Password hashes, verification codes and exact coordinates are never included.
- Public signup remains /api/auth/register and uses a conditional create.

## Federation peer authentication

Federation endpoints are mounted before the general browser/API-key middleware and require HMAC peer authentication themselves. They do not accept the shared browser API key as peer identity.

Each peer pair needs a distinct random secret of at least 32 characters:

- FEDERATION_LOCAL_NODE_ID (or existing NODE_ID) is this node's stable identity.
- FEDERATION_OUTBOUND_PEERS_JSON maps each remote NodeRegistry.nodeId to the secret this node uses when contacting that peer.
- FEDERATION_PEERS_JSON maps authorized inbound sender node IDs to their matching shared secrets.

For A to synchronize with B, A's outbound entry for B must match B's inbound entry for A. The reverse direction can use a different secret. Never put these values in browser code or commit a real .env file. Keep node clocks synchronized; signed requests and responses have a five-minute clock-skew window.

Requests sign the timestamp, HTTP method, path and SHA-256 digest of the exact request body. Export responses are also signed and checked against the node ID in the local NodeRegistry record. Production peers must use HTTPS; HTTP is accepted only for loopback development.

Federation user imports accept an explicit user-field allowlist, reject existing IDs atomically, strip passwords, contact fields, roles and verification state, and record sourceNodeId from the authenticated peer plus remoteUserId. Claimed origin identifiers are retained as provenance metadata from the signed peer payload; they never determine the authenticated sender.

Exports use explicit field allowlists. The location feature's exact owner coordinates remain in its separate local Locations table and are not part of the user export.

## Distributed request and connection limits

express-rate-limit is used for API, user writes, location, chat, stream and federation traffic. Chat routes require an account JWT (`chatAuth`); the shared browser/API key is explicitly rejected for private chat. Authenticated requests are keyed by req.user.userId; authenticated peers by req.federationPeer.nodeId; application-key traffic without a user identity falls back to source IP.

When REDIS_URL is configured, request counters and concurrent-stream reservations use Redis and are shared across instances. In a multi-instance deployment, set RATE_LIMIT_REDIS_REQUIRED=true so the service refuses to start without the shared store. Without Redis, counters and stream slots are process-local and suitable only for a documented single-instance deployment.

backend/middleware/chatRateLimit.js is intended to be mounted after chatAuth. backend/middleware/streamConcurrency.js provides a five-stream-per-account reservation. The authenticated-stream PR should wire the stream route in this order:

1. chatAuth
2. chatRateLimit(60)
3. createConcurrentStreamLimit({ maximum: 5 })
4. conversationStreams.open

The concurrency middleware releases a reservation on response close/finish and Redis reservations expire to recover from process crashes.

## Temporary fail-closed behavior and merge order

Until the owner-checked chat changes are deployed:

- /events and /stream/:conversationId return 410 instead of exposing the legacy unauthenticated feed.
- /uploads returns 410 instead of serving files to any caller holding the shared browser key.

After #191 is rebased and approved, restore attachment serving only behind chatAuth, the shared chat limiter, and attachmentOwner. After #192 is rebased and approved, replace the temporary stream 410 with the ordered authenticated handler above. Do not restore the old handlers before those protections are present.

No upload-creation endpoint exists in the current main tree; when one is introduced, place upload throttling on that actual write operation, not only on static download paths.

## CORS configuration

Set CORS_ALLOWED_ORIGINS to the exact deployed chat UI/application origins (comma-separated). Do not use * with credentials. The default remains the existing NTARI web origin. Authorization and the required integration/federation headers are explicitly allowed for preflight.

## Verification

The branch adds tests for user/admin response allowlists, non-admin denial, caller-supplied ID rejection, conditional writes, imported-user sanitization and provenance, peer request/response signatures, request limits, and concurrent-stream release. CI should run npm ci, npm test, CodeQL and the location-storage regression workflow on the PR. No local test run is claimed here.
98 changes: 98 additions & 0 deletions backend/federation/__tests__/federationRoutes.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
const express = require('express');
const request = require('supertest');

jest.mock('../../lib/dynamodbClient', () => ({
scan: jest.fn(),
put: jest.fn()
}));

const docClient = require('../../lib/dynamodbClient');
const federationRoutes = require('../federationRoutes');
const { createPeerHeaders, verifyPeerResponse } = require('../../middleware/federationPeerAuth');

describe('federation route security', () => {
const oldEnv = {
peers: process.env.FEDERATION_PEERS_JSON,
node: process.env.NODE_ID,
localNode: process.env.FEDERATION_LOCAL_NODE_ID
};
const secret = '0123456789abcdef0123456789abcdef';
let app;

beforeEach(() => {
process.env.FEDERATION_PEERS_JSON = JSON.stringify({ 'peer-1': secret });
process.env.NODE_ID = 'local-node';
process.env.FEDERATION_LOCAL_NODE_ID = 'local-node';
app = express();
app.use(express.json({ verify(req, _res, buffer) { req.rawBody = Buffer.from(buffer); } }));
app.use('/federation', federationRoutes);
docClient.scan.mockReset();
docClient.put.mockReset();
});

afterAll(() => {
if (oldEnv.peers === undefined) delete process.env.FEDERATION_PEERS_JSON;
else process.env.FEDERATION_PEERS_JSON = oldEnv.peers;
if (oldEnv.node === undefined) delete process.env.NODE_ID;
else process.env.NODE_ID = oldEnv.node;
if (oldEnv.localNode === undefined) delete process.env.FEDERATION_LOCAL_NODE_ID;
else process.env.FEDERATION_LOCAL_NODE_ID = oldEnv.localNode;
});

test('does not export unless the caller proves a configured peer identity', async () => {
const response = await request(app).get('/federation/export');
expect(response.status).toBe(401);
expect(docClient.scan).not.toHaveBeenCalled();
});

test('exports only allowlisted user, listing and transaction fields and signs response', async () => {
docClient.scan
.mockReturnValueOnce({ promise: async () => ({ Items: [{ id: 'l1', title: 'Apples', password: 'secret', internal: 'x' }] }) })
.mockReturnValueOnce({ promise: async () => ({ Items: [{ id: 't1', status: 'pending', cardToken: 'secret' }] }) })
.mockReturnValueOnce({ promise: async () => ({ Items: [{
id: 'u1', username: 'alice', email: 'a@example.test', phone: '555-0100',
password: 'hash', verificationCode: 'secret', role: 'admin', verified: true,
coordinates: { lat: 1, long: 2 }, reputationScore: 3
}] }) });

const headers = createPeerHeaders({
nodeId: 'peer-1', secret, method: 'GET', path: '/federation/export'
});
const response = await request(app).get('/federation/export').set(headers);
expect(response.status).toBe(200);
expect(response.body.users).toEqual([{
id: 'u1', username: 'alice', reputationScore: 3,
originNodeId: 'local-node', originUserId: 'u1'
}]);
expect(response.body.listings).toEqual([{ id: 'l1', title: 'Apples' }]);
expect(response.body.transactions).toEqual([{ id: 't1', status: 'pending' }]);
expect(verifyPeerResponse({
headers: response.headers,
expectedNodeId: 'local-node',
secret,
method: 'GET',
path: '/federation/export',
body: JSON.stringify(response.body)
})).toBe(true);
});

test('import uses the authenticated peer identity, not a body-supplied source id', async () => {
docClient.put.mockReturnValue({ promise: async () => ({}) });
const body = JSON.stringify({
sourceNodeId: 'forged-node',
users: [{ id: 'remote-u1', username: 'bob', role: 'admin', password: 'hash' }]
});
const headers = createPeerHeaders({
nodeId: 'peer-1', secret, method: 'POST', path: '/federation/import', body
});
const response = await request(app).post('/federation/import')
.set(headers).set('Content-Type', 'application/json').send(body);
expect(response.status).toBe(200);
const written = docClient.put.mock.calls[0][0];
expect(written.Item.sourceNodeId).toBe('peer-1');
expect(written.Item.remoteUserId).toBe('remote-u1');
expect(written.Item.role).toBeUndefined();
expect(written.Item.password).toBeUndefined();
expect(written.ConditionExpression).toBe('attribute_not_exists(#id)');
});
});
Loading
Loading