mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-03 22:12:01 +09:00
fix(security): require safe defaults for local services and updates
Signed-off-by: luojie <16602829831@163.com>
This commit is contained in:
1 parent
29be054e85
commit
840fed5289
12 files changed
+211
-21
No files matched your search
@@ -1,11 +1,12 @@
|
||||
# For development only
|
||||
# Set MONGODB_URL=mongodb://localhost:27017 in .env.local to use this container
|
||||
# The unauthenticated development database is published on host loopback only.
|
||||
services:
|
||||
mongo:
|
||||
image: mongo:8
|
||||
hostname: mongodb
|
||||
ports:
|
||||
- ${LOCAL_MONGO_PORT:-27017}:27017
|
||||
- "127.0.0.1:${LOCAL_MONGO_PORT:-27017}:27017"
|
||||
command: --replSet rs0 --bind_ip_all #--setParameter notablescan=1
|
||||
mem_limit: "5g"
|
||||
mem_reservation: "3g"
|
||||
|
||||
@@ -230,6 +230,12 @@ Without a token, a loopback server is still unauthenticated: any process on the
|
||||
|
||||
---
|
||||
|
||||
Startup checks report available updates without installing them. To opt in to
|
||||
automatic patch installation, set `RUFLO_AUTO_UPDATE=true` (`1`, `yes` and `on`
|
||||
also work). Minor and major updates remain manual; critical package priority
|
||||
does not bypass an opt-out. CI detection and `CLAUDE_FLOW_AUTO_UPDATE=false`
|
||||
still disable the update check.
|
||||
|
||||
## What You Get
|
||||
|
||||
| Capability | Description |
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { runStartupUpdateCheck } from '../src/update/index.js';
|
||||
import { DEFAULT_CONFIG } from '../src/update/checker.js';
|
||||
import updateCommand from '../src/commands/update.js';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { parse } from 'yaml';
|
||||
|
||||
const mocks = vi.hoisted(() => ({ check: vi.fn(), execute: vi.fn() }));
|
||||
vi.mock('../src/update/checker.js', () => ({
|
||||
DEFAULT_CONFIG: { enabled: true, checkIntervalHours: 24, autoUpdate: { patch: false, minor: false, major: false }, priority: {}, exclude: [] },
|
||||
checkForUpdates: mocks.check,
|
||||
checkSinglePackage: vi.fn(),
|
||||
getInstalledVersion: () => '1.0.0',
|
||||
}));
|
||||
vi.mock('../src/update/executor.js', () => ({
|
||||
executeMultipleUpdates: mocks.execute, executeUpdate: vi.fn(), rollbackUpdate: vi.fn(),
|
||||
getUpdateHistory: vi.fn(), clearHistory: vi.fn(), loadHistory: vi.fn(),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubEnv('RUFLO_AUTO_UPDATE', '');
|
||||
mocks.check.mockResolvedValue({ results: [{ package: '@claude-flow/cli', currentVersion: '1.0.0', latestVersion: '1.0.1', updateType: 'patch', shouldAutoUpdate: true, priority: 'critical' }], skipped: false });
|
||||
mocks.execute.mockResolvedValue([{ package: '@claude-flow/cli', version: '1.0.1', success: true }]);
|
||||
});
|
||||
afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); });
|
||||
|
||||
describe('startup update installation policy', () => {
|
||||
it('still reports available updates but does not install them without opt-in', async () => {
|
||||
const result = await runStartupUpdateCheck({});
|
||||
expect(result.checked).toBe(true);
|
||||
expect(result.updatesAvailable).toHaveLength(1);
|
||||
expect(result.updatesApplied).toEqual([]);
|
||||
expect(mocks.execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['1', 'true', ' YES ', 'On'])('accepts the explicit environment opt-in %s', async value => {
|
||||
vi.stubEnv('RUFLO_AUTO_UPDATE', value);
|
||||
expect((await runStartupUpdateCheck({})).updatesApplied).toEqual(['@claude-flow/cli@1.0.1']);
|
||||
expect(mocks.check).toHaveBeenCalledWith(expect.objectContaining({ autoUpdate: { patch: true, minor: false, major: false } }));
|
||||
expect(mocks.execute).toHaveBeenCalledTimes(1);
|
||||
expect(DEFAULT_CONFIG.autoUpdate.patch).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['0', 'false', 'off', 'not-enabled'])('does not install for %s', async value => {
|
||||
vi.stubEnv('RUFLO_AUTO_UPDATE', value);
|
||||
expect((await runStartupUpdateCheck({})).updatesApplied).toEqual([]);
|
||||
expect(mocks.execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lets explicit options override environment settings in both directions', async () => {
|
||||
vi.stubEnv('RUFLO_AUTO_UPDATE', 'true');
|
||||
await runStartupUpdateCheck({ autoUpdate: false });
|
||||
expect(mocks.execute).not.toHaveBeenCalled();
|
||||
vi.stubEnv('RUFLO_AUTO_UPDATE', 'false');
|
||||
await runStartupUpdateCheck({ autoUpdate: true });
|
||||
expect(mocks.execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reports the same opt-in policy in update check without installing packages', async () => {
|
||||
vi.stubEnv('RUFLO_AUTO_UPDATE', 'true');
|
||||
mocks.check.mockImplementation(async config => ({
|
||||
skipped: false,
|
||||
results: [{ package: '@claude-flow/cli', updateType: 'patch', shouldAutoUpdate: config.autoUpdate.patch }],
|
||||
}));
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
const command = updateCommand.subcommands!.find(item => item.name === 'check')!;
|
||||
await command.action!({ args: [], flags: { json: true }, cwd: process.cwd(), interactive: false });
|
||||
expect(JSON.parse(log.mock.calls[0][0] as string)[0].shouldAutoUpdate).toBe(true);
|
||||
expect(mocks.execute).not.toHaveBeenCalled();
|
||||
expect(DEFAULT_CONFIG.autoUpdate.patch).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the CLI entry point from forcing startup installation', () => {
|
||||
const source = readFileSync(new URL('../src/index.ts', import.meta.url), 'utf8');
|
||||
expect(source).not.toMatch(/runStartupUpdateCheck\(\{\s*autoUpdate:\s*true\s*\}\)/);
|
||||
});
|
||||
|
||||
it('publishes the development Mongo service only on loopback', () => {
|
||||
const compose = parse(readFileSync(new URL('../../../../ruflo/src/ruvocal/docker-compose.yml', import.meta.url), 'utf8'));
|
||||
const ports = compose.services.mongo.ports as string[];
|
||||
expect(ports).toHaveLength(1);
|
||||
const resolved = ports[0].replace('${LOCAL_MONGO_PORT:-27017}', '27118').split(':');
|
||||
expect(resolved).toEqual(['127.0.0.1', '27118', '27017']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { DEFAULT_CONFIG, checkSinglePackage, checkForUpdates } from '../src/update/checker.js';
|
||||
|
||||
vi.mock('node:module', () => ({
|
||||
createRequire: () => Object.assign(() => ({ version: '1.0.0' }), { resolve: () => 'fixture-package.json' }),
|
||||
}));
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
|
||||
|
||||
describe('package patch updates require opt-in regardless of priority', () => {
|
||||
it('disables automatic patch installation by default', () => {
|
||||
expect(DEFAULT_CONFIG.autoUpdate.patch).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['critical', 'high', 'normal', 'low'] as const)('honors opt-out for %s packages', async priority => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ 'dist-tags': { latest: '1.0.1' } }) })));
|
||||
const config = { ...DEFAULT_CONFIG, autoUpdate: { patch: false, minor: false, major: false }, priority: { '@claude-flow/cli': priority } };
|
||||
expect(await checkSinglePackage('@claude-flow/cli', config)).toMatchObject({ updateType: 'patch', shouldAutoUpdate: false });
|
||||
expect(await checkSinglePackage('@claude-flow/cli', { ...config, autoUpdate: { ...config.autoUpdate, patch: true } })).toMatchObject({ shouldAutoUpdate: true });
|
||||
});
|
||||
|
||||
it.each(['CI', 'CLAUDE_FLOW_AUTO_UPDATE'])('preserves the %s disable gate with the new opt-in present', async name => {
|
||||
vi.stubEnv('CI', '');
|
||||
vi.stubEnv('CONTINUOUS_INTEGRATION', '');
|
||||
vi.stubEnv('RUFLO_AUTO_UPDATE', 'true');
|
||||
vi.stubEnv(name, name === 'CI' ? '1' : 'false');
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
expect(await checkForUpdates({ ...DEFAULT_CONFIG, autoUpdate: { patch: true, minor: false, major: false } })).toMatchObject({ skipped: true, results: [] });
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
clearHistory,
|
||||
} from '../update/executor.js';
|
||||
import { clearCache } from '../update/rate-limiter.js';
|
||||
import { resolveStartupUpdateConfig } from '../update/index.js';
|
||||
|
||||
// Helper functions
|
||||
function formatUpdateType(type: string): string {
|
||||
@@ -66,7 +67,7 @@ const checkCommand: Command = {
|
||||
}
|
||||
|
||||
try {
|
||||
const { results, skipped, reason } = await checkForUpdates(DEFAULT_CONFIG);
|
||||
const { results, skipped, reason } = await checkForUpdates(resolveStartupUpdateConfig());
|
||||
|
||||
if (skipped) {
|
||||
output.printInfo(`Update check skipped: ${reason}`);
|
||||
|
||||
@@ -545,7 +545,7 @@ export class CLI {
|
||||
*/
|
||||
private async checkForUpdatesOnStartup(): Promise<void> {
|
||||
try {
|
||||
const result = await runStartupUpdateCheck({ autoUpdate: true });
|
||||
const result = await runStartupUpdateCheck({});
|
||||
|
||||
// Show notifications for available updates that weren't auto-applied
|
||||
if (result.checked && result.updatesAvailable.length > 0) {
|
||||
|
||||
@@ -33,7 +33,7 @@ const DEFAULT_CONFIG: UpdateConfig = {
|
||||
enabled: true,
|
||||
checkIntervalHours: 24,
|
||||
autoUpdate: {
|
||||
patch: true,
|
||||
patch: false,
|
||||
minor: false,
|
||||
major: false,
|
||||
},
|
||||
@@ -112,16 +112,10 @@ export function getUpdateType(
|
||||
|
||||
function shouldAutoUpdate(
|
||||
updateType: 'major' | 'minor' | 'patch' | 'none',
|
||||
priority: 'critical' | 'high' | 'normal' | 'low',
|
||||
config: UpdateConfig
|
||||
): boolean {
|
||||
if (updateType === 'none') return false;
|
||||
|
||||
// Critical security packages always auto-update patches
|
||||
if (priority === 'critical' && updateType === 'patch') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check config
|
||||
if (updateType === 'major') return config.autoUpdate.major;
|
||||
if (updateType === 'minor') return config.autoUpdate.minor;
|
||||
@@ -220,7 +214,7 @@ export async function checkForUpdates(
|
||||
latestVersion,
|
||||
updateType,
|
||||
priority,
|
||||
shouldAutoUpdate: shouldAutoUpdate(updateType, priority, config),
|
||||
shouldAutoUpdate: shouldAutoUpdate(updateType, config),
|
||||
});
|
||||
})
|
||||
);
|
||||
@@ -262,7 +256,7 @@ export async function checkSinglePackage(
|
||||
latestVersion,
|
||||
updateType,
|
||||
priority,
|
||||
shouldAutoUpdate: shouldAutoUpdate(updateType, priority, config),
|
||||
shouldAutoUpdate: shouldAutoUpdate(updateType, config),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* Features:
|
||||
* - Rate-limited update checks (24h default)
|
||||
* - Automatic patch updates for security packages
|
||||
* - Explicitly opted-in patch updates
|
||||
* - Compatibility validation before updates
|
||||
* - Rollback capability
|
||||
* - Update history logging
|
||||
@@ -45,10 +45,21 @@ export type { UpdateHistoryEntry, UpdateExecutionResult } from './executor.js';
|
||||
|
||||
// Re-export a convenience function for startup
|
||||
import { checkForUpdates, DEFAULT_CONFIG } from './checker.js';
|
||||
import type { UpdateCheckResult } from './checker.js';
|
||||
import type { UpdateCheckResult, UpdateConfig } from './checker.js';
|
||||
import { executeMultipleUpdates } from './executor.js';
|
||||
import { getInstalledVersion } from './checker.js';
|
||||
|
||||
/** Resolve the same opt-in policy for startup and update diagnostics. */
|
||||
export function resolveStartupUpdateConfig(options: { autoUpdate?: boolean } = {}): UpdateConfig {
|
||||
const autoUpdate = options.autoUpdate === undefined
|
||||
? /^(1|true|yes|on)$/i.test((process.env.RUFLO_AUTO_UPDATE ?? '').trim())
|
||||
: options.autoUpdate === true;
|
||||
return {
|
||||
...DEFAULT_CONFIG,
|
||||
autoUpdate: { ...DEFAULT_CONFIG.autoUpdate, patch: autoUpdate },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Run auto-update check on startup
|
||||
* This is the main entry point for the auto-update system
|
||||
@@ -56,7 +67,7 @@ import { getInstalledVersion } from './checker.js';
|
||||
export async function runStartupUpdateCheck(options: {
|
||||
verbose?: boolean;
|
||||
autoUpdate?: boolean;
|
||||
}): Promise<{
|
||||
} = {}): Promise<{
|
||||
checked: boolean;
|
||||
updatesAvailable: UpdateCheckResult[];
|
||||
updatesApplied: string[];
|
||||
@@ -70,7 +81,8 @@ export async function runStartupUpdateCheck(options: {
|
||||
};
|
||||
|
||||
try {
|
||||
const { results, skipped, reason } = await checkForUpdates(DEFAULT_CONFIG);
|
||||
const config = resolveStartupUpdateConfig(options);
|
||||
const { results, skipped, reason } = await checkForUpdates(config);
|
||||
|
||||
if (skipped) {
|
||||
result.skippedReason = reason;
|
||||
@@ -81,7 +93,7 @@ export async function runStartupUpdateCheck(options: {
|
||||
result.updatesAvailable = results;
|
||||
|
||||
// Auto-update if enabled
|
||||
if (options.autoUpdate !== false) {
|
||||
if (config.autoUpdate.patch) {
|
||||
const autoUpdateable = results.filter((r) => r.shouldAutoUpdate);
|
||||
|
||||
if (autoUpdateable.length > 0) {
|
||||
|
||||
@@ -38,6 +38,12 @@ FEDERATION_TRUST_LEVEL=untrusted # default: untrusted
|
||||
|
||||
## Tests
|
||||
|
||||
Handshake signatures cover `ruflo:federation:handshake:v1:` followed by the nonce,
|
||||
not the peer-supplied nonce alone. Signing adapters must sign the supplied bytes
|
||||
unchanged. Both peers must use this context; raw-nonce handshake responses from
|
||||
older peers are rejected, so upgrade federation peers together. This prevents a
|
||||
handshake response from also verifying as a signature over bare envelope bytes.
|
||||
|
||||
325 unit tests covering audit, routing, discovery, plugin lifecycle.
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { generateKeyPairSync, sign, verify } from 'node:crypto';
|
||||
import { HandshakeService, type HandshakeChallenge } from '../../src/domain/services/handshake-service.js';
|
||||
import { FederationNode } from '../../src/domain/entities/federation-node.js';
|
||||
import { canonicalizeEnvelopeForVerify } from '../../src/application/inbound-dispatcher.js';
|
||||
|
||||
const context = 'ruflo:federation:handshake:v1:';
|
||||
const keys = generateKeyPairSync('ed25519');
|
||||
const publicKey = keys.publicKey.export({ format: 'der', type: 'spki' }).subarray(-32).toString('hex');
|
||||
const signBytes = (data: string) => sign(null, Buffer.from(data), keys.privateKey).toString('hex');
|
||||
const verifyBytes = (data: string, signature: string) => verify(null, Buffer.from(data), keys.publicKey, Buffer.from(signature, 'hex'));
|
||||
const peer = () => FederationNode.create({ nodeId: 'remote', publicKey, endpoint: 'ws://remote:1',
|
||||
capabilities: { agentTypes: [], maxConcurrentSessions: 1, supportedProtocols: [], complianceModes: [] } });
|
||||
const service = () => new HandshakeService({
|
||||
generateSessionId: () => 'session', generateSessionToken: () => 'token', generateNonce: () => 'nonce',
|
||||
signChallenge: async data => signBytes(data), verifySignature: async (data, signature) => verifyBytes(data, signature),
|
||||
pinnedKeyFor: () => publicKey, getLocalNodeId: () => 'local', getLocalPublicKey: () => publicKey,
|
||||
getLocalCapabilities: () => [],
|
||||
});
|
||||
|
||||
describe('handshake signature domain', () => {
|
||||
it('does not sign arbitrary peer-supplied bytes as another protocol', async () => {
|
||||
const nonce = canonicalizeEnvelopeForVerify({ id: 'message', type: 'task-assignment',
|
||||
payload: { action: 'fixture' }, metadata: { sourceNodeId: 'remote', signatureVersion: 'jcs-v1' } });
|
||||
const challenge: HandshakeChallenge = { challengeId: 'challenge', nonce, timestamp: new Date().toISOString(), sourceNodeId: 'remote', targetNodeId: 'local' };
|
||||
const response = await service().respondToHandshake(challenge);
|
||||
expect(verifyBytes(nonce, response.signedNonce)).toBe(false);
|
||||
expect(verifyBytes(context + nonce, response.signedNonce)).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts a correctly prefixed challenge response', async () => {
|
||||
const handshake = service();
|
||||
const challenge = await handshake.initiateHandshake(peer());
|
||||
const result = await handshake.verifyChallenge({ challengeId: challenge.challengeId,
|
||||
signedNonce: signBytes(context + challenge.nonce), publicKey, capabilities: [] }, peer());
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.pinned).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects legacy raw-nonce and wrong-domain signatures', async () => {
|
||||
for (const prefix of ['', 'different-protocol:']) {
|
||||
const handshake = service();
|
||||
const challenge = await handshake.initiateHandshake(peer());
|
||||
const result = await handshake.verifyChallenge({ challengeId: challenge.challengeId,
|
||||
signedNonce: signBytes(prefix + challenge.nonce), publicKey, capabilities: [] }, peer());
|
||||
expect(result).toMatchObject({ success: false, error: 'Invalid challenge signature' });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import { FederationNode } from '../entities/federation-node.js';
|
||||
import { FederationSession, type SessionMetrics } from '../entities/federation-session.js';
|
||||
import { TrustLevel } from '../entities/trust-level.js';
|
||||
|
||||
export const HANDSHAKE_SIGNATURE_CONTEXT = 'ruflo:federation:handshake:v1:';
|
||||
|
||||
export interface HandshakeChallenge {
|
||||
readonly challengeId: string;
|
||||
readonly nonce: string;
|
||||
@@ -29,8 +31,9 @@ export interface HandshakeServiceDeps {
|
||||
generateSessionId: () => string;
|
||||
generateSessionToken: () => string;
|
||||
generateNonce: () => string;
|
||||
signChallenge: (nonce: string) => Promise<string>;
|
||||
verifySignature: (nonce: string, signature: string, publicKey: string) => Promise<boolean>;
|
||||
/** Sign/verify the provided domain-bound bytes without adding another prefix. */
|
||||
signChallenge: (payload: string) => Promise<string>;
|
||||
verifySignature: (payload: string, signature: string, publicKey: string) => Promise<boolean>;
|
||||
/** The Ed25519 key (hex) the operator pinned for a node id. Without a pin, a handshake proves nothing about who answered. */
|
||||
pinnedKeyFor?: (nodeId: string) => string | undefined;
|
||||
getLocalNodeId: () => string;
|
||||
@@ -83,7 +86,7 @@ export class HandshakeService {
|
||||
}
|
||||
|
||||
async respondToHandshake(challenge: HandshakeChallenge): Promise<HandshakeChallengeResponse> {
|
||||
const signedNonce = await this.deps.signChallenge(challenge.nonce);
|
||||
const signedNonce = await this.deps.signChallenge(HANDSHAKE_SIGNATURE_CONTEXT + challenge.nonce);
|
||||
|
||||
return {
|
||||
challengeId: challenge.challengeId,
|
||||
@@ -123,7 +126,7 @@ export class HandshakeService {
|
||||
}
|
||||
|
||||
const isValid = await this.deps.verifySignature(
|
||||
pending.challenge.nonce,
|
||||
HANDSHAKE_SIGNATURE_CONTEXT + pending.challenge.nonce,
|
||||
response.signedNonce,
|
||||
response.publicKey,
|
||||
);
|
||||
|
||||
@@ -69,6 +69,7 @@ export {
|
||||
} from './domain/services/discovery-service.js';
|
||||
export {
|
||||
HandshakeService,
|
||||
HANDSHAKE_SIGNATURE_CONTEXT,
|
||||
type HandshakeChallenge,
|
||||
type HandshakeChallengeResponse,
|
||||
type HandshakeResult,
|
||||
|
||||
Reference in new issue
Block a user