Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
107 changes: 107 additions & 0 deletions e2e/harmony/scope-trust.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/**
* Verifies the workspace's scope-trust gate around aspect loading.
*
* 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.
*
* Expectation: because scope A isn't on the second workspace's effective
* trust list (builtin + owner-of-defaultScope + configured), the aspect
* loader doesn't require the env, and the marker file is never written
* after the import.
*/
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';

(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;

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',
`
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();
`
);

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 with a defaultScope under a different owner — without
// this, the owner-wildcard derived from defaultScope would auto-trust
// the publisher's scope and the assertion wouldn't reflect a real
// cross-owner import.
helper.scopeHelper.reInitWorkspace({ addRemoteScopeAsDefaultScope: false });
helper.workspaceJsonc.addKeyValToWorkspace('defaultScope', 'other-owner.app');
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;

try {
helper.command.importComponent('comp1');
} catch {
// Aspect load refused → import command may exit non-zero. The
// marker-file check below is the source of truth.
}
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;
});
}
);
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
3 changes: 3 additions & 0 deletions scopes/workspace/workspace/scope-trust/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { ScopeTrust } from './scope-trust';
export type { TrustedScopesGroups } from './scope-trust';
export { ScopeTrustCmd, ScopeUntrustCmd } from './scope-trust.cmd';
73 changes: 73 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,73 @@
import type { Command } from '@teambit/cli';
import { formatSuccessSummary } from '@teambit/cli';
import chalk from 'chalk';
import type { ScopeTrust } from './scope-trust';

export class ScopeTrustCmd implements Command {
name = 'trust [scope-pattern]';
description = 'add a scope to the workspace trust list, or list trusted scopes when called without args';
arguments = [
{
name: 'scope-pattern',
description: 'scope name (e.g. "acme.frontend") or owner wildcard (e.g. "acme.*")',
},
];
options = [];
group = 'component-config';
extendedDescription = `trusted scopes can ship aspects (envs, generators) whose code is \`require()\`d locally during \`bit import\` / \`bit compile\`. by default the workspace trusts:
- builtin: teambit.*, bitdev.*
- the owner of the workspace's defaultScope (e.g. defaultScope "acme.frontend" trusts "acme.*")
- anything explicitly listed under "trustedScopes" in workspace.jsonc

run \`bit scope trust\` (no args) to inspect the effective list. run \`bit scope untrust <pattern>\` to remove an entry.`;

Comment thread
davidfirst marked this conversation as resolved.
constructor(private scopeTrust: ScopeTrust) {}

async report(args: string[]): Promise<string> {
const scopePattern = args[0];
if (!scopePattern) {
return this.formatList();
}
await this.scopeTrust.addTrustedScope(scopePattern);
return formatSuccessSummary(`added ${chalk.bold(scopePattern)} to trustedScopes in workspace.jsonc`);
}

private formatList(): string {
const groups = this.scopeTrust.getEffectiveTrustedPatterns();
const lines: string[] = [];
lines.push(chalk.bold('Trusted scopes (aspects from these scopes load without a prompt):'));
lines.push('');
lines.push(chalk.dim('builtin:'));
groups.builtin.forEach((p) => lines.push(` ${p}`));
if (groups.owner.length) {
lines.push('');
lines.push(chalk.dim('inferred from workspace defaultScope:'));
groups.owner.forEach((p) => lines.push(` ${p}`));
}
lines.push('');
lines.push(chalk.dim('configured in workspace.jsonc:'));
if (!groups.configured.length) {
lines.push(` ${chalk.dim('(none — use `bit scope trust <pattern>` to add)')}`);
} else {
groups.configured.forEach((p) => lines.push(` ${p}`));
}
return lines.join('\n');
}
}

export class ScopeUntrustCmd implements Command {
name = 'untrust <scope-pattern>';
description = 'remove a scope pattern from the workspace trust list (workspace.jsonc)';
arguments = [{ name: 'scope-pattern', description: 'pattern to remove (must match what was added)' }];
options = [];
group = 'component-config';
extendedDescription = `removes <scope-pattern> from "trustedScopes" under teambit.workspace/workspace in workspace.jsonc. builtin and owner-wildcard entries cannot be removed (they are computed at runtime).`;

constructor(private scopeTrust: ScopeTrust) {}

async report(args: string[]): Promise<string> {
const scopePattern = args[0];
await this.scopeTrust.removeTrustedScope(scopePattern);
return formatSuccessSummary(`removed ${chalk.bold(scopePattern)} from trustedScopes in workspace.jsonc`);
}
}
Loading