Add server.publicBaseUrl config (#85075)

This commit is contained in:
Josh Dover 2020-12-08 17:02:39 -07:00 committed by GitHub
parent 18a99fcc43
commit e116fce08e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
37 changed files with 260 additions and 45 deletions

View file

@ -18,6 +18,10 @@
# default to `true` starting in Kibana 7.0. # default to `true` starting in Kibana 7.0.
#server.rewriteBasePath: false #server.rewriteBasePath: false
# Specifies the public URL at which Kibana is available for end users. If
# `server.basePath` is configured this URL should end with the same basePath.
#server.publicBaseUrl: ""
# The maximum payload size in bytes for incoming server requests. # The maximum payload size in bytes for incoming server requests.
#server.maxPayloadBytes: 1048576 #server.maxPayloadBytes: 1048576

View file

@ -18,6 +18,7 @@ export interface IBasePath
| --- | --- | --- | | --- | --- | --- |
| [get](./kibana-plugin-core-public.ibasepath.get.md) | <code>() =&gt; string</code> | Gets the <code>basePath</code> string. | | [get](./kibana-plugin-core-public.ibasepath.get.md) | <code>() =&gt; string</code> | Gets the <code>basePath</code> string. |
| [prepend](./kibana-plugin-core-public.ibasepath.prepend.md) | <code>(url: string) =&gt; string</code> | Prepends <code>path</code> with the basePath. | | [prepend](./kibana-plugin-core-public.ibasepath.prepend.md) | <code>(url: string) =&gt; string</code> | Prepends <code>path</code> with the basePath. |
| [publicBaseUrl](./kibana-plugin-core-public.ibasepath.publicbaseurl.md) | <code>string</code> | The server's publicly exposed base URL, if configured. Includes protocol, host, port (optional) and the [IBasePath.serverBasePath](./kibana-plugin-core-public.ibasepath.serverbasepath.md)<!-- -->. |
| [remove](./kibana-plugin-core-public.ibasepath.remove.md) | <code>(url: string) =&gt; string</code> | Removes the prepended basePath from the <code>path</code>. | | [remove](./kibana-plugin-core-public.ibasepath.remove.md) | <code>(url: string) =&gt; string</code> | Removes the prepended basePath from the <code>path</code>. |
| [serverBasePath](./kibana-plugin-core-public.ibasepath.serverbasepath.md) | <code>string</code> | Returns the server's root basePath as configured, without any namespace prefix.<!-- -->See for getting the basePath value for a specific request | | [serverBasePath](./kibana-plugin-core-public.ibasepath.serverbasepath.md) | <code>string</code> | Returns the server's root basePath as configured, without any namespace prefix.<!-- -->See for getting the basePath value for a specific request |

View file

@ -0,0 +1,18 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-public](./kibana-plugin-core-public.md) &gt; [IBasePath](./kibana-plugin-core-public.ibasepath.md) &gt; [publicBaseUrl](./kibana-plugin-core-public.ibasepath.publicbaseurl.md)
## IBasePath.publicBaseUrl property
The server's publicly exposed base URL, if configured. Includes protocol, host, port (optional) and the [IBasePath.serverBasePath](./kibana-plugin-core-public.ibasepath.serverbasepath.md)<!-- -->.
<b>Signature:</b>
```typescript
readonly publicBaseUrl?: string;
```
## Remarks
Should be used for generating external URL links back to this Kibana instance.

View file

