-
Notifications
You must be signed in to change notification settings - Fork 951
feat(workspace): scope-trust list for aspect loading #10347
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
Merged
Merged
Changes from 8 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
f6753e7
feat(workspace): add scope-trust list for aspect loading
davidfirst 829b915
Merge branch 'master' into workspace/scope-trust
davidfirst 7777595
refactor(workspace): scope-trust is opt-in + single command with action
davidfirst 801a959
chore(scope-trust): address review feedback
davidfirst dbb89e2
chore(scope-trust): address review feedback (round 2)
davidfirst 0e0831a
Merge branch 'master' into workspace/scope-trust
davidfirst 354bcad
refactor(scope-trust): tighten implementation per review
davidfirst 89db658
chore(scope-trust): docs-friendly action description and placeholders
davidfirst a1d9644
chore(scope-trust): expand builtin trust list
davidfirst 0825b8f
test(perf): bump MAX_FILES_READ from 1057 to 1062
davidfirst 84abb5a
Merge branch 'master' into workspace/scope-trust
davidfirst 8cfea6e
chore(scope-trust): hoist requirePattern result for type-safe formatting
davidfirst 9e377b3
chore(scope-trust): reject nested-wildcard patterns
davidfirst File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,203 @@ | ||
| /** | ||
| * Verifies the workspace's scope-trust gate around aspect loading. | ||
| * | ||
| * The gate is opt-in: it only runs when `trustedScopes` is present in | ||
| * workspace.jsonc. The deny test below opts in explicitly; the allow test | ||
| * lists the env's scope. | ||
| * | ||
| * Setup: an env in scope A has a top-level statement that writes a marker | ||
| * file when an env-var is set. A consumer component uses that env. A second | ||
| * workspace whose `defaultScope` belongs to a different owner imports the | ||
| * consumer. | ||
| */ | ||
| import { expect } from 'chai'; | ||
| import os from 'os'; | ||
| import path from 'path'; | ||
| import fs from 'fs-extra'; | ||
| import { Helper, NpmCiRegistry, supportNpmCiRegistryTesting } from '@teambit/legacy.e2e-helper'; | ||
|
|
||
| const MARKER_ENV_VAR = 'BIT_SCOPE_TRUST_TEST_MARKER'; | ||
|
|
||
| const ENV_WITH_MARKER_SOURCE = ` | ||
| import * as fs from 'fs'; | ||
| const marker = process.env.${MARKER_ENV_VAR}; | ||
| if (marker) { | ||
| try { fs.writeFileSync(marker, 'env-module-loaded'); } catch (e) { /* best effort */ } | ||
| } | ||
| export class EmptyEnv {} | ||
| export default new EmptyEnv(); | ||
| `; | ||
|
|
||
| (supportNpmCiRegistryTesting ? describe : describe.skip)( | ||
| 'workspace scope-trust gate around aspect loading', | ||
| function () { | ||
| this.timeout(0); | ||
| let helper: Helper; | ||
| let npmCiRegistry: NpmCiRegistry; | ||
| let markerPath: string; | ||
| let originalMarkerEnv: string | undefined; | ||
| let importErrorOutput: string; | ||
|
|
||
| before(async () => { | ||
| // Stable absolute marker path; passed to spawned bit processes via the | ||
| // current process's env so the env module's top-level can write it. | ||
| markerPath = path.join( | ||
| os.tmpdir(), | ||
| `bit-scope-trust-marker-${Date.now()}-${Math.random().toString(36).slice(2)}.txt` | ||
| ); | ||
| fs.removeSync(markerPath); | ||
| originalMarkerEnv = process.env[MARKER_ENV_VAR]; | ||
| process.env[MARKER_ENV_VAR] = markerPath; | ||
|
|
||
| helper = new Helper({ scopesOptions: { remoteScopeWithDot: true } }); | ||
| helper.scopeHelper.setWorkspaceWithRemoteScope(); | ||
|
|
||
| // Env whose module body writes the marker file when MARKER_ENV_VAR is set. | ||
| helper.env.setEmptyEnv(); | ||
| helper.fs.outputFile('empty-env/empty-env.bit-env.ts', ENV_WITH_MARKER_SOURCE); | ||
|
|
||
| helper.fixtures.populateComponents(1, false); | ||
| helper.command.setEnv('comp1', 'empty-env'); | ||
|
|
||
| npmCiRegistry = new NpmCiRegistry(helper); | ||
| await npmCiRegistry.init(); | ||
| npmCiRegistry.configureCiInPackageJsonHarmony(); | ||
| helper.command.install(); | ||
| helper.command.compile(); | ||
| helper.command.tagAllComponents(); | ||
| helper.command.export(); | ||
|
|
||
| // Second workspace, opted in to scope-trust with an empty list. The | ||
| // defaultScope is under a different owner so the owner-wildcard doesn't | ||
| // auto-trust the publisher's scope; the empty list means only builtins | ||
| // are trusted, so the publisher's scope is rejected. | ||
| helper.scopeHelper.reInitWorkspace({ addRemoteScopeAsDefaultScope: false }); | ||
| helper.workspaceJsonc.addKeyValToWorkspace('defaultScope', 'other-owner.app'); | ||
| helper.workspaceJsonc.addKeyValToWorkspace('trustedScopes', []); | ||
| npmCiRegistry.setResolver(); | ||
|
|
||
| // Clear the marker before the import so any later write is attributable | ||
| // to the consumer-side aspect load (publisher-side install/compile runs | ||
| // its own env code naturally — its scope is trusted in its own workspace). | ||
| fs.removeSync(markerPath); | ||
| expect(fs.existsSync(markerPath), 'marker should be absent before import').to.be.false; | ||
|
|
||
| // The aspect-load gate refuses; the import surfaces the refusal | ||
| // message. Capture both stdout and any thrown error so we can assert | ||
| // on the message (avoids a false positive if the import had failed for | ||
| // an unrelated reason like a network/registry hiccup). | ||
| try { | ||
| importErrorOutput = helper.command.importComponent('comp1'); | ||
| } catch (err: any) { | ||
| importErrorOutput = `${err?.stdout || ''}\n${err?.stderr || ''}\n${err?.message || ''}`; | ||
| } | ||
| }); | ||
|
|
||
| after(() => { | ||
| try { | ||
| fs.removeSync(markerPath); | ||
| } catch {} | ||
| if (originalMarkerEnv === undefined) delete process.env[MARKER_ENV_VAR]; | ||
| else process.env[MARKER_ENV_VAR] = originalMarkerEnv; | ||
| npmCiRegistry?.destroy(); | ||
| helper?.scopeHelper.destroy(); | ||
| }); | ||
|
|
||
| it('does not load the env from a scope outside the trust list', () => { | ||
| expect(fs.existsSync(markerPath), `env module loaded; marker at ${markerPath}`).to.be.false; | ||
| }); | ||
|
|
||
| it("surfaces a refusal message naming the scope that isn't on the trust list", () => { | ||
| expect(importErrorOutput).to.match(/isn't on the workspace's trusted list/i); | ||
| }); | ||
| } | ||
| ); | ||
|
|
||
| (supportNpmCiRegistryTesting ? describe : describe.skip)( | ||
| 'workspace scope-trust gate: trusted env in a different scope than the consumer', | ||
| function () { | ||
| this.timeout(0); | ||
| let helper: Helper; | ||
| let npmCiRegistry: NpmCiRegistry; | ||
| let markerPath: string; | ||
| let originalMarkerEnv: string | undefined; | ||
| let envScopeName: string; | ||
| let importOutput: string; | ||
|
|
||
| before(async () => { | ||
| markerPath = path.join( | ||
| os.tmpdir(), | ||
| `bit-scope-trust-marker-${Date.now()}-${Math.random().toString(36).slice(2)}.txt` | ||
| ); | ||
| fs.removeSync(markerPath); | ||
| originalMarkerEnv = process.env[MARKER_ENV_VAR]; | ||
| process.env[MARKER_ENV_VAR] = markerPath; | ||
|
|
||
| helper = new Helper({ scopesOptions: { remoteScopeWithDot: true } }); | ||
| helper.scopeHelper.setWorkspaceWithRemoteScope(); | ||
| // The publisher's default remote will hold the env. envScopeName is the | ||
| // exact scope name the victim will trust explicitly via `bit scope trust`. | ||
| envScopeName = helper.scopes.remote; | ||
|
|
||
| // A second remote holds the consumer component. The victim does NOT | ||
| // trust this scope. The import should still succeed because only the | ||
| // env's scope is checked at aspect-load. | ||
| const compRemote = helper.scopeHelper.getNewBareScope('-comp-remote'); | ||
| // Register compRemote in the publisher workspace and cross-link the two | ||
| // remotes so each can resolve dependencies from the other. | ||
| helper.scopeHelper.addRemoteScope(compRemote.scopePath); | ||
| helper.scopeHelper.addRemoteScope(compRemote.scopePath, helper.scopes.remotePath); | ||
| helper.scopeHelper.addRemoteScope(helper.scopes.remotePath, compRemote.scopePath); | ||
|
|
||
| helper.env.setEmptyEnv(); | ||
| helper.fs.outputFile('empty-env/empty-env.bit-env.ts', ENV_WITH_MARKER_SOURCE); | ||
|
|
||
| helper.fixtures.populateComponents(1, false); | ||
| helper.command.setEnv('comp1', 'empty-env'); | ||
| // Retarget the consumer (comp1) to the second remote scope so its scope | ||
| // differs from the env's scope. | ||
| helper.command.setScope(compRemote.scopeName, 'comp1'); | ||
|
|
||
| npmCiRegistry = new NpmCiRegistry(helper); | ||
| await npmCiRegistry.init(); | ||
| npmCiRegistry.configureCiInPackageJsonHarmony(); | ||
| helper.command.install(); | ||
| helper.command.compile(); | ||
| helper.command.tagAllComponents(); | ||
| helper.command.export(); | ||
|
|
||
| // Victim workspace under a different owner (so neither scope is auto- | ||
| // trusted via the owner-of-defaultScope wildcard). Trust ONLY the env's | ||
| // scope explicitly. The consumer's scope remains untrusted. | ||
| helper.scopeHelper.reInitWorkspace({ addRemoteScopeAsDefaultScope: false }); | ||
| helper.workspaceJsonc.addKeyValToWorkspace('defaultScope', 'other-owner.app'); | ||
| helper.workspaceJsonc.addKeyValToWorkspace('trustedScopes', [envScopeName]); | ||
| helper.scopeHelper.addRemoteScope(compRemote.scopePath); | ||
| npmCiRegistry.setResolver({ [compRemote.scopeName]: compRemote.scopePath }); | ||
|
|
||
| fs.removeSync(markerPath); | ||
| expect(fs.existsSync(markerPath), 'marker should be absent before import').to.be.false; | ||
|
|
||
| importOutput = helper.command.import(`${compRemote.scopeName}/comp1`); | ||
| }); | ||
|
|
||
| after(() => { | ||
| try { | ||
| fs.removeSync(markerPath); | ||
| } catch {} | ||
| if (originalMarkerEnv === undefined) delete process.env[MARKER_ENV_VAR]; | ||
| else process.env[MARKER_ENV_VAR] = originalMarkerEnv; | ||
| npmCiRegistry?.destroy(); | ||
| helper?.scopeHelper.destroy(); | ||
| }); | ||
|
|
||
| it('imports successfully (no error about untrusted scopes)', () => { | ||
| expect(importOutput).to.match(/successfully imported/i); | ||
| expect(importOutput).to.not.match(/isn't on the workspace's trusted list/i); | ||
| }); | ||
|
|
||
| it('loads the env from the trusted scope', () => { | ||
| expect(fs.existsSync(markerPath), `env module did not load; expected marker at ${markerPath}`).to.be.true; | ||
| }); | ||
| } | ||
| ); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| export { ScopeTrust } from './scope-trust'; | ||
| export { ScopeTrustCmd } from './scope-trust.cmd'; |
107 changes: 107 additions & 0 deletions
107
scopes/workspace/workspace/scope-trust/scope-trust.cmd.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| import type { Command } from '@teambit/cli'; | ||
| import { formatHint, formatItem, formatSection, formatSuccessSummary, formatTitle, joinSections } from '@teambit/cli'; | ||
| import { BitError } from '@teambit/bit-error'; | ||
| import chalk from 'chalk'; | ||
| import type { ScopeTrust } from './scope-trust'; | ||
|
|
||
| const ACTIONS = ['list', 'enable', 'disable', 'add', 'remove'] as const; | ||
| type Action = (typeof ACTIONS)[number]; | ||
|
|
||
| export class ScopeTrustCmd implements Command { | ||
| name = 'trust [action] [pattern]'; | ||
| description = "manage which scopes are trusted to load aspects (envs, etc.) into the workspace's process"; | ||
| arguments = [ | ||
| { | ||
| name: 'action', | ||
| description: `one of: ${ACTIONS.join(', ')}. defaults to "list".`, | ||
| }, | ||
| { | ||
| name: 'pattern', | ||
| description: 'scope pattern (required for "add" and "remove")', | ||
| }, | ||
| ]; | ||
| options = []; | ||
| group = 'component-config'; | ||
| // Don't load aspects for this command. If the workspace already references | ||
| // an aspect from a scope that the trust list doesn't allow, the pre-command | ||
| // aspect-load step would itself trip the gate, leaving the user with no way | ||
| // to run `bit scope trust` to fix it. Skipping aspect-load keeps the command | ||
| // usable as a recovery path. | ||
| loadAspects = false; | ||
| extendedDescription = `scope-trust is opt-in. when off (the default), aspects from any scope load without a check. when on, aspects from a scope outside the trust list trigger a prompt (interactive shells) or an error (non-interactive). | ||
|
|
||
| bit scope trust # same as "list" | ||
| bit scope trust list # show status; if on, print the effective trust list | ||
| bit scope trust enable # turn on (writes "trustedScopes": [] to workspace.jsonc) | ||
| bit scope trust disable # turn off (removes "trustedScopes" from workspace.jsonc) | ||
| bit scope trust add PATTERN # add a pattern (auto-enables if needed) | ||
| bit scope trust remove PATTERN # remove a pattern (does NOT disable when list is empty) | ||
|
|
||
| once on, the effective trust set is: builtin (teambit.*, bitdev.*) + the owner of defaultScope + entries listed under "trustedScopes". patterns are exact ("acme.frontend") or owner wildcard ("acme.*").`; | ||
|
|
||
|
davidfirst marked this conversation as resolved.
|
||
| constructor(private scopeTrust: ScopeTrust) {} | ||
|
|
||
| async report(args: string[]): Promise<string> { | ||
| const [rawAction, pattern] = args; | ||
| const action = (rawAction || 'list') as Action; | ||
| if (!ACTIONS.includes(action)) { | ||
| throw new BitError(`unknown action "${rawAction}". valid actions: ${ACTIONS.join(', ')}.`); | ||
| } | ||
| switch (action) { | ||
| case 'list': | ||
| return this.formatList(); | ||
| case 'enable': | ||
| await this.scopeTrust.enable(); | ||
| return formatSuccessSummary('scope-trust enabled (added trustedScopes: [] to workspace.jsonc)'); | ||
| case 'disable': | ||
| await this.scopeTrust.disable(); | ||
| return formatSuccessSummary('scope-trust disabled (removed trustedScopes from workspace.jsonc)'); | ||
| case 'add': | ||
| await this.scopeTrust.addTrustedScope(requirePattern(action, pattern)); | ||
| return formatSuccessSummary(`added ${chalk.bold(pattern)} to trustedScopes in workspace.jsonc`); | ||
| case 'remove': | ||
| await this.scopeTrust.removeTrustedScope(requirePattern(action, pattern)); | ||
| return formatSuccessSummary(`removed ${chalk.bold(pattern)} from trustedScopes in workspace.jsonc`); | ||
|
davidfirst marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
|
|
||
| private formatList(): string { | ||
| if (!this.scopeTrust.isOptedIn()) { | ||
| return joinSections([ | ||
| formatTitle('scope-trust is off for this workspace.'), | ||
| 'aspects from any scope load without a check.', | ||
| formatHint( | ||
| 'to turn on:\n bit scope trust enable (no scopes added; only builtins + owner-of-defaultScope auto-trusted)\n bit scope trust add <pattern> (turns on and adds the first scope)' | ||
| ), | ||
| ]); | ||
| } | ||
| const groups = this.scopeTrust.getEffectiveTrustedPatterns(); | ||
| return joinSections([ | ||
| formatTitle('scope-trust is on. aspects from these scopes load without a prompt:'), | ||
| formatSection( | ||
| 'builtin', | ||
| '', | ||
| groups.builtin.map((p) => formatItem(p)) | ||
| ), | ||
| formatSection( | ||
| 'inferred from workspace defaultScope', | ||
| '', | ||
| groups.owner.map((p) => formatItem(p)) | ||
| ), | ||
| groups.configured.length | ||
| ? formatSection( | ||
| 'configured in workspace.jsonc', | ||
| '', | ||
| groups.configured.map((p) => formatItem(p)) | ||
| ) | ||
| : formatHint('no scopes configured in workspace.jsonc. add one with `bit scope trust add <pattern>`.'), | ||
| ]); | ||
| } | ||
| } | ||
|
|
||
| function requirePattern(action: Action, pattern: string | undefined): string { | ||
| if (!pattern) { | ||
| throw new BitError(`"${action}" requires a pattern. example: bit scope trust ${action} acme.frontend`); | ||
| } | ||
| return pattern; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.