Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
203 changes: 203 additions & 0 deletions e2e/harmony/scope-trust.e2e.ts
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 || ''}`;
}
Comment thread
davidfirst marked this conversation as resolved.
});

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;
});
}
);
7 changes: 5 additions & 2 deletions scopes/scope/scope/scope-aspects-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,11 @@ needed-for: ${neededFor || '<unknown>'}`);
return new RequireableComponent(
capsule.component,
async () => {
// eslint-disable-next-line global-require, import/no-dynamic-require
// Honor the workspace's scope-trust hook if registered. Absent in
// pure scope (remote-server) contexts.
const guard = this.scope.getAspectLoadGuard();
if (guard) await guard(capsule.component.id);

const plugins = this.aspectLoader.getPlugins(capsule.component, capsule.path);
if (plugins.has()) {
await this.compileIfNoDist(capsule, capsule.component);
Expand All @@ -227,7 +231,6 @@ needed-for: ${neededFor || '<unknown>'}`);
const runtimePath = scopeRuntime || mainRuntime;
// eslint-disable-next-line global-require, import/no-dynamic-require
if (runtimePath) require(runtimePath);
// eslint-disable-next-line global-require, import/no-dynamic-require
return aspect;
},
capsule
Expand Down
15 changes: 15 additions & 0 deletions scopes/scope/scope/scope.main.runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,21 @@ export class ScopeMain implements ComponentFactory {

localAspects: string[] = [];

/**
* Optional hook called immediately before an aspect is `require()`d from a
* scope-aspects capsule. Throws to refuse the load. The workspace aspect
* registers this to enforce the per-workspace scope-trust list.
*/
private aspectLoadGuard?: (componentId: ComponentID) => Promise<void>;

setAspectLoadGuard(guard: (componentId: ComponentID) => Promise<void>): void {
this.aspectLoadGuard = guard;
}

getAspectLoadGuard(): ((componentId: ComponentID) => Promise<void>) | undefined {
return this.aspectLoadGuard;
}

/**
* name of the scope
*/
Expand Down
2 changes: 2 additions & 0 deletions scopes/workspace/workspace/scope-trust/index.ts
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 scopes/workspace/workspace/scope-trust/scope-trust.cmd.ts
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.*").`;

Comment thread
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`);
Comment thread
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;
}
Loading