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 5 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
22 changes: 22 additions & 0 deletions documentation/2-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -918,6 +918,28 @@ 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`.

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

Set to `true` to enable unix socket domain.
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';

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');
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing the actual option.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we actually include the option in all examples? This way we'd encourage users to explicitly enable/disable UNIX sockets, which will ease transitioning to a new major release.

```

## 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#enableunixsocket)
- `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#enableunixsocket): `http://unix:SOCKET:PATH`

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

Expand Down
17 changes: 1 addition & 16 deletions documentation/tips.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,24 +89,9 @@ 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 option [enableUnixSocket](./2-options.md#enableunixsocket) for more.
szmarczak marked this conversation as resolved.
Show resolved Hide resolved

### 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#enableunixsocket)

#### 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,
enableUnixSocket: 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.enableUnixSocket && url.protocol === 'unix:') {
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.enableUnixSocket && url.hostname === 'unix') {
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 enableUnixSocket() {
return this._internals.enableUnixSocket;
}

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

this._internals.enableUnixSocket = 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 socket is enabled', withServer, async (t, server, got) => {
server.get('/protocol', unixProtocol);
server.get('/hostname', unixHostname);

const gotUnixSocketEnabled = got.extend({enableUnixSocket: true});

t.assert(gotUnixSocketEnabled.defaults.options.enableUnixSocket);

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

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

test('cannot redirect to unix protocol when unix socket is not enabled', withServer, async (t, server, got) => {
szmarczak marked this conversation as resolved.
Show resolved Hide resolved
server.get('/protocol', unixProtocol);
server.get('/hostname', unixHostname);

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

await t.throwsAsync(got('protocol'), {
message: 'Cannot redirect to UNIX socket',
instanceOf: RequestError,
Expand Down
40 changes: 33 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 gotUnixSocketEnabled = got.extend({enableUnixSocket: 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 gotUnixSocketEnabled(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 gotUnixSocketEnabled(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 gotUnixSocketEnabled(url)).body, 'ok');
});

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

const url = format('unix:%s:%s', server.socketPath, '/');
const instance = got.extend({prefixUrl: url});
const instance = gotUnixSocketEnabled.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 gotUnixSocketEnabled(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 gotUnixSocketEnabled(url)).body, 'ok');
});

test('unix: fails when unix socket is not enabled', async t => {
try {
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 socket is not enabled', async t => {
try {
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
}