Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
55 changes: 41 additions & 14 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isIP } from 'node:net';
import { loadMesheryAuth, type ResolvedMesheryAuth } from './config.js';
import { AxiError } from './errors.js';

Expand Down Expand Up @@ -76,6 +77,43 @@ export function nextPage(
return hasMore ? page + 2 : undefined;
}

/** True when the host resolves to this machine: localhost, 127.0.0.0/8, or ::1. */
export function isLoopbackHost(hostname: string): boolean {
// URL.hostname keeps IPv6 brackets, e.g. "[::1]".
const host = hostname.toLowerCase().replace(/^\[(.*)\]$/, '$1');
// 'localhost.' (trailing-dot root form) is still localhost; the old
// inline check accepted it, so keep accepting it here.
if (host === 'localhost' || host === 'localhost.') return true;
if (isIP(host) === 4) return host.startsWith('127.');
if (isIP(host) === 6) return host === '::1';
return false;
}

/**
* Refuse to send auth cookies in cleartext to a non-loopback host (CWE-319).
* HTTPS is always allowed; plain HTTP only for local Meshery deployments.
*/
function assertSecureEndpoint(endpoint: string): void {
let url: URL;
try {
url = new URL(endpoint);
} catch {
throw new AxiError(`Invalid Meshery endpoint: ${endpoint}`, 'VALIDATION_ERROR', [
'Check `mesheryctl system context view` endpoint',
]);
}
if (url.protocol === 'https:') return;
if (url.protocol === 'http:' && isLoopbackHost(url.hostname)) return;
throw new AxiError(
`Refusing to send Meshery credentials over cleartext ${url.protocol}//${url.host}`,
'VALIDATION_ERROR',
[
'Point the mesheryctl context at an https:// endpoint',
'Or use a loopback endpoint (localhost / 127.0.0.1) for a local Meshery',
],
);
}

