Files
web-app-launcher/src/lib/server/services/__tests__/discoveryService.test.ts
T
alexei.dolgolyov f1cfb61d13
Lint & Test / lint-and-check (push) Failing after 5m5s
Lint & Test / test (push) Has been skipped
Lint & Test / build (push) Has been skipped
Lint & Test / docker-build (push) Has been skipped
Lint & Test / audit (push) Has been skipped
feat: production hardening + password reset, metrics, signed webhooks
Security hardening (CRITICAL/HIGH from production-readiness audit):
- Require strong JWT_SECRET + separate INTEGRATION_ENCRYPTION_KEY at boot;
  refuse placeholder defaults. Integration key now derived via HKDF.
- SSRF guard (src/lib/server/utils/safeFetch.ts): DNS-resolves and rejects
  RFC1918/loopback/link-local/IPv4-mapped IPv6/decimal-IP/cloud-metadata.
  Manual redirect handling re-validates each 3xx Location hop. Applied to
  healthcheck, RSS, calendar, metric, system-stats, camera, notifications,
  discovery, apps/preview, and all integration clients.
- API tokens, session refresh tokens, invite tokens, password-reset tokens
  switched from bcrypt to sha256 with @unique indexed lookup (O(1) instead
  of O(N) bcrypt-compares; eliminates a trivial DoS).
- Refresh-token reuse detection via Session.previousTokenHash.
- Permission checks on App PATCH/DELETE and Widget/Section endpoints.
- /api/integrations/alerts now requires auth.
- SVG uploads sanitized through DOMPurify (svg profile, scheme allow-list).
- Custom CSS sanitizer + selector scoping (decodes CSS unicode escapes
  before pattern match, drops forbidden at-rules incl. @import without
  whitespace, strips dangerous url() args). Scoped to .custom-css-scope.
- Backup restore validates SQLite magic header, takes a safety snapshot,
  uses atomic rename, re-applies pragmas.
- SQLite WAL + busy_timeout + foreign_keys + synchronous=NORMAL at startup.
- Healthcheck scheduler was dead code; wired in hooks.server.ts with
  HMR-safe singleton, concurrency cap, overlap prevention, retention jobs
  for AppClick/Notification/AuditLog. Composite indexes added on hot paths.
- Security headers (CSP, HSTS-on-https, X-Frame-Options, Permissions-Policy)
  emitted on every response.
- Account-enumeration mitigation on login (dummy bcrypt on no-user/oauth
  branches) + rate limiting on login/register/onboarding/refresh/invite/
  password-reset.
- OAuth callback sanitizes IdP error_description before echoing.

New features:
- Custom +error.svelte pages (root + boards + admin) via shared
  ErrorState component. Inverted hierarchy (status as label, title as hero).
- /forgot-password + /reset-password + admin-mediated /admin/password-resets
  page. SHA256 tokens, 24h TTL, all sessions revoked on apply.
- /invite page for manual invite-token redemption.
- /api/metrics Prometheus exposition with optional METRICS_TOKEN bearer
  auth. Counters for login/healthcheck/notification/integration; gauges
  for users/boards/apps + per-status app counts.
- Webhook HMAC-SHA256 signing for HTTP notification channels (optional
  shared secret + configurable signature header, default X-Signature-256).
- PATCH /api/users/me/password for self-service password change.
- Persistent uploads at /app/data/uploads with served-from-volume handler
  at /uploads/[...path]. SVGs served with CSP: sandbox.
- /api/health does a DB ping; returns 503 on disconnect.
- Public /status filtered to guest-accessible-board apps when unauthenticated.
- Audit log coverage: LOGIN_SUCCESS/FAILED, LOGOUT, OAUTH_LOGIN,
  OAUTH_USER_PROVISIONED, SESSION_REVOKED, API_TOKEN_*, INVITE_*,
  APP_UPDATED, PASSWORD_CHANGED, PASSWORD_RESET_*.

Performance:
- Board page: removed double findAll() over-fetch; include links + appTags
  in board query; widgets lazy-loaded via dynamic imports (marked,
  DOMPurify, hls.js, integration renderers).
- uptimeService.getAllAppsUptime: single batched query instead of N+1.
- 30s in-memory user-locals cache; invalidated on user mutation.
- pruneOldStatuses: single window-function DELETE instead of N+1.

Code quality:
- Typed error classes (NotFoundError, PermissionError, RateLimitError,
  IntegrationError) with toHttpError mapper.
