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

[New platform] Restrict import internals of plugins & core services in ts files #33562

Closed
Closed
Show file tree
Hide file tree
Changes from all 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
27 changes: 27 additions & 0 deletions NOTICE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,30 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

---
This product uses tslint-rules-bunch which is available under a
"MIT" license.

The MIT License (MIT)

Copyright (c) 2017-present, Vladimir Yakovlev
https://github.com/vladimiry/tslint-rules-bunch

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@
"license-checker": "^16.0.0",
"listr": "^0.14.1",
"load-grunt-config": "0.19.2",
"micromatch": "^3.1.10",
"mocha": "3.3.0",
"multistream": "^2.1.1",
"murmurhash3js": "3.0.1",
Expand Down Expand Up @@ -408,6 +409,7 @@
"tslint-config-prettier": "^1.15.0",
"tslint-microsoft-contrib": "^6.0.0",
"tslint-plugin-prettier": "^2.0.0",
"tsutils": "^3.9.1",
"typescript": "^3.3.3333",
"typings-tester": "^0.3.2",
"vinyl-fs": "^3.0.2",
Expand Down
2 changes: 1 addition & 1 deletion src/core/public/base_path/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@
* under the License.
*/

export { BasePathService, BasePathStart } from './base_path_service';
export * from './base_path_service';
2 changes: 1 addition & 1 deletion src/core/public/chrome/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@
* under the License.
*/

export { Breadcrumb, ChromeService, ChromeStart, Brand, HelpExtension } from './chrome_service';
export * from './chrome_service';
2 changes: 1 addition & 1 deletion src/core/public/fatal_errors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@
* under the License.
*/

export { FatalErrorsStart, FatalErrorsService } from './fatal_errors_service';
export * from './fatal_errors_service';
2 changes: 1 addition & 1 deletion src/core/public/http/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@
* under the License.
*/

export { HttpService, HttpStart } from './http_service';
export * from './http_service';
2 changes: 1 addition & 1 deletion src/core/public/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@
* under the License.
*/

export { I18nService, I18nStart } from './i18n_service';
export * from './i18n_service';
34 changes: 18 additions & 16 deletions src/core/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,26 @@
* under the License.
*/

import { BasePathStart } from './base_path';
import { ChromeStart } from './chrome';
import { FatalErrorsStart } from './fatal_errors';
import { HttpStart } from './http';
import { I18nStart } from './i18n';
import { InjectedMetadataStart } from './injected_metadata';
import { NotificationsStart } from './notifications';
import { UiSettingsClient } from './ui_settings';
import * as BasePath from './base_path';
import * as Chrome from './chrome';
import * as FatalErrors from './fatal_errors';
import * as Http from './http';
import * as I18n from './i18n';
import * as InjectedMetadata from './injected_metadata';
import * as Notifications from './notifications';
import * as UiSettings from './ui_settings';

export { CoreSystem } from './core_system';

export interface CoreStart {
i18n: I18nStart;
injectedMetadata: InjectedMetadataStart;
fatalErrors: FatalErrorsStart;
notifications: NotificationsStart;
http: HttpStart;
basePath: BasePathStart;
uiSettings: UiSettingsClient;
chrome: ChromeStart;
i18n: I18n.I18nStart;
injectedMetadata: InjectedMetadata.InjectedMetadataStart;
fatalErrors: FatalErrors.FatalErrorsStart;
notifications: Notifications.NotificationsStart;
http: Http.HttpStart;
basePath: BasePath.BasePathStart;
uiSettings: UiSettings.UiSettingsStart;
chrome: Chrome.ChromeStart;
}

export { BasePath, Chrome, FatalErrors, Http, I18n, InjectedMetadata, Notifications, UiSettings };
6 changes: 1 addition & 5 deletions src/core/public/injected_metadata/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,4 @@
* under the License.
*/

export {
InjectedMetadataService,
InjectedMetadataParams,
InjectedMetadataStart,
} from './injected_metadata_service';
export * from './injected_metadata_service';
Copy link
Contributor Author

@mshustov mshustov Mar 21, 2019

Choose a reason for hiding this comment

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

I made changes to improve "Go to definition" work. Otherwise, ts resolves this place as a definition. Potential problem: we don't see what file exports. Sometimes it can export some functionality only for testing, which is also bad imho (because it's not public interface).

