mirror of
https://github.com/hanzoai/chat.git
synced 2026-09-30 20:51:17 +00:00
Five things answered outside /v1/chat/. Four of them are chat's; they move.
/health -> /v1/chat/health
POST /oauth/iam/session-> POST /v1/chat/auth/iam/session (it is auth)
GET /oauth/openid[/callback], /oauth/error
-> /v1/chat/auth/openid[/callback], /v1/chat/auth/error
/images/ -> /v1/chat/images/
The fifth — the built assets at / and the SPA catch-all — is the SPA's, and
stays. Every caller moved in the same commit: api-endpoints (health, iamSession),
the metrics + telemetry health filter, the helm probes, the PR-preview workflow,
the PWA nav-fallback denylist. `ErrorController` matched a failed OIDC callback
by the substring '/oauth/', which the move would have silently broken; it now
matches the route.
Images are the one persisted case: a conversation stores the served path, and
history is immutable. New writes emit /v1/chat/images/…; /images/* answers one
permanent redirect; `isServedImage` (data-provider, the one place that knows the
namespace) recognises both. Local deletion maps the served path back to disk.
Two routers were written, tested, advertised to the browser — and never mounted,
so both were a guaranteed 404: skills (types say /v1/chat/skills) and the RUM
OTLP proxy (`rum/proxy` advertises /v1/chat/rum). Mounted where they said.
Deleted, with zero callers: server/experimental.js — a drifted second copy of
the whole mount table, still referencing a router that no longer exists, that
would have silently absorbed this move and diverged again; and nginx.hanzo.conf,
referenced by no compose/Dockerfile/chart, whose own /health shadowed chat's.
Gates collapsed to their one behavior, and the env deleted:
ALLOW_SOCIAL_LOGIN IAM is the one identity provider; false produced a
server with no way to sign in. socialLogins.js is now
iamLogin.js — one name for one thing.
CONTINUE_ON_UNCAUGHT_EXCEPTION keeps a process alive in an unknown state
instead of letting the kubelet replace it.
CONFIG_BYPASS_VALIDATION boots on invalid config, on request.
MCP_SKIP_CODE_CHALLENGE_CHECK turns off PKCE verification.
OPENID_JWKS_URL_CACHE_ENABLED read as `isEnabled(x) || true` — never off.
A second, differently-defaulted read lived in
remoteAgentAuth; both are now just on.
NO_INDEX a third boolean idiom for a header we always want.
DISABLE_COMPRESSION, ENABLE_IMAGE_OUTPUT_GZIP_SCAN — we write these images
ourselves, as PNG/GIF; none is gzipped on disk.
Tests fail without the change: the auth router spec (6 of 7) against the old
router, the static spec against the old env-gated one, the config spec now sets
CONFIG_BYPASS_VALIDATION=true and still expects the exit, the error spec against
the '/oauth/' matcher, and index.spec asserts the top level serves HTML — so a
probe or caller left behind fails loudly instead of looking green.
167 lines
4.7 KiB
JavaScript
167 lines
4.7 KiB
JavaScript
const fs = require('fs');
|
|
const request = require('supertest');
|
|
const { MongoMemoryServer } = require('mongodb-memory-server');
|
|
const mongoose = require('mongoose');
|
|
|
|
jest.mock('~/server/services/Config', () => ({
|
|
loadCustomConfig: jest.fn(() => Promise.resolve({})),
|
|
getAppConfig: jest.fn().mockResolvedValue({
|
|
paths: {
|
|
uploads: '/tmp',
|
|
dist: '/tmp/dist',
|
|
fonts: '/tmp/fonts',
|
|
assets: '/tmp/assets',
|
|
},
|
|
fileStrategy: 'local',
|
|
imageOutputType: 'PNG',
|
|
}),
|
|
setCachedTools: jest.fn(),
|
|
}));
|
|
|
|
jest.mock('~/app/clients/tools', () => ({
|
|
createOpenAIImageTools: jest.fn(() => []),
|
|
createYouTubeTools: jest.fn(() => []),
|
|
manifestToolMap: {},
|
|
toolkits: [],
|
|
}));
|
|
|
|
jest.mock('~/config', () => ({
|
|
createMCPServersRegistry: jest.fn(),
|
|
createMCPManager: jest.fn().mockResolvedValue({
|
|
getAppToolFunctions: jest.fn().mockResolvedValue({}),
|
|
}),
|
|
}));
|
|
|
|
describe('Server metrics route', () => {
|
|
jest.setTimeout(30_000);
|
|
|
|
let mongoServer;
|
|
let app;
|
|
|
|
const originalReadFileSync = fs.readFileSync;
|
|
|
|
beforeAll(() => {
|
|
fs.readFileSync = function (filepath, options) {
|
|
if (filepath.includes('index.html')) {
|
|
return '<!DOCTYPE html><html><head><title>Chat</title></head><body><div id="root"></div></body></html>';
|
|
}
|
|
return originalReadFileSync(filepath, options);
|
|
};
|
|
});
|
|
|
|
afterAll(() => {
|
|
fs.readFileSync = originalReadFileSync;
|
|
});
|
|
|
|
beforeAll(async () => {
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const dirs = ['/tmp/dist', '/tmp/fonts', '/tmp/assets'];
|
|
dirs.forEach((dir) => {
|
|
if (!fs.existsSync(dir)) {
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
}
|
|
});
|
|
|
|
fs.writeFileSync(
|
|
path.join('/tmp/dist', 'index.html'),
|
|
'<!DOCTYPE html><html><head><title>Chat</title></head><body><div id="root"></div></body></html>',
|
|
);
|
|
|
|
mongoServer = await MongoMemoryServer.create();
|
|
process.env.MONGO_URI = mongoServer.getUri();
|
|
process.env.PORT = '0';
|
|
process.env.METRICS_SECRET = 'test-secret';
|
|
app = require('~/server');
|
|
|
|
await healthCheckPoll(app);
|
|
});
|
|
|
|
afterEach(() => {
|
|
process.env.METRICS_SECRET = 'test-secret';
|
|
});
|
|
|
|
afterAll(async () => {
|
|
delete process.env.METRICS_SECRET;
|
|
await mongoServer.stop();
|
|
await mongoose.disconnect();
|
|
});
|
|
|
|
it('returns 401 at /metrics when METRICS_SECRET is unset', async () => {
|
|
const response = await request(app).get('/metrics');
|
|
expect(response.status).toBe(401);
|
|
});
|
|
|
|
it('returns 401 at /metrics when no token provided', async () => {
|
|
process.env.METRICS_SECRET = 'test-secret';
|
|
|
|
const response = await request(app).get('/metrics');
|
|
|
|
expect(response.status).toBe(401);
|
|
});
|
|
|
|
it('returns 401 at /metrics when wrong token provided', async () => {
|
|
process.env.METRICS_SECRET = 'test-secret';
|
|
|
|
const response = await request(app).get('/metrics').set('Authorization', 'Bearer wrong-token');
|
|
|
|
expect(response.status).toBe(401);
|
|
});
|
|
|
|
it('returns 401 at /metrics when the bearer scheme is omitted', async () => {
|
|
process.env.METRICS_SECRET = 'test-secret';
|
|
|
|
const response = await request(app).get('/metrics').set('Authorization', 'test-secret');
|
|
|
|
expect(response.status).toBe(401);
|
|
});
|
|
|
|
it('returns 401 at /metrics for non-bearer auth schemes', async () => {
|
|
process.env.METRICS_SECRET = 'test-secret';
|
|
|
|
const response = await request(app).get('/metrics').set('Authorization', 'Basic test-secret');
|
|
|
|
expect(response.status).toBe(401);
|
|
});
|
|
|
|
it('exposes Prometheus metrics at /metrics with correct bearer token', async () => {
|
|
process.env.METRICS_SECRET = 'test-secret';
|
|
|
|
const response = await request(app).get('/metrics').set('Authorization', 'Bearer test-secret');
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(response.headers['content-type']).toMatch(/text\/plain/);
|
|
expect(response.text).toMatch(/^# HELP /m);
|
|
expect(response.text).toMatch(/^# TYPE /m);
|
|
});
|
|
|
|
it('accepts lowercase bearer scheme at /metrics', async () => {
|
|
process.env.METRICS_SECRET = 'test-secret';
|
|
|
|
const response = await request(app).get('/metrics').set('Authorization', 'bearer test-secret');
|
|
|
|
expect(response.status).toBe(200);
|
|
});
|
|
});
|
|
|
|
async function healthCheckPoll(app, retries = 0) {
|
|
const maxRetries = Math.floor(10000 / 30);
|
|
try {
|
|
const response = await request(app).get('/v1/chat/health');
|
|
if (response.text === 'OK') {
|
|
return;
|
|
}
|
|
} catch {
|
|
// Ignore connection errors during polling.
|
|
}
|
|
|
|
if (retries < maxRetries) {
|
|
await new Promise((resolve) => setTimeout(resolve, 30));
|
|
await healthCheckPoll(app, retries + 1);
|
|
return;
|
|
}
|
|
|
|
throw new Error('App did not become healthy within 10 seconds.');
|
|
}
|