- Locals.user shape exposes avatarUrl and narrows role via guard.
- App input types derived from Zod schemas via z.infer.
- 274 tests passing (up from 212); 62 new tests covering SSRF guard,
  CSS sanitizer, SVG sanitizer, rate limiter.

CI / Docker / config:
- Test workflow adds build, docker-build, audit jobs. Release workflow
  uses buildx multi-arch (amd64+arm64) with provenance + SBOM.
- Dockerfile uses tini, multi-stage prune, persistent uploads dir, single
  prisma migrate deploy (no destructive db push fallback).
- docker-compose: JWT_SECRET + INTEGRATION_ENCRYPTION_KEY required at
  startup, log rotation, resource limits.
- README documents breaking-change upgrade path.

Bug fixes from UI/UX review:
- ~55 missing i18n keys added to en/ru (auth flows, error pages, admin
  nav, register invite banner, settings.card_style).
- Hardcoded English on login replaced with $t('auth.remember_me').
- Admin nav uses i18n keys; mobile horizontal-scroll layout.
- Page <title> tags standardized.
- Password-resets: separated error/info/success surfaces, ConfirmDialog
  replaces window.confirm.
- Auth pages have matching lucide icon badges.
- Webhook secret has eye toggle and monospace input.
- text-green-500 → text-emerald-500 to match codebase convention.

Pre-existing CI lint failures cleaned up (31 errors → 0): each-key
attributes added, unused-svelte-ignore comments removed, two any casts
typed, dead skeleton components removed, /boards/[id]/edit redirect to
inline edit mode.

Tests: 274 / 274 passing
Type check: 0 errors / 0 warnings
Build: green
2026-05-26 19:51:21 +03:00

