Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add enableUnixSockets option #2062

Merged
merged 20 commits into from
Jul 21, 2022
Merged
Show file tree
Hide file tree
Changes from 10 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
25 changes: 25 additions & 0 deletions documentation/2-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -918,6 +918,31 @@ By default, requests will not use [method rewriting](https://datatracker.ietf.or

For example, when sending a `POST` request and receiving a `302`, it will resend the body to the new location using the same HTTP method (`POST` in this case). To rewrite the request as `GET`, set this option to `true`.

### `enableUnixSockets`

**Type: `boolean`**\
**Default: `false`**
szmarczak marked this conversation as resolved.
Show resolved Hide resolved

Enable it with care if you accept untrusted user input for the URL.
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
szmarczak marked this conversation as resolved.
Show resolved Hide resolved

sindresorhus marked this conversation as resolved.
Show resolved Hide resolved
When it is enabled, requests can also be sent via [UNIX Domain Sockets](https://serverfault.com/questions/124517/what-is-the-difference-between-unix-sockets-and-tcp-ip-sockets).\
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved
Use the following URL scheme: `PROTOCOL://unix:SOCKET:PATH`

- `PROTOCOL` - `http` or `https`
- `SOCKET` - Absolute path to a unix domain socket, for example: `/var/run/docker.sock`
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
- `PATH` - Request path, for example: `/v2/keys`

```js
import got from 'got';

const gotUnixSocketsEnabled = got.extend({enableUnixSockets: true});

await gotUnixSocketsEnabled('http://unix:/var/run/docker.sock:/containers/json');

// Or without protocol (HTTP by default)
await gotUnixSocketsEnabled('unix:/var/run/docker.sock:/containers/json');
```

## Methods

### `options.merge(other: Options | OptionsInit)`
Expand Down
2 changes: 1 addition & 1 deletion documentation/migration-guides/axios.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ We deeply care about readability, so we renamed these options:

- `httpAgent` → [`agent.http`](../2-options.md#agent)
- `httpsAgent` → [`agent.https`](../2-options.md#agent)
- `socketPath` → [`url`](../tips.md#unix)
- `socketPath` → [`url`](../2-options.md#enableunixsockets)
- `responseEncoding` → [`encoding`](../2-options.md#encoding)
- `auth.username` → [`username`](../2-options.md#username)
- `auth.password` → [`password`](../2-options.md#password)
Expand Down
2 changes: 1 addition & 1 deletion documentation/migration-guides/request.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ These Got options are the same as with Request:
- [`localAddress`](../2-options.md#localaddress)
- [`headers`](../2-options.md#headers)
- [`createConnection`](../2-options.md#createconnection)
- [UNIX sockets](../tips.md#unixsockets): `http://unix:SOCKET:PATH`
- [UNIX sockets](../2-options.md#enableunixsockets): `http://unix:SOCKET:PATH`

The `time` option does not exist, assume [it's always true](../6-timeout.md).

Expand Down
16 changes: 1 addition & 15 deletions documentation/tips.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,21 +92,7 @@ for await (const commitData of pagination) {
<a name="unix"></a>
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
### UNIX Domain Sockets

Requests can also be sent via [UNIX Domain Sockets](https://serverfault.com/questions/124517/what-is-the-difference-between-unix-sockets-and-tcp-ip-sockets).\
Use the following URL scheme: `PROTOCOL://unix:SOCKET:PATH`

- `PROTOCOL` - `http` or `https`
- `SOCKET` - Absolute path to a unix domain socket, for example: `/var/run/docker.sock`
- `PATH` - Request path, for example: `/v2/keys`

```js
import got from 'got';

await got('http://unix:/var/run/docker.sock:/containers/json');

// Or without protocol (HTTP by default)
await got('unix:/var/run/docker.sock:/containers/json');
```
See the [`enableUnixSockets` option](./2-options.md#enableunixsockets).

### Testing

Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ For advanced JSON usage, check out the [`parseJson`](documentation/2-options.md#

- [x] [RFC compliant caching](documentation/cache.md)
- [x] [Proxy support](documentation/tips.md#proxying)
- [x] [Unix Domain Sockets](documentation/tips.md#unix)
- [x] [Unix Domain Sockets](documentation/2-options.md#enableunixsockets)

#### Integration

Expand Down
15 changes: 13 additions & 2 deletions source/core/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -827,6 +827,7 @@ const defaultInternals: Options['_internals'] = {
},
setHost: true,
maxHeaderSize: undefined,
enableUnixSockets: false,
};

const cloneInternals = (internals: typeof defaultInternals) => {
Expand Down Expand Up @@ -1401,7 +1402,7 @@ export default class Options {
this._internals.url = url;
decodeURI(urlString);

if (url.protocol === 'unix:') {
if (this._internals.enableUnixSockets && url.protocol === 'unix:') {
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
url.href = `http://unix${url.pathname}${url.search}`;
}

Expand All @@ -1427,7 +1428,7 @@ export default class Options {
this._internals.searchParams = undefined;
}

if (url.hostname === 'unix') {
if (this._internals.enableUnixSockets && url.hostname === 'unix') {
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(`${url.pathname}${url.search}`);

if (matches?.groups) {
Expand Down Expand Up @@ -2345,6 +2346,16 @@ export default class Options {
this._internals.maxHeaderSize = value;
}

get enableUnixSockets() {
return this._internals.enableUnixSockets;
}

set enableUnixSockets(value: boolean) {
assert.boolean(value);

this._internals.enableUnixSockets = value;
}

// eslint-disable-next-line @typescript-eslint/naming-convention
toJSON() {
return {...this._internals};
Expand Down
23 changes: 22 additions & 1 deletion test/redirects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,31 @@ const unixHostname: Handler = (_request, response) => {
response.end();
};

test('cannot redirect to unix protocol', withServer, async (t, server, got) => {
test('cannot redirect to UNIX protocol when UNIX sockets are enabled', withServer, async (t, server, got) => {
server.get('/protocol', unixProtocol);
server.get('/hostname', unixHostname);

const gotUnixSocketsEnabled = got.extend({enableUnixSockets: true});

t.assert(gotUnixSocketsEnabled.defaults.options.enableUnixSockets);
szmarczak marked this conversation as resolved.
Show resolved Hide resolved

await t.throwsAsync(gotUnixSocketsEnabled('protocol'), {
message: 'Cannot redirect to UNIX socket',
instanceOf: RequestError,
});

await t.throwsAsync(gotUnixSocketsEnabled('hostname'), {
message: 'Cannot redirect to UNIX socket',
instanceOf: RequestError,
});
});

test('cannot redirect to UNIX protocol when UNIX sockets are not enabled', withServer, async (t, server, got) => {
server.get('/protocol', unixProtocol);
server.get('/hostname', unixHostname);

t.assert(!got.defaults.options.enableUnixSockets);

await t.throwsAsync(got('protocol'), {
message: 'Cannot redirect to UNIX socket',
instanceOf: RequestError,
Expand Down
42 changes: 35 additions & 7 deletions test/unix-socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {Handler} from 'express';
import got from '../source/index.js';
import {withSocketServer} from './helpers/with-server.js';

const gotUnixSocketsEnabled = got.extend({enableUnixSockets: true});

const okHandler: Handler = (_request, response) => {
response.end('ok');
};
Expand All @@ -21,26 +23,26 @@ if (process.platform !== 'win32') {
server.on('/', okHandler);

const url = format('http://unix:%s:%s', server.socketPath, '/');
t.is((await got(url)).body, 'ok');
t.is((await gotUnixSocketsEnabled(url)).body, 'ok');
});

test('protocol-less works', withSocketServer, async (t, server) => {
server.on('/', okHandler);

const url = format('unix:%s:%s', server.socketPath, '/');
t.is((await got(url)).body, 'ok');
t.is((await gotUnixSocketsEnabled(url)).body, 'ok');
});

test('address with : works', withSocketServer, async (t, server) => {
server.on('/foo:bar', okHandler);

const url = format('unix:%s:%s', server.socketPath, '/foo:bar');
t.is((await got(url)).body, 'ok');
t.is((await gotUnixSocketsEnabled(url)).body, 'ok');
});

test('throws on invalid URL', async t => {
try {
await got('unix:', {retry: {limit: 0}});
await gotUnixSocketsEnabled('unix:', {retry: {limit: 0}});
} catch (error: any) {
t.regex(error.code, /ENOTFOUND|EAI_AGAIN/);
}
Expand All @@ -50,22 +52,48 @@ if (process.platform !== 'win32') {
server.on('/', okHandler);

const url = format('unix:%s:%s', server.socketPath, '/');
const instance = got.extend({prefixUrl: url});
const instance = gotUnixSocketsEnabled.extend({prefixUrl: url});
t.is((await instance('')).body, 'ok');
});

test('passes search params', withSocketServer, async (t, server) => {
server.on('/?a=1', okHandler);

const url = format('http://unix:%s:%s', server.socketPath, '/?a=1');
t.is((await got(url)).body, 'ok');
t.is((await gotUnixSocketsEnabled(url)).body, 'ok');
});

test('redirects work', withSocketServer, async (t, server) => {
server.on('/', redirectHandler);
server.on('/foo', okHandler);

const url = format('http://unix:%s:%s', server.socketPath, '/');
t.is((await got(url)).body, 'ok');
t.is((await gotUnixSocketsEnabled(url)).body, 'ok');
});

test('unix: fails when unix sockets are not enabled', async t => {
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
try {
t.assert(!got.defaults.options.enableUnixSockets);
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
await got('unix:');
} catch (error: any) {
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
t.assert(error.code === 'ERR_UNSUPPORTED_PROTOCOL');
return;
}

// Fail if no error is thrown
t.fail();
});

test('http://unix:/ fails when unix sockets are not enabled', async t => {
try {
t.assert(!got.defaults.options.enableUnixSockets);
await got('http://unix:');
} catch (error: any) {
t.regex(error.code, /ENOTFOUND|EAI_AGAIN/);
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
return;
}

// Fail if no error is thrown
t.fail();
});
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
}