@ -22,6 +22,7 @@ The constructor for this class is marked as internal. Third-party code should no
| --- | --- | --- | --- | | --- | --- | --- | --- |
| [get](./kibana-plugin-core-server.basepath.get.md) | | <code>(request: KibanaRequest &#124; LegacyRequest) =&gt; string</code> | returns <code>basePath</code> value, specific for an incoming request. | | [get](./kibana-plugin-core-server.basepath.get.md) | | <code>(request: KibanaRequest &#124; LegacyRequest) =&gt; string</code> | returns <code>basePath</code> value, specific for an incoming request. |
| [prepend](./kibana-plugin-core-server.basepath.prepend.md) | | <code>(path: string) =&gt; string</code> | Prepends <code>path</code> with the basePath. | | [prepend](./kibana-plugin-core-server.basepath.prepend.md) | | <code>(path: string) =&gt; string</code> | Prepends <code>path</code> with the basePath. |
| [publicBaseUrl](./kibana-plugin-core-server.basepath.publicbaseurl.md) | | <code>string</code> | The server's publicly exposed base URL, if configured. Includes protocol, host, port (optional) and the [BasePath.serverBasePath](./kibana-plugin-core-server.basepath.serverbasepath.md)<!-- -->. |
| [remove](./kibana-plugin-core-server.basepath.remove.md) | | <code>(path: string) =&gt; string</code> | Removes the prepended basePath from the <code>path</code>. | | [remove](./kibana-plugin-core-server.basepath.remove.md) | | <code>(path: string) =&gt; string</code> | Removes the prepended basePath from the <code>path</code>. |
| [serverBasePath](./kibana-plugin-core-server.basepath.serverbasepath.md) | | <code>string</code> | returns the server's basePath<!-- -->See [BasePath.get](./kibana-plugin-core-server.basepath.get.md) for getting the basePath value for a specific request | | [serverBasePath](./kibana-plugin-core-server.basepath.serverbasepath.md) | | <code>string</code> | returns the server's basePath<!-- -->See [BasePath.get](./kibana-plugin-core-server.basepath.get.md) for getting the basePath value for a specific request |
| [set](./kibana-plugin-core-server.basepath.set.md) | | <code>(request: KibanaRequest &#124; LegacyRequest, requestSpecificBasePath: string) =&gt; void</code> | sets <code>basePath</code> value, specific for an incoming request. | | [set](./kibana-plugin-core-server.basepath.set.md) | | <code>(request: KibanaRequest &#124; LegacyRequest, requestSpecificBasePath: string) =&gt; void</code> | sets <code>basePath</code> value, specific for an incoming request. |

View file

@ -0,0 +1,18 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [BasePath](./kibana-plugin-core-server.basepath.md) &gt; [publicBaseUrl](./kibana-plugin-core-server.basepath.publicbaseurl.md)
## BasePath.publicBaseUrl property
The server's publicly exposed base URL, if configured. Includes protocol, host, port (optional) and the [BasePath.serverBasePath](./kibana-plugin-core-server.basepath.serverbasepath.md)<!-- -->.
<b>Signature:</b>
```typescript
readonly publicBaseUrl?: string;
```
## Remarks
Should be used for generating external URL links back to this Kibana instance.

View file

@ -4,6 +4,7 @@
## HttpServerInfo interface ## HttpServerInfo interface
Information about what hostname, port, and protocol the server process is running on. Note that this may not match the URL that end-users access Kibana at. For the public URL, see [BasePath.publicBaseUrl](./kibana-plugin-core-server.basepath.publicbaseurl.md)<!-- -->.
<b>Signature:</b> <b>Signature:</b>

View file

@ -86,7 +86,7 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [HttpResourcesRenderOptions](./kibana-plugin-core-server.httpresourcesrenderoptions.md) | Allows to configure HTTP response parameters | | [HttpResourcesRenderOptions](./kibana-plugin-core-server.httpresourcesrenderoptions.md) | Allows to configure HTTP response parameters |
| [HttpResourcesServiceToolkit](./kibana-plugin-core-server.httpresourcesservicetoolkit.md) | Extended set of [KibanaResponseFactory](./kibana-plugin-core-server.kibanaresponsefactory.md) helpers used to respond with HTML or JS resource. | | [HttpResourcesServiceToolkit](./kibana-plugin-core-server.httpresourcesservicetoolkit.md) | Extended set of [KibanaResponseFactory](./kibana-plugin-core-server.kibanaresponsefactory.md) helpers used to respond with HTML or JS resource. |
| [HttpResponseOptions](./kibana-plugin-core-server.httpresponseoptions.md) | HTTP response parameters | | [HttpResponseOptions](./kibana-plugin-core-server.httpresponseoptions.md) | HTTP response parameters |
| [HttpServerInfo](./kibana-plugin-core-server.httpserverinfo.md) | | | [HttpServerInfo](./kibana-plugin-core-server.httpserverinfo.md) | Information about what hostname, port, and protocol the server process is running on. Note that this may not match the URL that end-users access Kibana at. For the public URL, see [BasePath.publicBaseUrl](./kibana-plugin-core-server.basepath.publicbaseurl.md)<!-- -->. |
| [HttpServiceSetup](./kibana-plugin-core-server.httpservicesetup.md) | Kibana HTTP Service provides own abstraction for work with HTTP stack. Plugins don't have direct access to <code>hapi</code> server and its primitives anymore. Moreover, plugins shouldn't rely on the fact that HTTP Service uses one or another library under the hood. This gives the platform flexibility to upgrade or changing our internal HTTP stack without breaking plugins. If the HTTP Service lacks functionality you need, we are happy to discuss and support your needs. | | [HttpServiceSetup](./kibana-plugin-core-server.httpservicesetup.md) | Kibana HTTP Service provides own abstraction for work with HTTP stack. Plugins don't have direct access to <code>hapi</code> server and its primitives anymore. Moreover, plugins shouldn't rely on the fact that HTTP Service uses one or another library under the hood. This gives the platform flexibility to upgrade or changing our internal HTTP stack without breaking plugins. If the HTTP Service lacks functionality you need, we are happy to discuss and support your needs. |
| [HttpServiceStart](./kibana-plugin-core-server.httpservicestart.md) | | | [HttpServiceStart](./kibana-plugin-core-server.httpservicestart.md) | |
| [I18nServiceSetup](./kibana-plugin-core-server.i18nservicesetup.md) | | | [I18nServiceSetup](./kibana-plugin-core-server.i18nservicesetup.md) | |

View file

@ -442,6 +442,11 @@ running behind a proxy. Use the <<server-rewriteBasePath, `server.rewriteBasePat
if it should remove the basePath from requests it receives, and to prevent a if it should remove the basePath from requests it receives, and to prevent a
deprecation warning at startup. This setting cannot end in a slash (`/`). deprecation warning at startup. This setting cannot end in a slash (`/`).
|[[server-publicBaseUrl]] `server.publicBaseUrl:`
| The publicly available URL that end-users access Kibana at. Must include the protocol, hostname, port
(if different than the defaults for `http` and `https`, 80 and 443 respectively), and the
<<server-basePath, `server.basePath`>> (if configured). This setting cannot end in a slash (`/`).
| [[server-compression]] `server.compression.enabled:` | [[server-compression]] `server.compression.enabled:`
| Set to `false` to disable HTTP compression for all responses. *Default: `true`* | Set to `false` to disable HTTP compression for all responses. *Default: `true`*

View file

@ -16,6 +16,7 @@ Object {
"maxPayload": 1000, "maxPayload": 1000,
"name": "kibana-hostname", "name": "kibana-hostname",
"port": 1234, "port": 1234,
"publicBaseUrl": "https://myhost.com/abc",
"rewriteBasePath": false, "rewriteBasePath": false,
"socketTimeout": 2000, "socketTimeout": 2000,
"ssl": Object { "ssl": Object {
@ -47,6 +48,7 @@ Object {
"maxPayload": 1000, "maxPayload": 1000,
"name": "kibana-hostname", "name": "kibana-hostname",
"port": 1234, "port": 1234,
"publicBaseUrl": "http://myhost.com/abc",
"rewriteBasePath": false, "rewriteBasePath": false,
"socketTimeout": 2000, "socketTimeout": 2000,
"ssl": Object { "ssl": Object {

View file

@ -90,6 +90,7 @@ describe('#get', () => {
keepaliveTimeout: 5000, keepaliveTimeout: 5000,
socketTimeout: 2000, socketTimeout: 2000,
port: 1234, port: 1234,
publicBaseUrl: 'https://myhost.com/abc',
rewriteBasePath: false, rewriteBasePath: false,
ssl: { enabled: true, keyPassphrase: 'some-phrase', someNewValue: 'new' }, ssl: { enabled: true, keyPassphrase: 'some-phrase', someNewValue: 'new' },
compression: { enabled: true }, compression: { enabled: true },
@ -113,6 +114,7 @@ describe('#get', () => {
keepaliveTimeout: 5000, keepaliveTimeout: 5000,
socketTimeout: 2000, socketTimeout: 2000,
port: 1234, port: 1234,
publicBaseUrl: 'http://myhost.com/abc',
rewriteBasePath: false, rewriteBasePath: false,
ssl: { enabled: false, certificate: 'cert', key: 'key' }, ssl: { enabled: false, certificate: 'cert', key: 'key' },
compression: { enabled: true }, compression: { enabled: true },

View file

@ -84,6 +84,7 @@ export class LegacyObjectToConfigAdapter extends ObjectToConfigAdapter {
maxPayload: configValue.maxPayloadBytes, maxPayload: configValue.maxPayloadBytes,
name: configValue.name, name: configValue.name,
port: configValue.port, port: configValue.port,
publicBaseUrl: configValue.publicBaseUrl,
rewriteBasePath: configValue.rewriteBasePath, rewriteBasePath: configValue.rewriteBasePath,
ssl: configValue.ssl, ssl: configValue.ssl,
keepaliveTimeout: configValue.keepaliveTimeout, keepaliveTimeout: configValue.keepaliveTimeout,

View file

@ -56,6 +56,7 @@ exports[`CollapsibleNav renders links grouped by category 1`] = `
"basePath": "/test", "basePath": "/test",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "/test", "serverBasePath": "/test",
} }
@ -2078,6 +2079,7 @@ exports[`CollapsibleNav renders the default nav 1`] = `
"basePath": "/test", "basePath": "/test",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "/test", "serverBasePath": "/test",
} }
@ -2313,6 +2315,7 @@ exports[`CollapsibleNav renders the default nav 2`] = `
"basePath": "/test", "basePath": "/test",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "/test", "serverBasePath": "/test",
} }
@ -2549,6 +2552,7 @@ exports[`CollapsibleNav renders the default nav 3`] = `
"basePath": "/test", "basePath": "/test",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "/test", "serverBasePath": "/test",
} }

View file

@ -243,6 +243,7 @@ exports[`Header renders 1`] = `
"basePath": "/test", "basePath": "/test",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "/test", "serverBasePath": "/test",
} }
@ -5354,6 +5355,7 @@ exports[`Header renders 1`] = `
"basePath": "/test", "basePath": "/test",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "/test", "serverBasePath": "/test",
} }

View file

@ -98,4 +98,13 @@ describe('BasePath', () => {
expect(new BasePath('/foo/bar', '/foo').serverBasePath).toEqual('/foo'); expect(new BasePath('/foo/bar', '/foo').serverBasePath).toEqual('/foo');
}); });
}); });
describe('publicBaseUrl', () => {
it('returns value passed into construtor', () => {
expect(new BasePath('/foo/bar', '/foo').publicBaseUrl).toEqual(undefined);
expect(new BasePath('/foo/bar', '/foo', 'http://myhost.com/foo').publicBaseUrl).toEqual(
'http://myhost.com/foo'
);
});
});
}); });

View file

@ -22,7 +22,8 @@ import { modifyUrl } from '@kbn/std';
export class BasePath { export class BasePath {
constructor( constructor(
private readonly basePath: string = '', private readonly basePath: string = '',
public readonly serverBasePath: string = basePath public readonly serverBasePath: string = basePath,
public readonly publicBaseUrl?: string
) {} ) {}
public get = () => { public get = () => {

View file

@ -41,7 +41,8 @@ export class HttpService implements CoreService<HttpSetup, HttpStart> {
const kibanaVersion = injectedMetadata.getKibanaVersion(); const kibanaVersion = injectedMetadata.getKibanaVersion();
const basePath = new BasePath( const basePath = new BasePath(
injectedMetadata.getBasePath(), injectedMetadata.getBasePath(),
injectedMetadata.getServerBasePath() injectedMetadata.getServerBasePath(),
injectedMetadata.getPublicBaseUrl()
); );
const fetchService = new Fetch({ basePath, kibanaVersion }); const fetchService = new Fetch({ basePath, kibanaVersion });
const loadingCount = this.loadingCount.setup({ fatalErrors }); const loadingCount = this.loadingCount.setup({ fatalErrors });

View file

@ -102,6 +102,15 @@ export interface IBasePath {
* See {@link BasePath.get} for getting the basePath value for a specific request * See {@link BasePath.get} for getting the basePath value for a specific request
*/ */
readonly serverBasePath: string; readonly serverBasePath: string;
/**
* The server's publicly exposed base URL, if configured. Includes protocol, host, port (optional) and the
* {@link IBasePath.serverBasePath}.
*
* @remarks
* Should be used for generating external URL links back to this Kibana instance.
*/
readonly publicBaseUrl?: string;
} }
/** /**

View file

@ -23,6 +23,7 @@ const createSetupContractMock = () => {
const setupContract: jest.Mocked<InjectedMetadataSetup> = { const setupContract: jest.Mocked<InjectedMetadataSetup> = {
getBasePath: jest.fn(), getBasePath: jest.fn(),
getServerBasePath: jest.fn(), getServerBasePath: jest.fn(),
getPublicBaseUrl: jest.fn(),
getKibanaVersion: jest.fn(), getKibanaVersion: jest.fn(),
getKibanaBranch: jest.fn(), getKibanaBranch: jest.fn(),
getCspConfig: jest.fn(), getCspConfig: jest.fn(),

View file

@ -44,6 +44,7 @@ export interface InjectedMetadataParams {
branch: string; branch: string;
basePath: string; basePath: string;
serverBasePath: string; serverBasePath: string;
publicBaseUrl: string;
category?: AppCategory; category?: AppCategory;
csp: { csp: {
warnLegacyBrowsers: boolean; warnLegacyBrowsers: boolean;
@ -95,6 +96,10 @@ export class InjectedMetadataService {
return this.state.serverBasePath; return this.state.serverBasePath;
}, },
getPublicBaseUrl: () => {
return this.state.publicBaseUrl;
},
getAnonymousStatusPage: () => { getAnonymousStatusPage: () => {
return this.state.anonymousStatusPage; return this.state.anonymousStatusPage;
}, },
@ -142,6 +147,7 @@ export class InjectedMetadataService {
export interface InjectedMetadataSetup { export interface InjectedMetadataSetup {
getBasePath: () => string; getBasePath: () => string;
getServerBasePath: () => string; getServerBasePath: () => string;
getPublicBaseUrl: () => string;
getKibanaBuildNumber: () => number; getKibanaBuildNumber: () => number;
getKibanaBranch: () => string; getKibanaBranch: () => string;
getKibanaVersion: () => string; getKibanaVersion: () => string;

View file

@ -760,6 +760,7 @@ export interface IAnonymousPaths {
export interface IBasePath { export interface IBasePath {
get: () => string; get: () => string;
prepend: (url: string) => string; prepend: (url: string) => string;
readonly publicBaseUrl?: string;
remove: (url: string) => string; remove: (url: string) => string;
// Warning: (ae-unresolved-link) The @link reference could not be resolved: The package "kibana" does not have an export "BasePath" // Warning: (ae-unresolved-link) The @link reference could not be resolved: The package "kibana" does not have an export "BasePath"
readonly serverBasePath: string; readonly serverBasePath: string;

View file

@ -24,6 +24,14 @@ Object {
} }
`; `;
exports[`basePath throws if appends a slash 1`] = `"[basePath]: must start with a slash, don't end with one"`;
exports[`basePath throws if is an empty string 1`] = `"[basePath]: must start with a slash, don't end with one"`;
exports[`basePath throws if missing prepended slash 1`] = `"[basePath]: must start with a slash, don't end with one"`;
exports[`basePath throws if not specified, but rewriteBasePath is set 1`] = `"cannot use [rewriteBasePath] when [basePath] is not specified"`;
exports[`has defaults for config 1`] = ` exports[`has defaults for config 1`] = `
Object { Object {
"autoListen": true, "autoListen": true,
@ -89,14 +97,6 @@ Object {
} }
`; `;
exports[`throws if basepath appends a slash 1`] = `"[basePath]: must start with a slash, don't end with one"`;
exports[`throws if basepath is an empty string 1`] = `"[basePath]: must start with a slash, don't end with one"`;
exports[`throws if basepath is missing prepended slash 1`] = `"[basePath]: must start with a slash, don't end with one"`;
exports[`throws if basepath is not specified, but rewriteBasePath is set 1`] = `"cannot use [rewriteBasePath] when [basePath] is not specified"`;
exports[`throws if invalid hostname 1`] = `"[host]: value must be a valid hostname (see RFC 1123)."`; exports[`throws if invalid hostname 1`] = `"[host]: value must be a valid hostname (see RFC 1123)."`;
exports[`with TLS throws if TLS is enabled but \`redirectHttpFromPort\` is equal to \`port\` 1`] = `"Kibana does not accept http traffic to [port] when ssl is enabled (only https is allowed), so [ssl.redirectHttpFromPort] cannot be configured to the same value. Both are [1234]."`; exports[`with TLS throws if TLS is enabled but \`redirectHttpFromPort\` is equal to \`port\` 1`] = `"Kibana does not accept http traffic to [port] when ssl is enabled (only https is allowed), so [ssl.redirectHttpFromPort] cannot be configured to the same value. Both are [1234]."`;