/**
* Readable text for a failed request. Meshery reports failures as a MeshKit
* JSON error whose useful reason is in longDescription, so prefer that over
Expand Down Expand Up @@ -113,6 +151,9 @@ export async function serverRequestJson<T = unknown>(options: ServerRequestOptio
process.env['MESHERY_ENDPOINT']?.replace(/\/$/, '') ??
'http://localhost:9081';

// Before buildUrl, so a bad endpoint gets the readable error, not a TypeError.
if (!options.anonymous && auth) assertSecureEndpoint(endpoint);

const url = buildUrl(endpoint, options.path, options.query);
const headers: Record<string, string> = {
Accept: 'application/json',
Expand All @@ -121,20 +162,6 @@ export async function serverRequestJson<T = unknown>(options: ServerRequestOptio
headers['Content-Type'] = 'application/json';
}
if (!options.anonymous && auth) {
const target = new URL(url);
const host = target.hostname;
const loopback =
host === 'localhost' ||
host === 'localhost.' ||
host === '[::1]' ||
/^127(?:\.\d{1,3}){3}$/.test(host);
if (target.protocol !== 'https:' && !(target.protocol === 'http:' && loopback)) {
throw new AxiError(
'Authenticated Meshery Server requests require HTTPS for non-loopback endpoints',
'VALIDATION_ERROR',
['Configure an HTTPS endpoint in `mesheryctl system context`'],
);
}
// Cookie names match mesheryctl pkg/utils AddAuthDetails.
headers['Cookie'] = `token=${auth.tokenValue}; meshery-provider=${auth.providerValue}`;
}
Expand Down
114 changes: 76 additions & 38 deletions test/server-security.test.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,100 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { afterEach, describe, expect, it } from 'vitest';
import type { ResolvedMesheryAuth } from '../src/config.js';
import { serverGetJson, setServerFetcher } from '../src/server.js';
import { isLoopbackHost, serverGetJson, setServerAuth, setServerFetcher } from '../src/server.js';

function auth(endpoint: string): ResolvedMesheryAuth {
function authFor(endpoint: string): ResolvedMesheryAuth {
return {
context: { name: 'test', endpoint, tokenName: 'default' },
configPath: 'config.yaml',
tokenPath: 'auth.json',
configPath: '/dev/null',
tokenPath: '/dev/null',
tokenValue: 'secret',
providerValue: 'Meshery',
};
}

afterEach(() => setServerFetcher(undefined));
const calls: { url: string; init: RequestInit }[] = [];

function recordingFetcher(): void {
calls.length = 0;
setServerFetcher(async (url, init) => {
calls.push({ url, init });
return new Response('{"ok":true}', { status: 200 });
});
}

afterEach(() => {
setServerAuth(undefined);
setServerFetcher(undefined);
});

describe('isLoopbackHost', () => {
it.each(['localhost', 'LOCALHOST', 'localhost.', '127.0.0.1', '127.1.2.3', '[::1]', '::1'])(
'%s is loopback',
(host) => expect(isLoopbackHost(host)).toBe(true),
);

it.each([
'localhost.com',
'localhost.evil.com',
'127.0.0.1.evil.com',
'128.0.0.1',
'192.168.1.50',
'10.0.0.5',
'0.0.0.0',
'[::2]',
'meshery.example.com',
])('%s is not loopback', (host) => expect(isLoopbackHost(host)).toBe(false));
});

describe('serverGetJson transport security (#88)', () => {
it.each([
'http://localhost.com:9081',
'http://127.0.0.1.evil.com',
'http://192.168.1.50:9081',
'http://meshery.example.com',
])('rejects authenticated request to %s without sending it', async (ep) => {
recordingFetcher();
setServerAuth(authFor(ep));
await expect(serverGetJson({ path: 'api/x' })).rejects.toMatchObject({
code: 'VALIDATION_ERROR',
});
expect(calls).toHaveLength(0);
});

describe('server request transport', () => {
it.each([
'http://localhost:9081',
'http://127.0.0.1:9081',
'http://127.1.2.3:9081',
'http://[::1]:9081',
'https://meshery.example:9081',
])('sends cookies to %s', async (endpoint) => {
const fetcher = vi.fn(async () => new Response('{}'));
setServerFetcher(fetcher);
await serverGetJson({ path: '/api/test', auth: auth(endpoint) });
expect(fetcher).toHaveBeenCalledOnce();
expect(fetcher.mock.calls[0]?.[1]).toMatchObject({
headers: { Cookie: 'token=secret; meshery-provider=Meshery' },
'https://meshery.example.com',
'https://192.168.49.2:9081',
])('sends auth cookies to %s', async (ep) => {
recordingFetcher();
setServerAuth(authFor(ep));
await expect(serverGetJson({ path: 'api/x' })).resolves.toEqual({
ok: true,
});
expect(calls).toHaveLength(1);
const headers = calls[0]!.init.headers as Record<string, string>;
expect(headers['Cookie']).toContain('token=secret');
});

it.each([
'http://meshery.example:9081',
'http://192.168.1.2:9081',
'http://localhost.example:9081',
'http://127.0.0.1.example:9081',
'http://[::2]:9081',
])('rejects authenticated requests to %s before fetching', async (endpoint) => {
const fetcher = vi.fn(async () => new Response('{}'));
setServerFetcher(fetcher);
await expect(serverGetJson({ path: '/api/test', auth: auth(endpoint) })).rejects.toMatchObject({
it('reports an invalid endpoint as VALIDATION_ERROR', async () => {
recordingFetcher();
setServerAuth(authFor('not a url'));
await expect(serverGetJson({ path: 'api/x' })).rejects.toMatchObject({
code: 'VALIDATION_ERROR',
message: expect.stringContaining('HTTPS'),
message: expect.stringContaining('Invalid Meshery endpoint'),
});
expect(fetcher).not.toHaveBeenCalled();
expect(calls).toHaveLength(0);
});

it('allows anonymous HTTP requests without cookies', async () => {
const fetcher = vi.fn(async () => new Response('{}'));
setServerFetcher(fetcher);
await serverGetJson({
path: '/api/test',
anonymous: true,
auth: auth('http://meshery.example'),
it('allows anonymous requests to remote http without cookies', async () => {
recordingFetcher();
setServerAuth(authFor('http://192.168.1.50:9081'));
await expect(serverGetJson({ path: 'api/system/version', anonymous: true })).resolves.toEqual({
ok: true,
});
expect(fetcher).toHaveBeenCalledOnce();
expect(fetcher.mock.calls[0]?.[1]).toMatchObject({ headers: { Accept: 'application/json' } });
expect(fetcher.mock.calls[0]?.[1]?.headers).not.toHaveProperty('Cookie');
const headers = calls[0]!.init.headers as Record<string, string>;
expect(headers['Cookie']).toBeUndefined();
});
});
Loading