Skip to content
Open
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
8 changes: 8 additions & 0 deletions packages/contracts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,10 @@
"types": "./src/command-policy.ts",
"default": "./src/command-policy.ts"
},
"./credential-transport": {
"types": "./src/credential-transport.ts",
"default": "./src/credential-transport.ts"
},
"./daemon-command-surface": {
"types": "./src/daemon-command-surface.ts",
"default": "./src/daemon-command-surface.ts"
Expand Down Expand Up @@ -280,6 +284,10 @@
"types": "./src/interactor-types.ts",
"default": "./src/interactor-types.ts"
},
"./loopback-host": {
"types": "./src/loopback-host.ts",
"default": "./src/loopback-host.ts"
},
"./unsupported-interactor": {
"types": "./src/unsupported-interactor.ts",
"default": "./src/unsupported-interactor.ts"
Expand Down
69 changes: 69 additions & 0 deletions packages/contracts/src/credential-transport.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { expect, test } from 'vitest';
import { credentialTransportRefusal } from './credential-transport.ts';
import { isLoopbackHostname } from './loopback-host.ts';

test('loopback hostnames are recognized in each spelling a base URL carries', () => {
expect(isLoopbackHostname('LocalHost ')).toBe(true);
expect(isLoopbackHostname('127.0.0.1')).toBe(true);
expect(isLoopbackHostname('[::1]')).toBe(true);
expect(isLoopbackHostname('::ffff:127.0.0.1')).toBe(true);
expect(isLoopbackHostname('0.0.0.0')).toBe(false);
expect(isLoopbackHostname('127.1.2.3')).toBe(true);
expect(isLoopbackHostname('localhost.example.test')).toBe(false);
expect(isLoopbackHostname('')).toBe(false);
});

test.each([
'https://fleet.example.test/agent-device',
'https://10.0.0.7:4310',
'http://127.0.0.1:4310/agent-device',
'http://127.1:4310',
'http://[::1]:4310',
'http://[::ffff:127.0.0.1]:4310',
'http://LOCALHOST:4310',
])('a credential may travel to %s', (url) => {
expect(credentialTransportRefusal(url, {})).toBeUndefined();
});

test.each([
'http://fleet.example.test/agent-device',
'http://10.0.0.7:4310',
'http://100.64.1.2:4310',
'http://0.0.0.0:4310',
'http://localhost.:4310',
'http://127.0.0.1.nip.io:4310',
'ws://127.0.0.1:4310',
'http:',
])('a credential may not travel to %s', (url) => {
expect(credentialTransportRefusal(url, {})).toMatchObject({
code: 'INVALID_ARGS',
details: { reason: 'insecure_credential_transport' },
});
});

test('the refusal names the origin and the override, and nothing else from the URL', () => {
const refusal = credentialTransportRefusal(
'http://operator:hunter2@fleet.example.test:7777/private?token=secret',
{},
);

expect(refusal?.message).toContain('http://fleet.example.test:7777');
expect(refusal?.details?.hint).toContain('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1');
expect(JSON.stringify([refusal?.message, refusal?.details])).not.toMatch(
/operator|hunter2|private|secret/,
);
});

test.each([
['1', true],
['true', false],
['0', false],
[' 1', false],
['', false],
])('the override value %j admits plain http: %s', (value, admitted) => {
const refusal = credentialTransportRefusal('http://10.0.0.7:4310', {
AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: value,
});

expect(refusal === undefined).toBe(admitted);
});
38 changes: 38 additions & 0 deletions packages/contracts/src/credential-transport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import type { EnvMap } from '@agent-device/kernel/source-value';
import { isLoopbackHostname } from './loopback-host.ts';

const CREDENTIAL_TRANSPORT_REASONS = {
// A first-party credential would go to a configured URL that is neither https nor plain http to a
// loopback host, and the CLI or SDK environment does not set
// AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 (@agent-device/proxy has no override). agent-device
// 0.21.x warns on stderr instead of failing with it; 0.22 refuses with it before sending anything.
insecureTransport: { reason: 'insecure_credential_transport' },
} as const satisfies ReasonTable<'remote connection'>;

/**
* The rule for a configured URL that receives a first-party credential: https, or plain http to a
* loopback host. Returns the refusal for any other URL, unless the operator set
* `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1`. The refusal names the origin only.
*
* `env` is the sending process's own environment, never a value from a profile, ticket or peer.
* A sender with no override passes an empty `env` and a `hint` that names its own fixes.
*/
export function credentialTransportRefusal(
url: string,
env: Readonly<EnvMap>,
hint = 'Use https, ssh -L, or Tailscale Serve, or set AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1.',
): AppError | undefined {
if (env.AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT === '1') return undefined;
const destination = URL.parse(url);
if (destination?.protocol === 'https:') return undefined;
if (destination?.protocol === 'http:' && isLoopbackHostname(destination.hostname)) {
return undefined;
}
const origin = destination?.origin ?? 'an invalid URL';
return new AppError('INVALID_ARGS', `Refusing to send a credential in cleartext to ${origin}.`, {
reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason,
origin,
hint,
});
}
18 changes: 18 additions & 0 deletions packages/contracts/src/loopback-host.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import net from 'node:net';

const LOOPBACK_BLOCK_LIST = new net.BlockList();
LOOPBACK_BLOCK_LIST.addSubnet('127.0.0.0', 8, 'ipv4');
LOOPBACK_BLOCK_LIST.addAddress('::1', 'ipv6');
LOOPBACK_BLOCK_LIST.addSubnet('::ffff:127.0.0.0', 104, 'ipv6');

/** Whether a host names this machine: `localhost` or a loopback literal. No name is resolved. */
export function isLoopbackHostname(hostname: string): boolean {
const normalized = hostname
.trim()
.toLowerCase()
.replace(/^\[(.*)\]$/, '$1');
if (normalized === 'localhost') return true;
if (net.isIPv4(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv4');
if (net.isIPv6(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv6');
return false;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// A remote daemon token over plain http off loopback is warned about from the settings the client
// reads, before the first request leaves.

import assert from 'node:assert/strict';
import http from 'node:http';
import { afterEach, test, vi } from 'vitest';
import { beginStderrCapture, createTestHostEnvironment } from '@agent-device/test-kit';
import { assertRemoteServesCheckedRpc } from '../index.ts';

afterEach(() => {
vi.restoreAllMocks();
});

/** The stderr written by the time the first request to `daemonBaseUrl` opens; nothing is sent. */
async function stderrAtFirstSend(
daemonBaseUrl: string,
env: Record<string, string> = {},
): Promise<string> {
const stderr = beginStderrCapture();
let atSend: string | undefined;
vi.spyOn(http, 'request').mockImplementation(() => {
atSend ??= stderr.read();
throw new Error('stop at the socket');
});
try {
await assert.rejects(
assertRemoteServesCheckedRpc(
{ daemonBaseUrl, daemonAuthToken: 'remote-secret' },
createTestHostEnvironment({ env }),
),
);
} finally {
stderr.restore();
}
assert.ok(atSend !== undefined, 'the client never reached the socket');
return atSend;
}

test('a plain http daemon off loopback is warned about before the token leaves', async () => {
const warning = await stderrAtFirstSend('http://warned.example.test:7777/agent-device');

assert.match(warning, /http:\/\/warned\.example\.test:7777 are sent in cleartext/);
assert.doesNotMatch(warning, /remote-secret|agent-device\/health/);
});

test.each([
['a loopback daemon', 'http://127.0.0.1:7777', {}],
[
'the override in the host environment',
'http://overridden.example.test:7777',
{ AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1' },
],
] as const)('%s is not warned about', async (_label, daemonBaseUrl, env) => {
assert.equal(await stderrAtFirstSend(daemonBaseUrl, env), '');
});
5 changes: 4 additions & 1 deletion packages/daemon-client/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { RequestProgressEvent } from '@agent-device/contracts/progress';
import { test } from 'vitest';
import { test, vi } from 'vitest';
import assert from 'node:assert/strict';
import http from 'node:http';
import net from 'node:net';
Expand Down Expand Up @@ -37,10 +37,13 @@ async function withRemoteDaemonEnv<T>(callback: () => Promise<T>): Promise<T> {
const previousAuthToken = process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
process.env.AGENT_DEVICE_DAEMON_BASE_URL = 'http://remote-mac.example.test:7777/agent-device';
process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN = 'remote-secret';
// This host is not loopback: the transport warning would reach the tests that read stderr.
vi.stubEnv('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT', '1');

try {
return await callback();
} finally {
vi.unstubAllEnvs();
if (previousBaseUrl === undefined) delete process.env.AGENT_DEVICE_DAEMON_BASE_URL;
else process.env.AGENT_DEVICE_DAEMON_BASE_URL = previousBaseUrl;
if (previousAuthToken === undefined) delete process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
Expand Down
5 changes: 4 additions & 1 deletion packages/daemon-client/src/daemon-client-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type {
EnsureDaemonOptions,
} from '@agent-device/contracts/client';
import type { DaemonResponse } from '@agent-device/kernel/contracts';
import { isLoopbackHostname } from '@agent-device/contracts/loopback-host';
import { admitCredentialDestination } from '@agent-device/host-kit/credential-admission';
import { AppError, normalizeError, type NormalizedError } from '@agent-device/kernel/errors';
import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value';
import { readReplayDivergenceResume } from '@agent-device/ad-replay/divergence';
Expand All @@ -15,7 +17,6 @@ import {
type OwnedReplayStateDir,
} from '@agent-device/daemon-contracts/daemon-registration-owner';
import {
isLoopbackHostname,
resolveDaemonPaths,
resolveDaemonServerMode,
resolveDaemonTransportPreference,
Expand Down Expand Up @@ -254,6 +255,8 @@ function resolveRemoteClientSettings(
const remoteBaseUrl = resolveRemoteDaemonBaseUrl(rawBaseUrl);
const authToken = suppliedAuthToken ?? env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
validateRemoteDaemonTrust(remoteBaseUrl, authToken);
// Every remote request sends the token to this base URL.
if (remoteBaseUrl) admitCredentialDestination(remoteBaseUrl, env);
const daemonRpc = resolveDaemonRpcMode(req.flags?.daemonRpc);
return { rawBaseUrl, remoteBaseUrl, authToken, daemonRpc };
}
Expand Down
13 changes: 1 addition & 12 deletions packages/daemon-contracts/src/daemon-resolution-loopback.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test } from 'vitest';
import { daemonBaseUrlIsLocal, isLoopbackHostname } from './daemon-resolution.ts';
import { daemonBaseUrlIsLocal } from './daemon-resolution.ts';

test('a daemon base URL on loopback addresses this machine', () => {
expect(daemonBaseUrlIsLocal(undefined)).toBe(true);
Expand All @@ -15,14 +15,3 @@ test('a daemon base URL off loopback addresses another machine', () => {
// An unusable base URL is refused when the transport resolves it; here it is treated as remote.
expect(daemonBaseUrlIsLocal('not a url')).toBe(false);
});

test('loopback hostnames are recognized in each spelling a base URL carries', () => {
expect(isLoopbackHostname('LocalHost ')).toBe(true);
expect(isLoopbackHostname('127.0.0.1')).toBe(true);
expect(isLoopbackHostname('[::1]')).toBe(true);
expect(isLoopbackHostname('::ffff:127.0.0.1')).toBe(true);
expect(isLoopbackHostname('0.0.0.0')).toBe(false);
expect(isLoopbackHostname('127.1.2.3')).toBe(true);
expect(isLoopbackHostname('localhost.example.test')).toBe(false);
expect(isLoopbackHostname('')).toBe(false);
});
19 changes: 1 addition & 18 deletions packages/daemon-contracts/src/daemon-resolution.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import net from 'node:net';
import path from 'node:path';
import {
admitPrivateRoot,
Expand All @@ -13,6 +12,7 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import { type EnvMap } from '@agent-device/kernel/source-value';

import type { DaemonWireRequest } from '@agent-device/contracts/command';
import { isLoopbackHostname } from '@agent-device/contracts/loopback-host';
import type { OwnerIdentity } from '@agent-device/host-kit/process';
import type { DaemonServerMode, DaemonTransportPreference } from '@agent-device/kernel/contracts';
export type { DaemonServerMode, DaemonTransportPreference };
Expand Down Expand Up @@ -278,11 +278,6 @@ export function serverModeAnswersTransport(
return preference === 'http' ? mode !== 'socket' : mode !== 'http';
}

const LOOPBACK_BLOCK_LIST = new net.BlockList();
LOOPBACK_BLOCK_LIST.addSubnet('127.0.0.0', 8, 'ipv4');
LOOPBACK_BLOCK_LIST.addAddress('::1', 'ipv6');
LOOPBACK_BLOCK_LIST.addSubnet('::ffff:127.0.0.0', 104, 'ipv6');

/**
* Whether a daemon base URL addresses this machine. A caller on a non-loopback daemon drives devices
* hosted elsewhere, so it must not read this machine's state to answer a question about them.
Expand All @@ -299,18 +294,6 @@ export function daemonBaseUrlIsLocal(raw: string | undefined): boolean {
return isLoopbackHostname(hostname);
}

/** Whether an address names this machine: `localhost` or a loopback literal. */
export function isLoopbackHostname(hostname: string): boolean {
const normalized = hostname
.trim()
.toLowerCase()
.replace(/^\[(.*)\]$/, '$1');
if (normalized === 'localhost') return true;
if (net.isIPv4(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv4');
if (net.isIPv6(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv6');
return false;
}

export function resolveDaemonTransportPreference(
raw: string | undefined,
): DaemonTransportPreference {
Expand Down
4 changes: 4 additions & 0 deletions packages/host-kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@
"types": "./src/command.ts",
"default": "./src/command.ts"
},
"./credential-admission": {
"types": "./src/credential-admission.ts",
"default": "./src/credential-admission.ts"
},
"./diagnostics": {
"types": "./src/diagnostics.ts",
"default": "./src/diagnostics.ts"
Expand Down
53 changes: 53 additions & 0 deletions packages/host-kit/src/credential-admission.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
import { admitCredentialDestination } from './credential-admission.ts';

let stderr: string[] = [];

beforeEach(() => {
stderr = [];
vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => {
stderr.push(String(chunk));
return true;
});
});

afterEach(() => {
vi.restoreAllMocks();
});

test('an insecure destination is warned about once per origin and not refused', () => {
admitCredentialDestination('http://user:hunter2@once.example.test:7777/a?token=secret', {});
admitCredentialDestination('http://once.example.test:7777/b', {});
admitCredentialDestination('http://once.example.test:8888', {});

expect(stderr).toHaveLength(2);
expect(stderr[0]).toMatch(/^Warning: .*http:\/\/once\.example\.test:7777 .*cleartext/);
expect(stderr[0]).toContain('agent-device 0.22 will refuse this');
for (const fix of ['https', 'ssh -L', 'Tailscale Serve']) expect(stderr[0]).toContain(fix);
expect(stderr[0]).toContain('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1');
expect(stderr.join('')).not.toMatch(/user|hunter2|secret/);
expect(stderr[1]).toContain('http://once.example.test:8888');
});

test('a stderr that fails does not change the outcome', () => {
const listeners = process.stderr.listenerCount('error');
let listenersAtWrite = 0;
vi.mocked(process.stderr.write).mockImplementation(() => {
// A closed reader reports EPIPE as an event; without a listener at write time it is fatal.
listenersAtWrite = process.stderr.listenerCount('error');
throw new Error('EPIPE');
});

expect(() => admitCredentialDestination('http://broken-stderr.example.test', {})).not.toThrow();
expect(listenersAtWrite).toBe(listeners + 1);
});

test('a secure destination and the override stay silent', () => {
admitCredentialDestination('https://quiet.example.test', {});
admitCredentialDestination('http://127.0.0.1:4310', {});
admitCredentialDestination('http://quiet.example.test', {
AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1',
});

expect(stderr).toEqual([]);
});
Loading
Loading