Skip to content

Commit

Permalink
Changes....
Browse files Browse the repository at this point in the history
  • Loading branch information
azasypkin committed Oct 28, 2019
1 parent e6a41d4 commit 22ba245
Show file tree
Hide file tree
Showing 164 changed files with 7,626 additions and 7,707 deletions.
10 changes: 6 additions & 4 deletions packages/kbn-config-schema/src/errors/validation_error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,19 @@
import { SchemaError, SchemaTypeError, SchemaTypesError } from '.';

export class ValidationError extends SchemaError {
public static extractMessage(error: SchemaTypeError, namespace?: string) {
private static extractMessage(error: SchemaTypeError, namespace?: string, level?: number) {
const path = typeof namespace === 'string' ? [namespace, ...error.path] : error.path;

let message = error.message;
if (error instanceof SchemaTypesError) {
const indentLevel = level || 0;
const childErrorMessages = error.errors.map(childError =>
ValidationError.extractMessage(childError, namespace)
ValidationError.extractMessage(childError, namespace, indentLevel + 1)
);

message = `${message}\n${childErrorMessages
.map(childErrorMessage => `- ${childErrorMessage}`)
const indent = ' '.repeat(indentLevel);
message = `${indent}${message}\n${childErrorMessages
.map(childErrorMessage => `${indent}- ${childErrorMessage}`)
.join('\n')}`;
}

Expand Down
20 changes: 20 additions & 0 deletions packages/kbn-config-schema/src/types/map_of_type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,23 @@ test('object within mapOf', () => {

expect(type.validate(value)).toEqual(expected);
});

test('error preserves full path', () => {
const type = schema.object({
grandParentKey: schema.object({
parentKey: schema.mapOf(schema.string({ minLength: 2 }), schema.number()),
}),
});

expect(() =>
type.validate({ grandParentKey: { parentKey: { a: 'some-value' } } })
).toThrowErrorMatchingInlineSnapshot(
`"[grandParentKey.parentKey.key(\\"a\\")]: value is [a] but it must have a minimum length of [2]."`
);

expect(() =>
type.validate({ grandParentKey: { parentKey: { ab: 'some-value' } } })
).toThrowErrorMatchingInlineSnapshot(
`"[grandParentKey.parentKey.ab]: expected value of type [number] but got [string]"`
);
});
2 changes: 1 addition & 1 deletion packages/kbn-config-schema/src/types/map_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export class MapOfType<K, V> extends Type<Map<K, V>> {
return `expected value of type [Map] or [object] but got [${typeDetect(value)}]`;
case 'map.key':
case 'map.value':
const childPathWithIndex = reason.path.slice();
const childPathWithIndex = path.slice();
childPathWithIndex.splice(
path.length,
0,
Expand Down
16 changes: 16 additions & 0 deletions packages/kbn-config-schema/src/types/one_of_type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,19 @@ test('fails if not matching literal', () => {

expect(() => type.validate('bar')).toThrowErrorMatchingSnapshot();
});

test('fails if nested union type fail', () => {
const type = schema.oneOf([
schema.oneOf([schema.boolean()]),
schema.oneOf([schema.oneOf([schema.object({})])]),
]);

expect(() => type.validate('aaa')).toThrowErrorMatchingInlineSnapshot(`
"types that failed validation:
- [0]: types that failed validation:
- [0]: expected value of type [boolean] but got [string]
- [1]: types that failed validation:
- [0]: types that failed validation:
- [0]: expected a plain object value, but found [string] instead."
`);
});
20 changes: 20 additions & 0 deletions packages/kbn-config-schema/src/types/record_of_type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,23 @@ test('object within recordOf', () => {

expect(type.validate(value)).toEqual({ foo: { bar: 123 } });
});

test('error preserves full path', () => {
const type = schema.object({
grandParentKey: schema.object({
parentKey: schema.recordOf(schema.string({ minLength: 2 }), schema.number()),
}),
});

expect(() =>
type.validate({ grandParentKey: { parentKey: { a: 'some-value' } } })
).toThrowErrorMatchingInlineSnapshot(
`"[grandParentKey.parentKey.key(\\"a\\")]: value is [a] but it must have a minimum length of [2]."`
);

expect(() =>
type.validate({ grandParentKey: { parentKey: { ab: 'some-value' } } })
).toThrowErrorMatchingInlineSnapshot(
`"[grandParentKey.parentKey.ab]: expected value of type [number] but got [string]"`
);
});
2 changes: 1 addition & 1 deletion packages/kbn-config-schema/src/types/record_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class RecordOfType<K extends string, V> extends Type<Record<K, V>> {
return `expected value of type [object] but got [${typeDetect(value)}]`;
case 'record.key':
case 'record.value':
const childPathWithIndex = reason.path.slice();
const childPathWithIndex = path.slice();
childPathWithIndex.splice(
path.length,
0,
Expand Down
4 changes: 3 additions & 1 deletion packages/kbn-config-schema/src/types/union_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ export class UnionType<RTS extends Array<Type<any>>, T> extends Type<T> {
const childPathWithIndex = e.path.slice();
childPathWithIndex.splice(path.length, 0, index.toString());

return new SchemaTypeError(e.message, childPathWithIndex);
return e instanceof SchemaTypesError
? new SchemaTypesError(e.message, childPathWithIndex, e.errors)
: new SchemaTypeError(e.message, childPathWithIndex);
})
);
}
Expand Down
4 changes: 3 additions & 1 deletion src/core/server/http/http_server.mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ interface RequestFixtureOptions {
path?: string;
method?: RouteMethod;
socket?: Socket;
routeTags?: string[];
}

function createKibanaRequestMock({
Expand All @@ -49,6 +50,7 @@ function createKibanaRequestMock({
query = {},
method = 'get',
socket = new Socket(),
routeTags,
}: RequestFixtureOptions = {}) {
const queryString = querystring.stringify(query);
return KibanaRequest.from(
Expand All @@ -64,7 +66,7 @@ function createKibanaRequestMock({
query: queryString,
search: queryString ? `?${queryString}` : queryString,
},
route: { settings: {} },
route: { settings: { tags: routeTags } },
raw: {
req: { socket },
},
Expand Down
1 change: 1 addition & 0 deletions src/core/server/saved_objects/service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export interface SavedObjectsLegacyService<Request = any> {
addScopedSavedObjectsClientWrapperFactory: SavedObjectsClientProvider<
Request
>['addClientWrapperFactory'];
setScopedSavedObjectsClientFactory: SavedObjectsClientProvider<Request>['setClientFactory'];
getScopedSavedObjectsClient: SavedObjectsClientProvider<Request>['getClient'];
SavedObjectsClient: typeof SavedObjectsClient;
types: string[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export class SavedObjectsClientProvider<Request = unknown> {
this._wrapperFactories.add(priority, { id, factory });
}

setClientFactory(customClientFactory: SavedObjectsClientFactory) {
setClientFactory(customClientFactory: SavedObjectsClientFactory<Request>) {
if (this._clientFactory !== this._originalClientFactory) {
throw new Error(`custom client factory is already set, unable to replace the current one`);
}
Expand Down
2 changes: 1 addition & 1 deletion x-pack/legacy/plugins/actions/server/shim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export interface Server extends Legacy.Server {
*/
export type TaskManagerStartContract = Pick<TaskManager, 'schedule' | 'fetch' | 'remove'>;
export type XPackMainPluginSetupContract = Pick<XPackMainPlugin, 'registerFeature'>;
export type SecurityPluginSetupContract = Pick<SecurityPlugin, 'config' | 'registerLegacyAPI'>;
export type SecurityPluginSetupContract = Pick<SecurityPlugin, '__legacyCompat'>;
export type SecurityPluginStartContract = Pick<SecurityPlugin, 'authc'>;
export type EncryptedSavedObjectsSetupContract = Pick<EncryptedSavedObjectsPlugin, 'registerType'>;
export type TaskManagerSetupContract = Pick<
Expand Down
2 changes: 1 addition & 1 deletion x-pack/legacy/plugins/alerting/server/shim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export interface Server extends Legacy.Server {
* Shim what we're thinking setup and start contracts will look like
*/
export type TaskManagerStartContract = Pick<TaskManager, 'schedule' | 'fetch' | 'remove'>;
export type SecurityPluginSetupContract = Pick<SecurityPlugin, 'config' | 'registerLegacyAPI'>;
export type SecurityPluginSetupContract = Pick<SecurityPlugin, '__legacyCompat'>;
export type SecurityPluginStartContract = Pick<SecurityPlugin, 'authc'>;
export type EncryptedSavedObjectsSetupContract = Pick<EncryptedSavedObjectsPlugin, 'registerType'>;
export type XPackMainPluginSetupContract = Pick<XPackMainPlugin, 'registerFeature'>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ export const getCustomLogo = async ({
// We use the basePath from the saved job, which we'll have post spaces being implemented;
// or we use the server base path, which uses the default space
getBasePath: () => job.basePath || serverBasePath,
path: '/',
route: { settings: {} },
url: {
href: '/',
},
raw: {
req: {
url: '/',
},
},
};

const savedObjects = server.savedObjects;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ function executeJobFn(server) {
// We use the basePath from the saved job, which we'll have post spaces being implemented;
// or we use the server base path, which uses the default space
getBasePath: () => basePath || serverBasePath,
path: '/',
route: { settings: {} },
url: {
href: '/',
},
raw: {
req: {
url: '/',
},
},
};

const callEndpoint = (endpoint, clientParams = {}, options = {}) => {
Expand Down
17 changes: 1 addition & 16 deletions x-pack/legacy/plugins/reporting/server/lib/get_user.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,9 @@
*/

import { oncePerServer } from './once_per_server';
import { getClient as getShieldClient } from '../../../../server/lib/get_client_shield';

function getUserFn(server) {
const callShieldWithRequest = getShieldClient(server).callWithRequest;

return async function getUser(request) {
const xpackInfo = server.plugins.xpack_main.info;
if (xpackInfo && xpackInfo.isAvailable() && xpackInfo.feature('security').isEnabled()) {
try {
return await callShieldWithRequest(request, 'shield.authenticate');
} catch (err) {
server.log(['reporting', 'getUser', 'debug'], err);
return null;
}
}

return null;
};
return (request) => server.plugins.security.getUser(request);
}

export const getUserFactory = oncePerServer(getUserFn);
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('authorized_user_pre_routing', function () {
// so createMockServer reuses the same 'instance' of the server and overwrites
// the properties to contain different values
const createMockServer = (function () {
const callWithRequestStub = sinon.stub();
const getUserStub = sinon.stub();
let mockConfig;

const mockServer = {
Expand All @@ -30,13 +30,7 @@ describe('authorized_user_pre_routing', function () {
log: function () {},
plugins: {
xpack_main: {},
elasticsearch: {
createCluster: function () {
return {
callWithRequest: callWithRequestStub
};
}
}
security: { getUser: getUserStub },
}
};

Expand All @@ -57,8 +51,8 @@ describe('authorized_user_pre_routing', function () {
}
};

callWithRequestStub.resetHistory();
callWithRequestStub.returns(Promise.resolve(user));
getUserStub.resetHistory();
getUserStub.resolves(user);
return mockServer;
};
}());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ function authorizedUserPreRoutingFn(server) {
}

const user = await getUser(request);

if (!user) {
return boom.unauthorized(`Sorry, you aren't authenticated`);
}
Expand Down
4 changes: 0 additions & 4 deletions x-pack/legacy/plugins/security/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,4 @@
* you may not use this file except in compliance with the Elastic License.
*/

export const GLOBAL_RESOURCE = '*';
export const IGNORED_TYPES = ['space'];
export const APPLICATION_PREFIX = 'kibana-';
export const RESERVED_PRIVILEGES_APPLICATION_WILDCARD = 'kibana-*';
export const INTERNAL_API_BASE_PATH = '/internal/security';
1 change: 0 additions & 1 deletion x-pack/legacy/plugins/security/common/login_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,4 @@ export type LoginLayout = 'form' | 'error-es-unavailable' | 'error-xpack-unavail
export interface LoginState {
layout: LoginLayout;
allowLogin: boolean;
loginMessage: string;
}
17 changes: 11 additions & 6 deletions x-pack/legacy/plugins/security/common/model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@
* you may not use this file except in compliance with the Elastic License.
*/

export { Role, RoleIndexPrivilege, RoleKibanaPrivilege } from './role';
export { FeaturesPrivileges } from './features_privileges';
export { RawKibanaPrivileges, RawKibanaFeaturePrivileges } from './raw_kibana_privileges';
export { KibanaPrivileges } from './kibana_privileges';
export { ApiKey } from './api_key';
export { User, EditUser, getUserDisplayName } from '../../../../../plugins/security/common/model';
export {
AuthenticatedUser,
BuiltinESPrivileges,
EditUser,
FeaturesPrivileges,
KibanaPrivileges,
RawKibanaFeaturePrivileges,
RawKibanaPrivileges,
Role,
RoleIndexPrivilege,
RoleKibanaPrivilege,
User,
canUserChangePassword,
getUserDisplayName,
} from '../../../../../plugins/security/common/model';
export { BuiltinESPrivileges } from './builtin_es_privileges';
2 changes: 0 additions & 2 deletions x-pack/legacy/plugins/security/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@

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

/**
* Public interface of the security plugin.
*/
export interface SecurityPlugin {
authorization: Readonly<AuthorizationService>;
getUser: (request: Legacy.Request) => Promise<AuthenticatedUser>;
}
Loading

0 comments on commit 22ba245

Please sign in to comment.