Files
homeclaw/tests/claude-fs.test.ts
T

130 lines
8.1 KiB
TypeScript

// 클로드 앱 서버 모드 파일 API(routes-claude-fs.ts) — 관리자/일반 사용자 범위, 차단 규칙, 심볼릭 링크 탈출.
import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import http from 'http';
import express from 'express';
import { registerClaudeFsRoutes, isSecretOrSystemPath } from '../src/gateway/routes/routes-claude-fs';
import { getConfig, getUserWorkspace } from '../src/config/config';
const CFG = getConfig().getConfigDir();
describe('isSecretOrSystemPath — 차단 규칙', () => {
test('시스템 경로/루트 차단', () => {
for (const p of ['/', '/etc', '/etc/passwd', '/proc/1', '/root', '/usr/bin', '/var/lib/x']) assert.ok(isSecretOrSystemPath(p, CFG), p);
});
test('.smallclaw 설정·키·vault·세션 차단, 워크스페이스는 허용', () => {
for (const rel of ['config.json', 'vault/vault.enc', 'active-sessions.json', 'claude-key.txt', 'users/papa/profile.json', 'logs/gateway.log'])
assert.ok(isSecretOrSystemPath(path.join(CFG, rel), CFG), rel);
for (const rel of ['users/papa/workspace', 'users/papa/workspace/workshop/robot/a.txt', 'workspace/x'])
assert.equal(isSecretOrSystemPath(path.join(CFG, rel), CFG), null, rel);
});
test('비밀 파일·폴더 차단', () => {
for (const p of ['/home/u/.ssh/id_rsa', '/srv/app/.env', '/srv/app/.env.production', '/x/server.pem', '/x/my_api_key.txt', '/home/u/.claude/settings.json', '/x/credentials.json'])
assert.ok(isSecretOrSystemPath(p, CFG), p);
});
test('일반 프로젝트 파일은 허용', () => {
for (const p of ['/srv/homeclaw/src/tools/stl-cad.ts', '/tmp/work/readme.md']) assert.equal(isSecretOrSystemPath(p, CFG), null, p);
});
});
describe('HTTP — 관리자/일반 사용자', () => {
let server: http.Server; let base = '';
let role: 'admin' | 'user' = 'admin'; let username = 'zz_claude_fs_test';
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-fs-'));
const ws = getUserWorkspace('zz_claude_fs_test');
const call = async (method: string, url: string, body?: any) => {
const r = await fetch(base + url, { method, headers: { 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined });
return { status: r.status, json: await r.json().catch(() => ({})) as any };
};
before(async () => {
fs.mkdirSync(path.join(tmp, 'proj', 'sub'), { recursive: true });
fs.writeFileSync(path.join(tmp, 'proj', 'a.txt'), 'hello');
fs.writeFileSync(path.join(tmp, 'proj', 'sub', 'b.md'), 'x');
fs.writeFileSync(path.join(tmp, 'proj', '.env'), 'SECRET=1');
fs.writeFileSync(path.join(tmp, 'outside.txt'), 'outside');
fs.symlinkSync(path.join(tmp, 'outside.txt'), path.join(tmp, 'proj', 'link.txt'));
fs.mkdirSync(path.join(ws, 'workshop', 'robot'), { recursive: true });
fs.writeFileSync(path.join(ws, 'workshop', 'robot', 'n.txt'), 'note');
const app = express(); app.use(express.json());
app.use((req, _res, next) => { (req as any).user = { username, role, workspace: ws }; next(); });
registerClaudeFsRoutes(app);
await new Promise<void>(r => { server = app.listen(0, '127.0.0.1', () => r()); });
base = `http://127.0.0.1:${(server.address() as any).port}`;
});
after(() => {
server.close();
fs.rmSync(tmp, { recursive: true, force: true });
fs.rmSync(path.join(CFG, 'users', 'zz_claude_fs_test'), { recursive: true, force: true });
});
test('관리자: 임의 절대경로 루트 — 목록/읽기/쓰기', async () => {
role = 'admin';
const root = encodeURIComponent(path.join(tmp, 'proj'));
const list = await call('GET', `/api/claude-fs/files?root=${root}`);
assert.equal(list.status, 200);
assert.deepEqual(list.json.files.sort(), ['a.txt', 'sub/b.md']); // .env·링크는 목록에서 빠짐
assert.equal((await call('GET', `/api/claude-fs/file?root=${root}&name=a.txt`)).json.content, 'hello');
const w = await call('POST', '/api/claude-fs/save', { root: path.join(tmp, 'proj'), filename: 'new/dir/c.txt', content: 'zzz' });
assert.ok(w.json.success);
assert.equal(fs.readFileSync(path.join(tmp, 'proj', 'new', 'dir', 'c.txt'), 'utf8'), 'zzz');
});
test('관리자도: 시스템·.smallclaw 설정 루트는 403', async () => {
role = 'admin';
for (const r of ['/etc', '/', CFG]) assert.equal((await call('GET', `/api/claude-fs/files?root=${encodeURIComponent(r)}`)).status, 403, r);
});
test('관리자도: .env 읽기/쓰기 403, 경로 탈출(..) 403, 링크 탈출 403', async () => {
role = 'admin';
const root = path.join(tmp, 'proj'); const q = encodeURIComponent(root);
assert.equal((await call('GET', `/api/claude-fs/file?root=${q}&name=.env`)).status, 403);
assert.equal((await call('POST', '/api/claude-fs/save', { root, filename: '.env', content: 'x' })).status, 403);
assert.equal((await call('GET', `/api/claude-fs/file?root=${q}&name=${encodeURIComponent('../outside.txt')}`)).status, 403);
assert.equal((await call('GET', `/api/claude-fs/file?root=${q}&name=link.txt`)).status, 403);
assert.equal((await call('POST', '/api/claude-fs/save', { root, filename: 'link.txt', content: 'overwrite' })).status, 403);
assert.equal(fs.readFileSync(path.join(tmp, 'outside.txt'), 'utf8'), 'outside', '링크로 밖 파일이 바뀜');
});
test('일반 사용자: 자기 워크스페이스 상대경로는 OK, 밖 절대경로는 403', async () => {
role = 'user';
const ok = await call('GET', `/api/claude-fs/files?root=${encodeURIComponent('workshop/robot')}`);
assert.equal(ok.status, 200); assert.deepEqual(ok.json.files, ['n.txt']);
assert.equal((await call('GET', `/api/claude-fs/files?root=${encodeURIComponent(path.join(tmp, 'proj'))}`)).status, 403);
assert.equal((await call('GET', `/api/claude-fs/files?root=${encodeURIComponent('/srv/homeclaw/src')}`)).status, 403);
assert.equal((await call('GET', `/api/claude-fs/files?root=${encodeURIComponent('../..')}`)).status, 403);
});
test('root 비우면 code/ 폴더(기본)', async () => {
role = 'user';
const info = await call('GET', '/api/claude-fs/info');
assert.equal(info.status, 200);
assert.ok(info.json.root.endsWith(path.join('workspace', 'code')));
});
});
import { ptyAccessDecision } from '../src/gateway/pty-guard';
describe('ptyAccessDecision — 웹 터미널 접근', () => {
const admin = { username: 'papa', role: 'admin' }; const host = 'localhost:18789';
test('로그인한 관리자 + 같은 Origin → 허용', () => {
assert.equal(ptyAccessDecision({ user: admin, origin: 'http://localhost:18789', host }).allowed, true);
assert.equal(ptyAccessDecision({ user: admin, origin: 'https://claw.example.com', host: 'claw.example.com' }).allowed, true);
});
test('비로그인(user=null) 거부', () => {
assert.equal(ptyAccessDecision({ user: null, origin: 'http://localhost:18789', host }).allowed, false);
assert.equal(ptyAccessDecision({ user: undefined, origin: 'http://localhost:18789', host }).allowed, false);
});
test('일반 사용자 거부', () => {
assert.equal(ptyAccessDecision({ user: { username: 'apple', role: 'user' }, origin: 'http://localhost:18789', host }).allowed, false);
});
test('Origin 없음/다른 사이트/형식 오류 거부', () => {
assert.equal(ptyAccessDecision({ user: admin, host }).allowed, false);
assert.equal(ptyAccessDecision({ user: admin, origin: 'https://evil.example', host }).allowed, false);
assert.equal(ptyAccessDecision({ user: admin, origin: 'not a url', host }).allowed, false);
assert.equal(ptyAccessDecision({ user: admin, origin: 'http://localhost:18789' }).allowed, false);
});
});
test('프록시가 Host 를 바꿔도 X-Forwarded-Host 가 Origin 과 같으면 허용', () => {
assert.equal(ptyAccessDecision({ user: { username: 'papa', role: 'admin' }, origin: 'https://claw.example.com', host: '192.168.0.5:18789', forwardedHost: 'claw.example.com' }).allowed, true);
assert.equal(ptyAccessDecision({ user: { username: 'papa', role: 'admin' }, origin: 'https://evil.example', host: '192.168.0.5:18789', forwardedHost: 'claw.example.com' }).allowed, false);
});