4 changes: 2 additions & 2 deletions src/core/public/notifications/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@
* under the License.
*/

export { Toast, ToastInput, ToastsStart } from './toasts';
export { NotificationsService, NotificationsStart } from './notifications_service';
export * from './toasts';
export * from './notifications_service';
6 changes: 3 additions & 3 deletions src/core/public/ui_settings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@
* under the License.
*/

export { UiSettingsService, UiSettingsStart } from './ui_settings_service';
export { UiSettingsClient } from './ui_settings_client';
export { UiSettingsState } from './types';
export * from './ui_settings_service';
export * from './ui_settings_client';
export * from './types';
208 changes: 208 additions & 0 deletions src/dev/tslint/rules/noImportZonesRule.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

/* @notice
Copy link
Contributor Author

Choose a reason for hiding this comment

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

What should we do when use software licensed under MIT? Included a note as per https://github.com/elastic/kibana/blob/master/webpackShims/childnode-remove-polyfill.js

Copy link
Contributor

Choose a reason for hiding this comment

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

This is how we comply with The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software., but you should include /* eslint-disable @kbn/license-header/require-license-header */ too, since this isn't Apache 2.0 code.

Copy link
Contributor Author

@mshustov mshustov Mar 21, 2019

Choose a reason for hiding this comment

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

since this isn't Apache 2.0 code.

you mean only this file is not Apache 2.0 anymore because of MIT license? or it's not needed to be licensed under Apache 2.0 at all?

Copy link
Contributor

@spalger spalger Mar 21, 2019

Choose a reason for hiding this comment

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

you mean only this file is not Apache 2.0 anymore because of MIT license?

correct

* This product uses tslint-rules-bunch which is available under a
* "MIT" license.
*
* The MIT License (MIT)
*
* Copyright (c) 2017-present, Vladimir Yakovlev
* https://github.com/vladimiry/tslint-rules-bunch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

const path = require('path');
const Lint = require('tslint');
const mm = require('micromatch');
const { findImports, ImportKind } = require('tsutils');

function traverseToTopFolder(src, pattern) {
while(src && mm([src], pattern).length) {
Copy link
Contributor Author

@mshustov mshustov Mar 21, 2019

Choose a reason for hiding this comment

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

I think it's okay to have a local fork of the no-import-zones rule, we can port some logic to eslint as well (if we want ofc).
the only problem that I see right now - we don't have tests and it's not in written in ts anymore.

const srcIdx = src.lastIndexOf(path.delimiter);
src = src.slice(0, srcIdx);
}
return src;
}

function isSameFolderOrDescendent(src, imported, pattern) {
const srcFileFolderRoot = traverseToTopFolder(src, pattern);
const importedFileFolderRoot = traverseToTopFolder(imported, pattern);
return srcFileFolderRoot === importedFileFolderRoot;
}

const metadata = {
ruleName: 'no-import-zones',
description: `Forbids specific imports for the specified targets using 'micromatch' patterns matching`,
optionsDescription: Lint.Utils.dedent`
* 'basePath': by default 'process.cwd()' is used as the base path, but custom 'basePath'
property can be specified on the both zone/top and specific item levels. If values are specified on the
both levels, then specific item's value takes the priority.
* 'patterns' object specifies:
* 'target': file name pattern to which forbidding rule will be applied
* 'from': file import pattern that will be from for the specified 'target'
* 'verbose': verbose output
`,
options: {
type: 'object',
required: ['zones'],
additionalProperties: false,
properties: {
basePath: { type: ['string', 'null'] },
zones: {
type: 'array',
items: {
type: 'object',
required: ['patterns'],
additionalProperties: false,
properties: {
basePath: { type: ['string', 'null'] },
patterns: {
type: 'array',
items: {
type: 'object',
required: ['target', 'from'],
additionalProperties: false,
properties: {
target: {
anyOf: [
{ type: 'string' },
{ type: 'array', items: { type: 'string' } },
],
},
from: {
anyOf: [
{ type: 'string' },
{ type: 'array', items: { type: 'string' } },
],
},
},
},
},
},
},
},
},
},
optionExamples: [
true,
[
{
basePath: 'src',
zones: [
{
patterns: [
{
target: 'test/**/*',
from: 'lib/**/*',
},
],
},
],
},
],
],
type: 'functionality',
typescriptOnly: false,
};