279 lines
7.3 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock child_process for Docker discovery
vi.mock('node:child_process', () => ({
execFile: vi.fn()
}));
vi.mock('node:util', () => ({
promisify: (fn: unknown) => fn
}));
// Mock appService for discoverAll
vi.mock('../appService.js', () => ({
findAll: vi.fn()
}));
import { execFile } from 'node:child_process';
import { findAll as findAllApps } from '../appService.js';
import { discoverDocker, discoverTraefik, discoverAll } from '../discoveryService.js';
const mockExecFile = execFile as unknown as ReturnType<typeof vi.fn>;
const mockFindAllApps = findAllApps as ReturnType<typeof vi.fn>;
describe('discoveryService', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('discoverDocker', () => {
it('returns services from running Docker containers', async () => {
const containers = [
{
Id: 'abc123',
Names: ['/gitea'],
Image: 'gitea/gitea:latest',
Ports: [{ IP: '0.0.0.0', PrivatePort: 3000, PublicPort: 3000, Type: 'tcp' }],
Labels: { 'org.opencontainers.image.description': 'Self-hosted Git' },
State: 'running'
}
];
mockExecFile.mockResolvedValue({ stdout: JSON.stringify(containers) });
const result = await discoverDocker('/var/run/docker.sock');
expect(result.services).toHaveLength(1);
expect(result.services[0].name).toBe('gitea');
expect(result.services[0].url).toBe('http://localhost:3000');
expect(result.services[0].source).toBe('docker');
expect(result.error).toBeUndefined();
});
it('extracts URL from Traefik labels in Docker containers', async () => {
const containers = [
{
Id: 'def456',
Names: ['/myapp'],
Image: 'myapp:latest',
Ports: [],
Labels: {
'traefik.http.routers.myapp.rule': 'Host(`myapp.example.com`)',
'traefik.http.routers.myapp.entrypoints': 'websecure'
},
State: 'running'
}
];
mockExecFile.mockResolvedValue({ stdout: JSON.stringify(containers) });
const result = await discoverDocker('/var/run/docker.sock');
expect(result.services).toHaveLength(1);
expect(result.services[0].url).toBe('https://myapp.example.com');
});
it('skips containers without accessible URLs', async () => {
const containers = [
{
Id: 'nop123',
Names: ['/background-worker'],
Image: 'worker:latest',
Ports: [],
Labels: {},
State: 'running'
}
];
mockExecFile.mockResolvedValue({ stdout: JSON.stringify(containers) });
const result = await discoverDocker('/var/run/docker.sock');
expect(result.services).toHaveLength(0);
});
it('returns error when Docker socket is inaccessible', async () => {
mockExecFile.mockRejectedValue(new Error('connect ENOENT /var/run/docker.sock'));
const result = await discoverDocker('/var/run/docker.sock');
expect(result.services).toHaveLength(0);
expect(result.error).toContain('ENOENT');
});
});
describe('discoverTraefik', () => {
// Build a Response-like object compatible with both raw fetch tests and
// the SafeResponse wrapper used by safeFetch.
function mockResponse(body: unknown, ok: boolean, status: number) {
const bodyString = JSON.stringify(body);
const bodyBytes = new TextEncoder().encode(bodyString);
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(bodyBytes);
controller.close();
}
});
return {
ok,
status,
headers: new Headers({ 'content-type': 'application/json' }),
body: stream,
json: () => Promise.resolve(body),
text: () => Promise.resolve(bodyString)
};
}
it('returns services from Traefik routers', async () => {
const routers = [
{
name: 'myapp@docker',
rule: 'Host(`myapp.example.com`)',
service: 'myapp@docker',
entryPoints: ['websecure']
}
];
const services = [
{
name: 'myapp@docker',
loadBalancer: { servers: [{ url: 'http://172.17.0.2:8080' }] }
}
];
vi.stubGlobal(
'fetch',
vi.fn((url: string) => {
if (url.includes('/api/http/routers')) {
return Promise.resolve(mockResponse(routers, true, 200));
}
return Promise.resolve(mockResponse(services, true, 200));
})
);
const result = await discoverTraefik('http://traefik.local:8080');
expect(result.services).toHaveLength(1);
expect(result.services[0].name).toBe('myapp');
expect(result.services[0].url).toBe('https://myapp.example.com');
expect(result.services[0].source).toBe('traefik');
vi.unstubAllGlobals();
});
it('returns error on Traefik API failure', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => Promise.resolve(mockResponse({}, false, 500)))
);
const result = await discoverTraefik('http://traefik.local:8080');
expect(result.services).toHaveLength(0);
expect(result.error).toContain('500');
vi.unstubAllGlobals();
});
it('returns error when fetch throws', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => Promise.reject(new Error('Network error')))
);
const result = await discoverTraefik('http://traefik.local:8080');
expect(result.services).toHaveLength(0);
expect(result.error).toContain('Network error');
vi.unstubAllGlobals();
});
});
describe('discoverAll', () => {
it('marks already-registered services', async () => {
mockExecFile.mockResolvedValue({
stdout: JSON.stringify([
{
Id: 'c1',
Names: ['/gitea'],
Image: 'gitea/gitea',
Ports: [{ IP: '0.0.0.0', PrivatePort: 3000, PublicPort: 3000, Type: 'tcp' }],
Labels: {},
State: 'running'
}
])
});
mockFindAllApps.mockResolvedValue([
{ id: 'a1', name: 'Gitea', url: 'http://localhost:3000' }
]);
const result = await discoverAll({ dockerSocketPath: '/var/run/docker.sock' });
expect(result.services).toHaveLength(1);
expect(result.services[0].alreadyRegistered).toBe(true);
});
it('deduplicates by URL preferring Traefik', async () => {
mockExecFile.mockResolvedValue({
stdout: JSON.stringify([
{
Id: 'c1',
Names: ['/app'],
Image: 'app:latest',
Ports: [],
Labels: {
'traefik.http.routers.app.rule': 'Host(`app.example.com`)'
},
State: 'running'
}
])
});
vi.stubGlobal(
'fetch',
vi.fn((url: string) => {
if (url.includes('/api/http/routers')) {
return Promise.resolve({
ok: true,
json: () =>
Promise.resolve([
{
name: 'app@docker',
rule: 'Host(`app.example.com`)',
service: 'app@docker',
entryPoints: ['web']
}
])
});
}
return Promise.resolve({ ok: true, json: () => Promise.resolve([]) });
})
);
mockFindAllApps.mockResolvedValue([]);
const result = await discoverAll({
dockerSocketPath: '/var/run/docker.sock',
traefikApiUrl: 'http://traefik.local:8080'
});
// Should deduplicate: both Docker (via label) and Traefik discover http://app.example.com
const urls = result.services.map((s) => s.url);
const unique = new Set(urls);
expect(urls.length).toBe(unique.size);
vi.unstubAllGlobals();
});
it('returns empty when no sources configured', async () => {
mockFindAllApps.mockResolvedValue([]);
const result = await discoverAll({});
expect(result.services).toHaveLength(0);
expect(result.errors).toHaveLength(0);
});
});
});