feat: eslint rule to check forbidden plugin imports

basically verify-local-dependencies.js but done during linting also in
the 3rd party repositories.

Signed-off-by: Hellgren Heikki <heikki.hellgren@op.fi>
This commit is contained in:
Hellgren Heikki
2025-06-13 01:46:04 +03:00
parent 2071dd40cf
commit 063b2d39ce
21 changed files with 429 additions and 89 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-scaffolder-backend-module-gitlab': patch
---
Fixed dependency to frontend package from tests
+12
View File
@@ -0,0 +1,12 @@
---
'@backstage/eslint-plugin': patch
---
Added new eslint rule to restrict mixed plugin imports.
New rule `@backstage/no-mixed-plugin-imports` disallows mixed imports between plugins that are mixing
the backstage architecture. This rule forces that:
- No imports from frontend plugins to backend plugins or other frontend plugins.
- No imports from backend plugins to frontend plugins or other backend plugins.
- No imports from common plugins to frontend or backend plugins.
+17 -1
View File
@@ -18,8 +18,24 @@ var path = require('path');
module.exports = {
root: true,
plugins: ['@spotify', 'notice', 'react', 'testing-library'],
plugins: ['@spotify', 'notice', 'react', 'testing-library', '@backstage'],
rules: {
'@backstage/no-mixed-plugin-imports': [
'error',
{
// TODO: Fix these either by right role or by moving things to new packages
excludedTargetPackages: [
'@backstage/test-utils',
'@backstage/config-loader',
'@backstage/plugin-catalog',
'@backstage/plugin-permission-backend',
'@backstage/plugin-app-backend',
'@backstage/plugin-techdocs',
'@backstage/plugin-app',
'@backstage/plugin-catalog-backend'
],
}
],
'react/react-in-jsx-scope': 'off',
'notice/notice': [
'error',
+1
View File
@@ -122,6 +122,7 @@
"@backstage/codemods": "workspace:*",
"@backstage/create-app": "workspace:*",
"@backstage/e2e-test-utils": "workspace:*",
"@backstage/eslint-plugin": "workspace:*",
"@backstage/repo-tools": "workspace:*",
"@changesets/cli": "^2.14.0",
"@octokit/rest": "^19.0.3",
+1
View File
@@ -3,6 +3,7 @@ module.exports = {
extends: ['plugin:storybook/recommended'],
rules: {
'react/forbid-elements': 'off',
'@backstage/no-mixed-plugin-imports': 'off'
},
};
+1
View File
@@ -41,3 +41,4 @@ The following rules are provided by this plugin:
| [@backstage/no-relative-monorepo-imports](./docs/rules/no-relative-monorepo-imports.md) | Forbid relative imports that reach outside of the package in a monorepo. |
| [@backstage/no-undeclared-imports](./docs/rules/no-undeclared-imports.md) | Forbid imports of external packages that have not been declared in the appropriate dependencies field in `package.json`. |
| [@backstage/no-top-level-material-ui-4-imports](./docs/rules/no-top-level-material-ui-4-imports.md) | Forbid top level import from Material UI v4 packages. |
| [@backstage/no-mixed-plugin-imports](./docs/rules/no-mixed-plugin-imports.md) | Disallow mixed plugin imports. |
@@ -0,0 +1,67 @@
# @backstage/no-mixed-plugin-imports
Disallow mixed imports between backstage plugins.
## Usage
Add the rules as follows, it has no options:
```js
"@backstage/no-mixed-plugin-imports": ["error"]
```
## Rule Details
Given the following two target packages:
```json
{
"name": "@backstage/plugin-foo",
"backstage": {
"role": "frontend-plugin"
}
}
```
```json
{
"name": "@backstage/plugin-bar",
"backstage": {
"role": "frontend-plugin"
}
}
```
### Fail
```ts
import { FooCard } from '@backstage/plugin-foo';
```
### Pass
```ts
import { FooCard } from '@backstage/plugin-foo-react';
```
## Options
You can ignore specific target packages or files by adding them to the options in the `.eslintrc.js` file:
```js
{
rules: {
'@backstage/no-mixed-plugin-imports': [
'error',
{
excludedTargetPackages: [
'@backstage/plugin-foo',
],
excludedFiles: [
'**/*.{test,spec}.[jt]s?(x)'
],
}
]
}
}
```
+2
View File
@@ -22,6 +22,7 @@ module.exports = {
'@backstage/no-forbidden-package-imports': 'error',
'@backstage/no-relative-monorepo-imports': 'error',
'@backstage/no-undeclared-imports': 'error',
'@backstage/no-mixed-plugin-imports': 'error',
},
},
},
@@ -30,5 +31,6 @@ module.exports = {
'no-relative-monorepo-imports': require('./rules/no-relative-monorepo-imports'),
'no-undeclared-imports': require('./rules/no-undeclared-imports'),
'no-top-level-material-ui-4-imports': require('./rules/no-top-level-material-ui-4-imports'),
'no-mixed-plugin-imports': require('./rules/no-mixed-plugin-imports'),
},
};
@@ -0,0 +1,149 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed 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.
*/
// @ts-check
const visitImports = require('../lib/visitImports');
const getPackages = require('../lib/getPackages');
const minimatch = require('minimatch');
const roleRules = [
{
sourceRole: ['frontend-plugin', 'web-library'],
targetRole: [
'backend-plugin',
'node-library',
'backend-plugin-module',
'frontend-plugin',
],
},
{
sourceRole: ['backend-plugin', 'node-library', 'backend-plugin-module'],
targetRole: ['frontend-plugin', 'web-library', 'backend-plugin'],
},
{
sourceRole: ['common-library'],
targetRole: [
'frontend-plugin',
'web-library',
'backend-plugin',
'node-library',
'backend-plugin-module',
],
},
];
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'problem',
messages: {
forbidden:
'{{sourcePackage}} ({{sourceRole}}) uses forbidden import from {{targetPackage}} ({{targetRole}}).',
},
docs: {
description: 'Disallow mixed plugin imports.',
url: 'https://github.com/backstage/backstage/blob/master/packages/eslint-plugin/docs/rules/no-mixed-plugin-imports.md',
},
schema: [
{
type: 'object',
properties: {
excludedTargetPackages: {
type: 'array',
items: { type: 'string' },
uniqueItems: true,
},
excludedFiles: {
type: 'array',
items: { type: 'string' },
uniqueItems: true,
},
},
additionalProperties: false,
},
],
},
create(context) {
const packages = getPackages(context.cwd);
if (!packages) {
return {};
}
const filePath = context.physicalFilename
? context.physicalFilename
: context.filename;
const pkg = packages.byPath(filePath);
if (!pkg) {
return {};
}
const options = context.options[0] || {};
const ignoreTargetPackages = options.excludedTargetPackages || [];
const ignorePatterns = options.excludedFiles || [
'**/*.{test,spec}.[jt]s?(x)',
'**/dev/index.[jt]s?(x)',
];
if (
ignorePatterns.some(pattern =>
new minimatch.Minimatch(pattern).match(context.filename),
)
) {
return {};
}
return visitImports(context, (node, imp) => {
if (imp.type !== 'internal') {
return;
}
const targetPackage = imp.package;
const targetName = targetPackage.packageJson.name;
const sourceName = pkg.packageJson.name;
if (sourceName === targetName) {
return;
}
const sourceRole = pkg.packageJson.backstage?.role;
const targetRole = targetPackage.packageJson.backstage?.role;
if (!sourceRole || !targetRole) {
return;
}
if (
roleRules.some(
rule =>
rule.sourceRole.includes(sourceRole) &&
rule.targetRole.includes(targetRole) &&
!ignoreTargetPackages.includes(targetName),
)
) {
context.report({
node: node,
messageId: 'forbidden',
data: {
sourcePackage: pkg.packageJson.name || imp.package.dir,
sourceRole,
targetPackage: targetPackage.packageJson.name || imp.package.dir,
targetRole,
},
});
}
});
},
};
@@ -1,5 +1,12 @@
{
"name": "@internal/foo",
"backstage": {
"role": "frontend-plugin"
},
"files": [
"dist",
"type-utils"
],
"dependencies": {
"@internal/bar": "1.0.0"
},
@@ -8,9 +15,5 @@
},
"peerDependencies": {
"react": "*"
},
"files": [
"dist",
"type-utils"
]
}
}
@@ -0,0 +1,68 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed 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.
*/
import { RuleTester } from 'eslint';
import path from 'path';
import rule from '../rules/no-mixed-plugin-imports';
const RULE = 'no-mixed-plugin-imports';
const FIXTURE = path.resolve(__dirname, '__fixtures__/monorepo');
const ERR = (
sourcePackage: string,
sourceRole: string,
targetPackage: string,
targetRole: string,
) => ({
message: `${sourcePackage} (${sourceRole}) uses forbidden import from ${targetPackage} (${targetRole}).`,
});
// cwd must be restored
const origDir = process.cwd();
afterAll(() => {
process.chdir(origDir);
});
process.chdir(FIXTURE);
const ruleTester = new RuleTester({
parserOptions: {
sourceType: 'module',
ecmaVersion: 2021,
},
});
ruleTester.run(RULE, rule, {
valid: [
{
code: `import '@internal/inline'`,
filename: path.join(FIXTURE, 'packages/bar/src/index.ts'),
},
],
invalid: [
{
code: `import '@internal/foo'`,
filename: path.join(FIXTURE, 'packages/bar/src/index.ts'),
errors: [
ERR(
'@internal/bar',
'frontend-plugin',
'@internal/foo',
'frontend-plugin',
),
],
},
],
});
@@ -59,7 +59,6 @@
"devDependencies": {
"@backstage/backend-test-utils": "workspace:^",
"@backstage/cli": "workspace:^",
"@backstage/core-app-api": "workspace:^",
"@backstage/plugin-scaffolder-node-test-utils": "workspace:^"
}
}
@@ -14,12 +14,12 @@
* limitations under the License.
*/
import { ConfigReader } from '@backstage/core-app-api';
import { ScmIntegrations } from '@backstage/integration';
import { createMockActionContext } from '@backstage/plugin-scaffolder-node-test-utils';
import yaml from 'yaml';
import { createGitlabGroupEnsureExistsAction } from './gitlabGroupEnsureExists';
import { examples } from './gitlabGroupEnsureExists.examples';
import { mockServices } from '@backstage/backend-test-utils';
const mockGitlabClient = {
Groups: {
@@ -50,15 +50,17 @@ describe('gitlab:group:ensureExists', () => {
full_path: 'group1',
});
const config = new ConfigReader({
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'tokenlols',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
const config = mockServices.rootConfig({
data: {
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'tokenlols',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
},
},
});
const integrations = ScmIntegrations.fromConfig(config);
@@ -14,11 +14,11 @@
* limitations under the License.
*/
import { ConfigReader } from '@backstage/core-app-api';
import { ScmIntegrations } from '@backstage/integration';
import { createMockActionContext } from '@backstage/plugin-scaffolder-node-test-utils';
import { createGitlabGroupEnsureExistsAction } from './gitlabGroupEnsureExists';
import { getClient } from '../util';
import { mockServices } from '@backstage/backend-test-utils';
const mockGitlabClient = {
Groups: {
@@ -45,15 +45,17 @@ describe('gitlab:group:ensureExists', () => {
jest.clearAllMocks();
});
const config = new ConfigReader({
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'tokenlols',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
const config = mockServices.rootConfig({
data: {
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'tokenlols',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
},
},
});
const integrations = ScmIntegrations.fromConfig(config);
@@ -14,12 +14,12 @@
* limitations under the License.
*/
import { ConfigReader } from '@backstage/core-app-api';
import { ScmIntegrations } from '@backstage/integration';
import { createMockActionContext } from '@backstage/plugin-scaffolder-node-test-utils';
import { createGitlabIssueAction } from './gitlabIssueCreate';
import { examples } from './gitlabIssueCreate.examples';
import yaml from 'yaml';
import { mockServices } from '@backstage/backend-test-utils';
const mockGitlabClient = {
Issues: {
@@ -46,15 +46,17 @@ describe('gitlab:issues:create', () => {
jest.useRealTimers();
});
const config = new ConfigReader({
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'sample-token',
apiBaseUrl: 'https://gitlab.com/api/v1',
},
],
const config = mockServices.rootConfig({
data: {
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'sample-token',
apiBaseUrl: 'https://gitlab.com/api/v1',
},
],
},
},
});
const integrations = ScmIntegrations.fromConfig(config);
@@ -14,11 +14,11 @@
* limitations under the License.
*/
import { ConfigReader } from '@backstage/core-app-api';
import { ScmIntegrations } from '@backstage/integration';
import { createMockActionContext } from '@backstage/plugin-scaffolder-node-test-utils';
import { IssueType } from '../commonGitlabConfig';
import { createGitlabIssueAction } from './gitlabIssueCreate';
import { mockServices } from '@backstage/backend-test-utils';
const mockGitlabClient = {
Issues: {
@@ -45,15 +45,17 @@ describe('gitlab:issues:create', () => {
jest.useRealTimers();
});
const config = new ConfigReader({
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'myIntegrationsToken',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
const config = mockServices.rootConfig({
data: {
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'myIntegrationsToken',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
},
},
});
const integrations = ScmIntegrations.fromConfig(config);
@@ -15,11 +15,11 @@
*/
import { createMockActionContext } from '@backstage/plugin-scaffolder-node-test-utils';
import { ConfigReader } from '@backstage/core-app-api';
import { ScmIntegrations } from '@backstage/integration';
import { editGitlabIssueAction } from './gitlabIssueEdit';
import { examples } from './gitlabIssueEdit.examples';
import yaml from 'yaml';
import { mockServices } from '@backstage/backend-test-utils';
const mockGitlabClient = {
Issues: {
@@ -46,15 +46,17 @@ describe('gitlab:issue:edit', () => {
jest.useRealTimers();
});
const config = new ConfigReader({
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'myIntegrationsToken',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
const config = mockServices.rootConfig({
data: {
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'myIntegrationsToken',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
},
},
});
const integrations = ScmIntegrations.fromConfig(config);
@@ -15,10 +15,10 @@
*/
import { createMockActionContext } from '@backstage/plugin-scaffolder-node-test-utils';
import { ConfigReader } from '@backstage/core-app-api';
import { ScmIntegrations } from '@backstage/integration';
import { IssueType } from '../commonGitlabConfig';
import { editGitlabIssueAction } from './gitlabIssueEdit';
import { mockServices } from '@backstage/backend-test-utils';
const mockGitlabClient = {
Issues: {
@@ -45,15 +45,17 @@ describe('gitlab:issue:edit', () => {
jest.useRealTimers();
});
const config = new ConfigReader({
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'myIntegrationsToken',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
const config = mockServices.rootConfig({
data: {
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'myIntegrationsToken',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
},
},
});
const integrations = ScmIntegrations.fromConfig(config);
@@ -14,12 +14,12 @@
* limitations under the License.
*/
import { ConfigReader } from '@backstage/core-app-api';
import { ScmIntegrations } from '@backstage/integration';
import { createMockActionContext } from '@backstage/plugin-scaffolder-node-test-utils';
import { createTriggerGitlabPipelineAction } from './gitlabPipelineTrigger';
import { examples } from './gitlabPipelineTrigger.examples';
import yaml from 'yaml';
import { mockServices } from '@backstage/backend-test-utils';
const mockGitlabClient = {
PipelineTriggerTokens: {
@@ -49,15 +49,17 @@ describe('gitlab:pipeline:trigger', () => {
jest.useRealTimers();
});
const config = new ConfigReader({
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'glpat-abcdef',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
const config = mockServices.rootConfig({
data: {
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'glpat-abcdef',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
},
},
});
const integrations = ScmIntegrations.fromConfig(config);
@@ -14,10 +14,10 @@
* limitations under the License.
*/
import { ConfigReader } from '@backstage/core-app-api';
import { ScmIntegrations } from '@backstage/integration';
import { createMockActionContext } from '@backstage/plugin-scaffolder-node-test-utils';
import { createTriggerGitlabPipelineAction } from './gitlabPipelineTrigger';
import { mockServices } from '@backstage/backend-test-utils';
const mockGitlabClient = {
PipelineTriggerTokens: {
@@ -47,15 +47,17 @@ describe('gitlab:pipeline:trigger', () => {
jest.useRealTimers();
});
const config = new ConfigReader({
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'glpat-abcdef',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
const config = mockServices.rootConfig({
data: {
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'glpat-abcdef',
apiBaseUrl: 'https://gitlab.com/api/v4',
},
],
},
},
});
const integrations = ScmIntegrations.fromConfig(config);
+2 -2
View File
@@ -4598,7 +4598,7 @@ __metadata:
languageName: unknown
linkType: soft
"@backstage/eslint-plugin@workspace:^, @backstage/eslint-plugin@workspace:packages/eslint-plugin":
"@backstage/eslint-plugin@workspace:*, @backstage/eslint-plugin@workspace:^, @backstage/eslint-plugin@workspace:packages/eslint-plugin":
version: 0.0.0-use.local
resolution: "@backstage/eslint-plugin@workspace:packages/eslint-plugin"
dependencies:
@@ -7702,7 +7702,6 @@ __metadata:
"@backstage/backend-test-utils": "workspace:^"
"@backstage/cli": "workspace:^"
"@backstage/config": "workspace:^"
"@backstage/core-app-api": "workspace:^"
"@backstage/errors": "workspace:^"
"@backstage/integration": "workspace:^"
"@backstage/plugin-scaffolder-node": "workspace:^"
@@ -45419,6 +45418,7 @@ __metadata:
"@backstage/create-app": "workspace:*"
"@backstage/e2e-test-utils": "workspace:*"
"@backstage/errors": "workspace:^"
"@backstage/eslint-plugin": "workspace:*"
"@backstage/repo-tools": "workspace:*"
"@changesets/cli": "npm:^2.14.0"
"@manypkg/get-packages": "npm:^1.1.3"