Skip to content

Commit

Permalink
Migrate to NP plugin.
Browse files Browse the repository at this point in the history
  • Loading branch information
azasypkin committed Jun 26, 2019
1 parent 3cff787 commit e901c8f
Show file tree
Hide file tree
Showing 73 changed files with 1,188 additions and 988 deletions.
1 change: 0 additions & 1 deletion kibana.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ export namespace Legacy {
export namespace elasticsearch {
export type Plugin = LegacyElasticsearch.ElasticsearchPlugin;
export type Cluster = LegacyElasticsearch.Cluster;
export type CallClusterWithRequest = LegacyElasticsearch.CallClusterWithRequest;
export type ClusterConfig = LegacyElasticsearch.ClusterConfig;
export type CallClusterOptions = LegacyElasticsearch.CallClusterOptions;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/kbn-config-schema/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ function uri(options?: URIOptions): Type<string> {
return new URIType(options);
}

function literal<T extends string | number | boolean>(value: T): Type<T> {
function literal<T extends string | number | boolean | null>(value: T): Type<T> {
return new LiteralType(value);
}

Expand Down Expand Up @@ -167,7 +167,7 @@ function siblingRef<T>(key: string): SiblingReference<T> {

function conditional<A extends ConditionalTypeValue, B, C>(
leftOperand: Reference<A>,
rightOperand: Reference<A> | A,
rightOperand: Reference<A> | A | Type<unknown>,
equalType: Type<B>,
notEqualType: Type<C>,
options?: TypeOptions<B | C>
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-config-schema/src/references/reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { internals, Reference as InternalReference } from '../internals';
export class Reference<T> {
public static isReference<V>(value: V | Reference<V> | undefined): value is Reference<V> {
return (
value !== undefined &&
value != null &&
typeof (value as Reference<V>).getSchema === 'function' &&
internals.isRef((value as Reference<V>).getSchema())
);
Expand Down
7 changes: 5 additions & 2 deletions packages/kbn-config-schema/src/types/conditional_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,16 @@ export type ConditionalTypeValue = string | number | boolean | object | null;
export class ConditionalType<A extends ConditionalTypeValue, B, C> extends Type<B | C> {
constructor(
leftOperand: Reference<A>,
rightOperand: Reference<A> | A,
rightOperand: Reference<A> | A | Type<unknown>,
equalType: Type<B>,
notEqualType: Type<C>,
options?: TypeOptions<B | C>
) {
const schema = internals.when(leftOperand.getSchema(), {
is: Reference.isReference(rightOperand) ? rightOperand.getSchema() : rightOperand,
is:
Reference.isReference(rightOperand) || rightOperand instanceof Type
? rightOperand.getSchema()
: rightOperand,
otherwise: notEqualType.getSchema(),
then: equalType.getSchema(),
});
Expand Down
2 changes: 2 additions & 0 deletions src/core/server/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export interface PackageInfo {
branch: string;
buildNum: number;
buildSha: string;
dist: boolean;
}

export interface EnvironmentMode {
Expand Down Expand Up @@ -137,6 +138,7 @@ export class Env {
branch: pkg.branch,
buildNum: isKibanaDistributable ? pkg.build.number : Number.MAX_SAFE_INTEGER,
buildSha: isKibanaDistributable ? pkg.build.sha : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
dist: isKibanaDistributable,
version: pkg.version,
});
}
Expand Down
2 changes: 2 additions & 0 deletions src/core/server/http/http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ export interface HttpServerSetup {
isAuthenticated: AuthStateStorage['isAuthenticated'];
getAuthHeaders: AuthHeadersStorage['get'];
};
isTLSEnabled: boolean;
}

export class HttpServer {
Expand Down Expand Up @@ -128,6 +129,7 @@ export class HttpServer {
// bridge core and the "legacy" Kibana internally. Once this bridge isn't
// needed anymore we shouldn't return the instance from this method.
server: this.server,
isTLSEnabled: config.ssl.enabled,
};
}

Expand Down
1 change: 1 addition & 0 deletions src/core/server/http/http_service.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const createSetupContractMock = () => {
getAuthHeaders: jest.fn(),
},
createNewServer: jest.fn(),
isTLSEnabled: false,
};
setupContract.createNewServer.mockResolvedValue({} as HttpServerSetup);
return setupContract;
Expand Down
11 changes: 4 additions & 7 deletions src/core/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@
* @packageDocumentation
*/

import { Observable } from 'rxjs';
import { ClusterClient, ElasticsearchServiceSetup } from './elasticsearch';
import { ElasticsearchServiceSetup } from './elasticsearch';
import { HttpServiceSetup, HttpServiceStart } from './http';
import { PluginsServiceSetup, PluginsServiceStart } from './plugins';

Expand Down Expand Up @@ -102,24 +101,22 @@ export {
SavedObjectsUpdateResponse,
} from './saved_objects';

export { RecursiveReadonly } from '../utils';
export { RecursiveReadonly, deepFreeze } from '../utils';

/**
* Context passed to the plugins `setup` method.
*
* @public
*/
export interface CoreSetup {
elasticsearch: {
adminClient$: Observable<ClusterClient>;
dataClient$: Observable<ClusterClient>;
};
elasticsearch: ElasticsearchServiceSetup;
http: {
registerOnPreAuth: HttpServiceSetup['registerOnPreAuth'];
registerAuth: HttpServiceSetup['registerAuth'];
registerOnPostAuth: HttpServiceSetup['registerOnPostAuth'];
basePath: HttpServiceSetup['basePath'];
createNewServer: HttpServiceSetup['createNewServer'];
isTLSEnabled: HttpServiceSetup['isTLSEnabled'];
};
}

Expand Down
3 changes: 3 additions & 0 deletions src/core/server/plugins/plugin_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,16 @@ export function createPluginSetupContext<TPlugin, TPluginDependencies>(
elasticsearch: {
adminClient$: deps.elasticsearch.adminClient$,
dataClient$: deps.elasticsearch.dataClient$,
createClient: deps.elasticsearch.createClient,
legacy: deps.elasticsearch.legacy,
},
http: {
registerOnPreAuth: deps.http.registerOnPreAuth,
registerAuth: deps.http.registerAuth,
registerOnPostAuth: deps.http.registerOnPostAuth,
basePath: deps.http.basePath,
createNewServer: deps.http.createNewServer,
isTLSEnabled: deps.http.isTLSEnabled,
},
};
}
Expand Down
2 changes: 1 addition & 1 deletion src/legacy/core_plugins/elasticsearch/lib/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class Cluster {
constructor(private readonly clusterClient: ClusterClient) {}

public callWithRequest = async (
req: Request | FakeRequest | KibanaRequest,
req: Request | FakeRequest,
endpoint: string,
clientParams?: Record<string, unknown>,
options?: CallAPIOptions
Expand Down
1 change: 1 addition & 0 deletions x-pack/dev-tools/jest/create_jest_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export function createJestConfig({
return {
rootDir: xPackKibanaDirectory,
roots: [
'<rootDir>/plugins',
'<rootDir>/legacy/plugins',
'<rootDir>/legacy/server',
],
Expand Down
54 changes: 0 additions & 54 deletions x-pack/legacy/plugins/security/__snapshots__/index.test.js.snap

This file was deleted.

7 changes: 5 additions & 2 deletions x-pack/legacy/plugins/security/common/model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,8 @@ export { Role, RoleIndexPrivilege, RoleKibanaPrivilege } from './role';
export { FeaturesPrivileges } from './features_privileges';
export { RawKibanaPrivileges, RawKibanaFeaturePrivileges } from './raw_kibana_privileges';
export { KibanaPrivileges } from './kibana_privileges';
export { User, EditUser, getUserDisplayName } from './user';
export { AuthenticatedUser, canUserChangePassword } from './authenticated_user';
export { User, EditUser, getUserDisplayName } from '../../../../../plugins/security/common/model';
export {
AuthenticatedUser,
canUserChangePassword,
} from '../../../../../plugins/security/common/model';
3 changes: 0 additions & 3 deletions x-pack/legacy/plugins/security/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,13 @@

import { Legacy } from 'kibana';
import { AuthenticatedUser } from './common/model';
import { AuthenticationResult, DeauthenticationResult } from './server/lib/authentication';
import { AuthorizationService } from './server/lib/authorization/service';

/**
* Public interface of the security plugin.
*/
export interface SecurityPlugin {
authorization: Readonly<AuthorizationService>;
authenticate: (request: Legacy.Request) => Promise<AuthenticationResult>;
deauthenticate: (request: Legacy.Request) => Promise<DeauthenticationResult>;
getUser: (request: Legacy.Request) => Promise<AuthenticatedUser>;
isAuthenticated: (request: Legacy.Request) => Promise<boolean>;
}
74 changes: 32 additions & 42 deletions x-pack/legacy/plugins/security/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
*/

import { resolve } from 'path';
import { getUserProvider } from './server/lib/get_user';
import { initAuthenticateApi } from './server/routes/api/v1/authenticate';
import { initUsersApi } from './server/routes/api/v1/users';
import { initExternalRolesApi } from './server/routes/api/external/roles';
Expand All @@ -15,7 +14,6 @@ import { initOverwrittenSessionView } from './server/routes/views/overwritten_se
import { initLoginView } from './server/routes/views/login';
import { initLogoutView } from './server/routes/views/logout';
import { initLoggedOutView } from './server/routes/views/logged_out';
import { validateConfig } from './server/lib/validate_config';
import { initAuthentication } from './server/lib/authentication';
import { checkLicense } from './server/lib/check_license';
import { SecurityAuditLogger } from './server/lib/audit_logger';
Expand All @@ -33,30 +31,20 @@ import { SecureSavedObjectsClientWrapper } from './server/lib/saved_objects_clie
import { deepFreeze } from './server/lib/deep_freeze';
import { createOptionalPlugin } from '../../server/lib/optional_plugin';

let defaultVars;
export const security = (kibana) => new kibana.Plugin({
id: 'security',
configPrefix: 'xpack.security',
publicDir: resolve(__dirname, 'public'),
require: ['kibana', 'elasticsearch', 'xpack_main'],

config(Joi) {
const providerOptionsSchema = (providerName, schema) => Joi.any()
.when('providers', {
is: Joi.array().items(Joi.string().valid(providerName).required(), Joi.string()),
then: schema,
otherwise: Joi.any().forbidden(),
});

return Joi.object({
enabled: Joi.boolean().default(true),
cookieName: Joi.string().default('sid'),
encryptionKey: Joi.when(Joi.ref('$dist'), {
is: true,
then: Joi.string(),
otherwise: Joi.string().default('a'.repeat(32)),
}),
sessionTimeout: Joi.number().allow(null).default(null),
secureCookies: Joi.boolean().default(false),
cookieName: Joi.any().description('This key is handled in the new platform security plugin ONLY'),
encryptionKey: Joi.any().description('This key is handled in the new platform security plugin ONLY'),
sessionTimeout: Joi.any().description('This key is handled in the new platform security plugin ONLY'),
secureCookies: Joi.any().description('This key is handled in the new platform security plugin ONLY'),
authorization: Joi.object({
legacyFallback: Joi.object({
enabled: Joi.boolean().default(true) // deprecated
Expand All @@ -65,11 +53,7 @@ export const security = (kibana) => new kibana.Plugin({
audit: Joi.object({
enabled: Joi.boolean().default(false)
}).default(),
authc: Joi.object({
providers: Joi.array().items(Joi.string()).default(['basic']),
oidc: providerOptionsSchema('oidc', Joi.object({ realm: Joi.string().required() }).required()),
saml: providerOptionsSchema('saml', Joi.object({ realm: Joi.string().required() }).required()),
}).default()
authc: Joi.any().description('This key is handled in the new platform security plugin ONLY')
}).default();
},

Expand Down Expand Up @@ -110,15 +94,7 @@ export const security = (kibana) => new kibana.Plugin({
'plugins/security/hacks/on_unauthorized_response'
],
home: ['plugins/security/register_feature'],
injectDefaultVars: function (server) {
const config = server.config();

return {
secureCookies: config.get('xpack.security.secureCookies'),
sessionTimeout: config.get('xpack.security.sessionTimeout'),
enableSpaceAwarePrivileges: config.get('xpack.spaces.enabled'),
};
}
injectDefaultVars: () => defaultVars,
},

async postInit(server) {
Expand All @@ -136,21 +112,37 @@ export const security = (kibana) => new kibana.Plugin({
},

async init(server) {
const plugin = this;
const securityPlugin = this.kbnServer.newPlatform.setup.plugins.security;
if (!securityPlugin) {
throw new Error('New Platform XPack Security plugin is not available.');
}

const config = server.config();
const xpackMainPlugin = server.plugins.xpack_main;
const xpackInfo = xpackMainPlugin.info;
securityPlugin.registerLegacyAPI({
xpackInfo,
isSystemAPIRequest: server.plugins.kibana.systemApi.isSystemApiRequest.bind(
server.plugins.kibana.systemApi
),
});

const plugin = this;
const config = server.config();
const xpackInfoFeature = xpackInfo.feature(plugin.id);

// Config required for default injected vars is coming from new platform plugin and hence we can
// initialize these only within `init` function of the legacy plugin.
defaultVars = {
secureCookies: securityPlugin.config.secureCookies,
sessionTimeout: securityPlugin.config.sessionTimeout,
enableSpaceAwarePrivileges: config.get('xpack.spaces.enabled'),
};

// Register a function that is called whenever the xpack info changes,
// to re-compute the license check results for this plugin
xpackInfoFeature.registerLicenseCheckResultsGenerator(checkLicense);

validateConfig(config, message => server.log(['security', 'warning'], message));

await initAuthentication(this.kbnServer, server);
server.expose(initAuthentication(securityPlugin));

const { savedObjects } = server;

Expand Down Expand Up @@ -194,18 +186,16 @@ export const security = (kibana) => new kibana.Plugin({
return client;
});

getUserProvider(server);

initAuthenticateApi(server);
initAuthenticateApi(securityPlugin, server);
initAPIAuthorization(server, authorization);
initAppAuthorization(server, xpackMainPlugin, authorization);
initUsersApi(server);
initUsersApi(securityPlugin, server);
initExternalRolesApi(server);
initIndicesApi(server);
initPrivilegesApi(server);
initLoginView(server, xpackMainPlugin);
initLoginView(securityPlugin, server, xpackMainPlugin);
initLogoutView(server);
initLoggedOutView(server);
initLoggedOutView(securityPlugin, server);
initOverwrittenSessionView(server);

server.injectUiAppVars('login', () => {
Expand Down
Loading

0 comments on commit e901c8f

Please sign in to comment.