View file

@ -34,6 +34,18 @@ describe('BasePath', () => {
}); });
}); });
describe('publicBaseUrl', () => {
it('defaults to an undefined', () => {
const basePath = new BasePath();
expect(basePath.publicBaseUrl).toBe(undefined);
});
it('returns the publicBaseUrl', () => {
const basePath = new BasePath('/server', 'http://myhost.com/server');
expect(basePath.publicBaseUrl).toBe('http://myhost.com/server');
});
});
describe('#get()', () => { describe('#get()', () => {
it('returns base path associated with an incoming Legacy.Request request', () => { it('returns base path associated with an incoming Legacy.Request request', () => {
const request = httpServerMock.createRawRequest(); const request = httpServerMock.createRawRequest();

View file

@ -34,10 +34,19 @@ export class BasePath {
* See {@link BasePath.get} for getting the basePath value for a specific request * See {@link BasePath.get} for getting the basePath value for a specific request
*/ */
public readonly serverBasePath: string; public readonly serverBasePath: string;
/**
* The server's publicly exposed base URL, if configured. Includes protocol, host, port (optional) and the
* {@link BasePath.serverBasePath}.
*
* @remarks
* Should be used for generating external URL links back to this Kibana instance.
*/
public readonly publicBaseUrl?: string;
/** @internal */ /** @internal */
constructor(serverBasePath: string = '') { constructor(serverBasePath: string = '', publicBaseUrl?: string) {
this.serverBasePath = serverBasePath; this.serverBasePath = serverBasePath;
this.publicBaseUrl = publicBaseUrl;
} }
/** /**

View file

@ -119,36 +119,104 @@ test('can specify max payload as string', () => {
expect(configValue.maxPayload.getValueInBytes()).toBe(2 * 1024 * 1024); expect(configValue.maxPayload.getValueInBytes()).toBe(2 * 1024 * 1024);
}); });
test('throws if basepath is missing prepended slash', () => { describe('basePath', () => {
const httpSchema = config.schema; test('throws if missing prepended slash', () => {
const obj = { const httpSchema = config.schema;
basePath: 'foo', const obj = {
}; basePath: 'foo',
expect(() => httpSchema.validate(obj)).toThrowErrorMatchingSnapshot(); };
expect(() => httpSchema.validate(obj)).toThrowErrorMatchingSnapshot();
});
test('throws if appends a slash', () => {
const httpSchema = config.schema;
const obj = {
basePath: '/foo/',
};
expect(() => httpSchema.validate(obj)).toThrowErrorMatchingSnapshot();
});
test('throws if is an empty string', () => {
const httpSchema = config.schema;
const obj = {
basePath: '',
};
expect(() => httpSchema.validate(obj)).toThrowErrorMatchingSnapshot();
});
test('throws if not specified, but rewriteBasePath is set', () => {
const httpSchema = config.schema;
const obj = {
rewriteBasePath: true,
};
expect(() => httpSchema.validate(obj)).toThrowErrorMatchingSnapshot();
});
}); });
test('throws if basepath appends a slash', () => { describe('publicBaseUrl', () => {
const httpSchema = config.schema; test('throws if invalid HTTP(S) URL', () => {
const obj = { const httpSchema = config.schema;
basePath: '/foo/', expect(() =>
}; httpSchema.validate({ publicBaseUrl: 'myhost.com' })
expect(() => httpSchema.validate(obj)).toThrowErrorMatchingSnapshot(); ).toThrowErrorMatchingInlineSnapshot(
}); `"[publicBaseUrl]: expected URI with scheme [http|https]."`
);
expect(() =>
httpSchema.validate({ publicBaseUrl: '//myhost.com' })
).toThrowErrorMatchingInlineSnapshot(
`"[publicBaseUrl]: expected URI with scheme [http|https]."`
);
expect(() =>
httpSchema.validate({ publicBaseUrl: 'ftp://myhost.com' })
).toThrowErrorMatchingInlineSnapshot(
`"[publicBaseUrl]: expected URI with scheme [http|https]."`
);
});
test('throws if basepath is an empty string', () => { test('throws if includes hash, query, or auth', () => {
const httpSchema = config.schema; const httpSchema = config.schema;
const obj = { expect(() =>
basePath: '', httpSchema.validate({ publicBaseUrl: 'http://myhost.com/?a=b' })
}; ).toThrowErrorMatchingInlineSnapshot(
expect(() => httpSchema.validate(obj)).toThrowErrorMatchingSnapshot(); `"[publicBaseUrl] may only contain a protocol, host, port, and pathname"`
}); );
expect(() =>
httpSchema.validate({ publicBaseUrl: 'http://myhost.com/#a' })
).toThrowErrorMatchingInlineSnapshot(
`"[publicBaseUrl] may only contain a protocol, host, port, and pathname"`
);
expect(() =>
httpSchema.validate({ publicBaseUrl: 'http://user:pass@myhost.com' })
).toThrowErrorMatchingInlineSnapshot(
`"[publicBaseUrl] may only contain a protocol, host, port, and pathname"`
);
});
test('throws if basepath is not specified, but rewriteBasePath is set', () => { test('throws if basePath and publicBaseUrl are specified, but do not match', () => {
const httpSchema = config.schema; const httpSchema = config.schema;
const obj = { expect(() =>
rewriteBasePath: true, httpSchema.validate({
}; basePath: '/foo',
expect(() => httpSchema.validate(obj)).toThrowErrorMatchingSnapshot(); publicBaseUrl: 'https://myhost.com/',
})
).toThrowErrorMatchingInlineSnapshot(
`"[publicBaseUrl] must contain the [basePath]: / !== /foo"`
);
});
test('does not throw if valid URL and matches basePath', () => {
const httpSchema = config.schema;
expect(() => httpSchema.validate({ publicBaseUrl: 'http://myhost.com' })).not.toThrow();
expect(() => httpSchema.validate({ publicBaseUrl: 'http://myhost.com/' })).not.toThrow();
expect(() => httpSchema.validate({ publicBaseUrl: 'https://myhost.com' })).not.toThrow();
expect(() =>
httpSchema.validate({ publicBaseUrl: 'https://myhost.com/foo', basePath: '/foo' })
).not.toThrow();
expect(() => httpSchema.validate({ publicBaseUrl: 'http://myhost.com:8080' })).not.toThrow();
expect(() =>
httpSchema.validate({ publicBaseUrl: 'http://myhost.com:4/foo', basePath: '/foo' })
).not.toThrow();
});
}); });
test('accepts only valid uuids for server.uuid', () => { test('accepts only valid uuids for server.uuid', () => {

View file

@ -19,6 +19,7 @@
import { ByteSizeValue, schema, TypeOf } from '@kbn/config-schema'; import { ByteSizeValue, schema, TypeOf } from '@kbn/config-schema';
import { hostname } from 'os'; import { hostname } from 'os';
import url from 'url';
import { CspConfigType, CspConfig, ICspConfig } from '../csp'; import { CspConfigType, CspConfig, ICspConfig } from '../csp';
import { SslConfig, sslSchema } from './ssl_config'; import { SslConfig, sslSchema } from './ssl_config';
@ -32,11 +33,12 @@ const match = (regex: RegExp, errorMsg: string) => (str: string) =>
// before update to make sure it's in sync with validation rules in Legacy // before update to make sure it's in sync with validation rules in Legacy
// https://github.com/elastic/kibana/blob/master/src/legacy/server/config/schema.js // https://github.com/elastic/kibana/blob/master/src/legacy/server/config/schema.js
export const config = { export const config = {
path: 'server', path: 'server' as const,
schema: schema.object( schema: schema.object(
{ {
name: schema.string({ defaultValue: () => hostname() }), name: schema.string({ defaultValue: () => hostname() }),
autoListen: schema.boolean({ defaultValue: true }), autoListen: schema.boolean({ defaultValue: true }),
publicBaseUrl: schema.maybe(schema.uri({ scheme: ['http', 'https'] })),
basePath: schema.maybe( basePath: schema.maybe(
schema.string({ schema.string({
validate: match(validBasePathRegex, "must start with a slash, don't end with one"), validate: match(validBasePathRegex, "must start with a slash, don't end with one"),
@ -106,6 +108,17 @@ export const config = {
if (!rawConfig.basePath && rawConfig.rewriteBasePath) { if (!rawConfig.basePath && rawConfig.rewriteBasePath) {
return 'cannot use [rewriteBasePath] when [basePath] is not specified'; return 'cannot use [rewriteBasePath] when [basePath] is not specified';
} }
if (rawConfig.publicBaseUrl) {
const parsedUrl = url.parse(rawConfig.publicBaseUrl);
if (parsedUrl.query || parsedUrl.hash || parsedUrl.auth) {
return `[publicBaseUrl] may only contain a protocol, host, port, and pathname`;
}
if (parsedUrl.path !== (rawConfig.basePath ?? '/')) {
return `[publicBaseUrl] must contain the [basePath]: ${parsedUrl.path} !== ${rawConfig.basePath}`;
}
}
if (!rawConfig.compression.enabled && rawConfig.compression.referrerWhitelist) { if (!rawConfig.compression.enabled && rawConfig.compression.referrerWhitelist) {
return 'cannot use [compression.referrerWhitelist] when [compression.enabled] is set to false'; return 'cannot use [compression.referrerWhitelist] when [compression.enabled] is set to false';
} }
@ -138,6 +151,7 @@ export class HttpConfig {
public customResponseHeaders: Record<string, string | string[]>; public customResponseHeaders: Record<string, string | string[]>;
public maxPayload: ByteSizeValue; public maxPayload: ByteSizeValue;
public basePath?: string; public basePath?: string;
public publicBaseUrl?: string;
public rewriteBasePath: boolean; public rewriteBasePath: boolean;
public ssl: SslConfig; public ssl: SslConfig;
public compression: { enabled: boolean; referrerWhitelist?: string[] }; public compression: { enabled: boolean; referrerWhitelist?: string[] };
@ -165,6 +179,7 @@ export class HttpConfig {
this.maxPayload = rawHttpConfig.maxPayload; this.maxPayload = rawHttpConfig.maxPayload;
this.name = rawHttpConfig.name; this.name = rawHttpConfig.name;
this.basePath = rawHttpConfig.basePath; this.basePath = rawHttpConfig.basePath;
this.publicBaseUrl = rawHttpConfig.publicBaseUrl;
this.keepaliveTimeout = rawHttpConfig.keepaliveTimeout; this.keepaliveTimeout = rawHttpConfig.keepaliveTimeout;
this.socketTimeout = rawHttpConfig.socketTimeout; this.socketTimeout = rawHttpConfig.socketTimeout;
this.rewriteBasePath = rawHttpConfig.rewriteBasePath; this.rewriteBasePath = rawHttpConfig.rewriteBasePath;

View file

@ -119,7 +119,7 @@ export class HttpServer {
await this.server.register([HapiStaticFiles]); await this.server.register([HapiStaticFiles]);
this.config = config; this.config = config;
const basePathService = new BasePath(config.basePath); const basePathService = new BasePath(config.basePath, config.publicBaseUrl);
this.setupBasePathRewrite(config, basePathService); this.setupBasePathRewrite(config, basePathService);
this.setupConditionalCompression(config); this.setupConditionalCompression(config);
this.setupRequestStateAssignment(config); this.setupRequestStateAssignment(config);

View file

@ -60,8 +60,12 @@ export type InternalHttpServiceStartMock = jest.Mocked<InternalHttpServiceStart>
basePath: BasePathMocked; basePath: BasePathMocked;
}; };
const createBasePathMock = (serverBasePath = '/mock-server-basepath'): BasePathMocked => ({ const createBasePathMock = (
serverBasePath = '/mock-server-basepath',
publicBaseUrl = 'http://myhost.com/mock-server-basepath'
): BasePathMocked => ({
serverBasePath, serverBasePath,
publicBaseUrl,
get: jest.fn().mockReturnValue(serverBasePath), get: jest.fn().mockReturnValue(serverBasePath),
set: jest.fn(), set: jest.fn(),
prepend: jest.fn(), prepend: jest.fn(),

View file

@ -316,7 +316,12 @@ export interface InternalHttpServiceStart extends HttpServiceStart {
isListening: () => boolean; isListening: () => boolean;
} }
/** @public */ /**
* Information about what hostname, port, and protocol the server process is
* running on. Note that this may not match the URL that end-users access
* Kibana at. For the public URL, see {@link BasePath.publicBaseUrl}.
* @public
*/
export interface HttpServerInfo { export interface HttpServerInfo {
/** The name of the Kibana server */ /** The name of the Kibana server */
name: string; name: string;

View file

@ -36,6 +36,7 @@ Object {
"user": Object {}, "user": Object {},
}, },
}, },
"publicBaseUrl": "http://myhost.com/mock-server-basepath",
"serverBasePath": "/mock-server-basepath", "serverBasePath": "/mock-server-basepath",
"uiPlugins": Array [], "uiPlugins": Array [],
"vars": Object {}, "vars": Object {},
@ -79,6 +80,7 @@ Object {
"user": Object {}, "user": Object {},
}, },
}, },
"publicBaseUrl": "http://myhost.com/mock-server-basepath",
"serverBasePath": "/mock-server-basepath", "serverBasePath": "/mock-server-basepath",
"uiPlugins": Array [], "uiPlugins": Array [],
"vars": Object {}, "vars": Object {},
@ -126,6 +128,7 @@ Object {
}, },
}, },
}, },
"publicBaseUrl": "http://myhost.com/mock-server-basepath",
"serverBasePath": "/mock-server-basepath", "serverBasePath": "/mock-server-basepath",
"uiPlugins": Array [], "uiPlugins": Array [],
"vars": Object {}, "vars": Object {},
@ -169,6 +172,7 @@ Object {
"user": Object {}, "user": Object {},
}, },
}, },
"publicBaseUrl": "http://myhost.com/mock-server-basepath",
"serverBasePath": "/mock-server-basepath", "serverBasePath": "/mock-server-basepath",
"uiPlugins": Array [], "uiPlugins": Array [],
"vars": Object {}, "vars": Object {},
@ -212,6 +216,7 @@ Object {
"user": Object {}, "user": Object {},
}, },
}, },
"publicBaseUrl": "http://myhost.com/mock-server-basepath",
"serverBasePath": "/mock-server-basepath", "serverBasePath": "/mock-server-basepath",
"uiPlugins": Array [], "uiPlugins": Array [],
"vars": Object {}, "vars": Object {},