class Rule extends Lint.Rules.AbstractRule {
isEnabled() {
return super.isEnabled() && this.ruleArguments.length > 0;
}

apply(sourceFile) {
return this.applyWithFunction(sourceFile, walk, this.ruleArguments);
}
}

Rule.metadata = metadata;

function walk(ctx) {
for (const importUnit of findImports(ctx.sourceFile, ImportKind.All)) {
for (const { basePath: topLevelBasePath, zones, verbose } of ctx.options) {
for (const { basePath: zoneBasePath, patterns } of zones) {
// eslint-disable-next-line no-nested-ternary
const basePath = zoneBasePath
? resolveBasePath(zoneBasePath)
: topLevelBasePath
? resolveBasePath(topLevelBasePath)
: path.resolve(process.cwd());

const srcFile = path.resolve(path.resolve(ctx.sourceFile.fileName));
const srcFileDir = path.parse(srcFile).dir;

const importFile = importUnit.text.startsWith('.')
? path.resolve(srcFileDir, importUnit.text)
: importUnit.text;

const relativeSrcFile = path.relative(basePath, srcFile);
const relativeImportFile = path.relative(basePath, importFile);
for (const { target, from } of patterns) {
if (
mm([relativeSrcFile], target).length &&
mm([relativeImportFile], from).length &&
!isSameFolderOrDescendent(relativeSrcFile, relativeImportFile, target)
) {
const zone = { basePath, target, from };
const messages = [
`(${Rule.metadata.ruleName}): '${importUnit.text}' import is forbidden`,
];

if (verbose) {
messages.push(...[
`; rule: ${JSON.stringify(zone)}; resolved values: ${JSON.stringify({
file: relativeSrcFile,
import: relativeImportFile,
})}`,
]);
}

ctx.addFailure(importUnit.getStart(ctx.sourceFile) + 1, importUnit.end - 1, messages.join(''));
}
}
}
}
}
}

function resolveBasePath(basePath) {
return path.isAbsolute(basePath)
? basePath
: path.relative(process.cwd(), basePath);
}

exports.Rule = Rule;
1 change: 1 addition & 0 deletions src/legacy/server/saved_objects/routes/_mock_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/

import Hapi from 'hapi';
// tslint:disable-next-line:no-import-zones
Copy link
Contributor Author

Choose a reason for hiding this comment

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

shouldn't we provide server factory / builder for testing purposes?
similar test https://github.com/elastic/kibana/blob/master/x-pack/plugins/security/server/routes/api/public/roles/put.test.js

import { defaultValidationErrorHandler } from '../../../../core/server/http/http_tools';

const defaultConfig = {
Expand Down
6 changes: 3 additions & 3 deletions src/legacy/ui/public/chrome/api/base_path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
* under the License.
*/

import { BasePathStart } from '../../../../../core/public/base_path';
let newPlatformBasePath: BasePathStart;
import { BasePath } from '../../../../../core/public/';
let newPlatformBasePath: BasePath.BasePathStart;

export function __newPlatformInit__(instance: BasePathStart) {
export function __newPlatformInit__(instance: BasePath.BasePathStart) {
if (newPlatformBasePath) {
throw new Error('ui/chrome/api/base_path is already initialized');
}
Expand Down
8 changes: 5 additions & 3 deletions src/legacy/ui/public/chrome/api/breadcrumbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@

import { IRootScopeService } from 'angular';
import { fatalError } from 'ui/notify/fatal_error';
import { Breadcrumb, ChromeStart } from '../../../../../core/public/chrome';
import { Chrome } from '../../../../../core/public';

type Breadcrumb = Chrome.Breadcrumb;
export { Breadcrumb };

export type BreadcrumbsApi = ReturnType<typeof createBreadcrumbsApi>['breadcrumbs'];

let newPlatformChrome: ChromeStart;
export function __newPlatformInit__(instance: ChromeStart) {
let newPlatformChrome: Chrome.ChromeStart;
export function __newPlatformInit__(instance: Chrome.ChromeStart) {
if (newPlatformChrome) {
throw new Error('ui/chrome/api/breadcrumbs is already initialized');
}
Expand Down
Loading