View file

@ -52,7 +52,7 @@ export class RenderingService {
packageInfo: this.coreContext.env.packageInfo, packageInfo: this.coreContext.env.packageInfo,
}; };
const basePath = http.basePath.get(request); const basePath = http.basePath.get(request);
const serverBasePath = http.basePath.serverBasePath; const { serverBasePath, publicBaseUrl } = http.basePath;
const settings = { const settings = {
defaults: uiSettings.getRegistered(), defaults: uiSettings.getRegistered(),
user: includeUserSettings ? await uiSettings.getUserProvided() : {}, user: includeUserSettings ? await uiSettings.getUserProvided() : {},
@ -72,6 +72,7 @@ export class RenderingService {
branch: env.packageInfo.branch, branch: env.packageInfo.branch,
basePath, basePath,
serverBasePath, serverBasePath,
publicBaseUrl,
env, env,
anonymousStatusPage: status.isStatusPageAnonymous(), anonymousStatusPage: status.isStatusPageAnonymous(),
i18n: { i18n: {

View file

@ -40,6 +40,7 @@ export interface RenderingMetadata {
branch: string; branch: string;
basePath: string; basePath: string;
serverBasePath: string; serverBasePath: string;
publicBaseUrl?: string;
env: { env: {
mode: EnvironmentMode; mode: EnvironmentMode;
packageInfo: PackageInfo; packageInfo: PackageInfo;

View file

@ -269,9 +269,10 @@ export interface AuthToolkit {
// @public // @public
export class BasePath { export class BasePath {
// @internal // @internal
constructor(serverBasePath?: string); constructor(serverBasePath?: string, publicBaseUrl?: string);
get: (request: KibanaRequest | LegacyRequest) => string; get: (request: KibanaRequest | LegacyRequest) => string;
prepend: (path: string) => string; prepend: (path: string) => string;
readonly publicBaseUrl?: string;
remove: (path: string) => string; remove: (path: string) => string;
readonly serverBasePath: string; readonly serverBasePath: string;
set: (request: KibanaRequest | LegacyRequest, requestSpecificBasePath: string) => void; set: (request: KibanaRequest | LegacyRequest, requestSpecificBasePath: string) => void;
@ -862,7 +863,7 @@ export interface HttpResponseOptions {
// @public // @public
export type HttpResponsePayload = undefined | string | Record<string, any> | Buffer | Stream; export type HttpResponsePayload = undefined | string | Record<string, any> | Buffer | Stream;
// @public (undocumented) // @public
export interface HttpServerInfo { export interface HttpServerInfo {
hostname: string; hostname: string;
name: string; name: string;

View file

@ -69,6 +69,7 @@ export default () =>
customResponseHeaders: HANDLED_IN_NEW_PLATFORM, customResponseHeaders: HANDLED_IN_NEW_PLATFORM,
keepaliveTimeout: HANDLED_IN_NEW_PLATFORM, keepaliveTimeout: HANDLED_IN_NEW_PLATFORM,
maxPayloadBytes: HANDLED_IN_NEW_PLATFORM, maxPayloadBytes: HANDLED_IN_NEW_PLATFORM,
publicBaseUrl: HANDLED_IN_NEW_PLATFORM,
socketTimeout: HANDLED_IN_NEW_PLATFORM, socketTimeout: HANDLED_IN_NEW_PLATFORM,
ssl: HANDLED_IN_NEW_PLATFORM, ssl: HANDLED_IN_NEW_PLATFORM,
compression: HANDLED_IN_NEW_PLATFORM, compression: HANDLED_IN_NEW_PLATFORM,

View file

@ -13,6 +13,7 @@ exports[`DashboardEmptyScreen renders correctly with readonly mode 1`] = `
"basePath": "", "basePath": "",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "", "serverBasePath": "",
}, },
@ -376,6 +377,7 @@ exports[`DashboardEmptyScreen renders correctly with visualize paragraph 1`] = `
"basePath": "", "basePath": "",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "", "serverBasePath": "",
}, },
@ -747,6 +749,7 @@ exports[`DashboardEmptyScreen renders correctly without visualize paragraph 1`]
"basePath": "", "basePath": "",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "", "serverBasePath": "",
}, },

View file

@ -262,6 +262,7 @@ exports[`SavedObjectsTable should render normally 1`] = `
"basePath": "", "basePath": "",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "", "serverBasePath": "",
} }

View file

@ -175,6 +175,7 @@ exports[`Flyout conflicts should allow conflict resolution 2`] = `
"basePath": "", "basePath": "",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "", "serverBasePath": "",
}, },

View file

@ -316,6 +316,7 @@ exports[`TelemetryManagementSectionComponent renders null because allowChangingO
"basePath": "", "basePath": "",
"get": [Function], "get": [Function],
"prepend": [Function], "prepend": [Function],
"publicBaseUrl": undefined,
"remove": [Function], "remove": [Function],
"serverBasePath": "", "serverBasePath": "",
}, },