Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

10.9 KB
Raw Blame
const test = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const HOOK = path.join(__dirname, '..', '..', 'hooks', 'validate-write-safety.js');

function isInsideOrSame(root, target) {
  const rel = path.relative(root, target);
  return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
}

function runHook(payload, env) {
  const res = spawnSync(process.execPath, [HOOK], {
    input: JSON.stringify(payload),
    encoding: 'utf8',
    env: { ...process.env, ...(env || {}) },
  });
  return { status: res.status, stderr: res.stderr || '' };
}

function runHookWithSplitStdin(payload, splitNeedle) {
  return new Promise((resolve, reject) => {
    const child = require('node:child_process').spawn(process.execPath, [HOOK], {
      env: { ...process.env },
      stdio: ['pipe', 'pipe', 'pipe'],
    });
    const stdout = [];
    const stderr = [];
    child.stdout.on('data', (chunk) => stdout.push(chunk));
    child.stderr.on('data', (chunk) => stderr.push(chunk));
    child.on('error', reject);
    child.on('close', (status) => {
      resolve({
        status,
        stdout: Buffer.concat(stdout).toString('utf8'),
        stderr: Buffer.concat(stderr).toString('utf8'),
      });
    });
    const bytes = Buffer.from(JSON.stringify(payload), 'utf8');
    const needle = Buffer.from(splitNeedle, 'utf8');
    const at = bytes.indexOf(needle);
    assert.notEqual(at, -1, 'payload must contain the split needle');
    child.stdin.write(bytes.subarray(0, at + 1));
    setImmediate(() => child.stdin.end(bytes.subarray(at + 1)));
  });
}

let cwd;
test.beforeEach(() => {
  cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-ws-'));
  // Mark this as an active genpage session so the (session-scoped) guard engages.
  fs.writeFileSync(path.join(cwd, 'pcf-plan.md'), '# plan\n', 'utf8');
});
test.afterEach(() => {
  try { fs.rmSync(cwd, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); } catch { /* ignore */ }
});

test('write inside the working directory is allowed (exit 0)', () => {
  const payload = {
    tool_name: 'Write',
    tool_input: { file_path: path.join(cwd, 'sub', 'page.tsx'), content: 'x' },
    cwd,
  };
  assert.equal(runHook(payload).status, 0);
});

test('relative path resolving under cwd is allowed (exit 0)', () => {
  const payload = { tool_name: 'Edit', tool_input: { file_path: 'RuntimeTypes.ts', new_string: 'x' }, cwd };
  assert.equal(runHook(payload).status, 0);
});

test('write escaping the working directory is flagged, non-blocking (exit 1)', () => {
  // Target the drive/filesystem root so the path is outside BOTH cwd and the
  // tmpdir scratch exception (cwd itself lives under tmpdir here).
  const outside = path.join(path.parse(cwd).root, 'pcf-guard-evil', 'evil.ts');
  const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
  const { status, stderr } = runHook(payload);
  assert.equal(status, 1); // non-blocking: exit 1 (only exit 2 would block)
  assert.match(stderr, /outside your project folder/);
});

test('parent-traversal path escaping to the root is flagged, non-blocking (exit 1)', () => {
  const target = path.join(path.parse(cwd).root, 'pcf-guard-evil2.ts');
  const rel = path.relative(cwd, target); // e.g. ..\..\..\pcf-guard-evil2.ts
  const payload = { tool_name: 'Edit', tool_input: { file_path: rel, new_string: 'x' }, cwd };
  assert.equal(runHook(payload).status, 1);
});

test('outside-cwd write is NOT flagged when there is no pcf session (exit 0)', () => {
  fs.rmSync(path.join(cwd, 'pcf-plan.md'), { force: true });
  fs.rmSync(path.join(cwd, 'pcf-intent.json'), { force: true });
  const outside = path.join(path.parse(cwd).root, 'pcf-guard-evil', 'evil.ts');
  const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
  assert.equal(runHook(payload).status, 0);
});

test('pcf-plan.md in a working subdir activates the guard (exit 1)', () => {
  fs.rmSync(path.join(cwd, 'pcf-plan.md'), { force: true });
  const wd = path.join(cwd, 'my-page');
  fs.mkdirSync(wd);
  fs.writeFileSync(path.join(wd, 'pcf-plan.md'), '# plan\n', 'utf8');
  const outside = path.join(path.parse(cwd).root, 'pcf-guard-evil', 'evil.ts');
  const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
  assert.equal(runHook(payload).status, 1);
});

for (const marker of ['pcf-intent.json', 'pcf-plan.md']) {
  test(`pcf marker ${marker} at cwd activates the guard (exit 1)`, () => {
    fs.rmSync(path.join(cwd, 'pcf-plan.md'), { force: true });
    fs.rmSync(path.join(cwd, 'pcf-intent.json'), { force: true });
    fs.writeFileSync(path.join(cwd, marker), '{}\n', 'utf8');
    const outside = path.join(path.parse(cwd).root, 'pcf-guard-evil', 'evil.ts');
    const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
    assert.equal(runHook(payload).status, 1);
  });

  test(`pcf marker ${marker} in a working subdir activates the guard (exit 1)`, () => {
    fs.rmSync(path.join(cwd, 'pcf-plan.md'), { force: true });
    fs.rmSync(path.join(cwd, 'pcf-intent.json'), { force: true });
    const wd = path.join(cwd, 'my-pcf');
    fs.mkdirSync(wd);
    fs.writeFileSync(path.join(wd, marker), '{}\n', 'utf8');
    const outside = path.join(path.parse(cwd).root, 'pcf-guard-evil', 'evil.ts');
    const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
    assert.equal(runHook(payload).status, 1);
  });
}

test('tmpdir scratch writes are allowed (exit 0)', () => {
  const payload = {
    tool_name: 'Write',
    tool_input: { file_path: path.join(os.tmpdir(), 'scratch-xyz.txt'), content: 'x' },
    cwd,
  };
  assert.equal(runHook(payload).status, 0);
});

test('non-write tools are ignored (exit 0)', () => {
  const payload = { tool_name: 'Read', tool_input: { file_path: '/etc/passwd' }, cwd };
  assert.equal(runHook(payload).status, 0);
});

test('PCF_SKIP_WRITE_GUARD=1 bypasses the guard (exit 0)', () => {
  const outside = path.join(path.dirname(cwd), 'sibling', 'evil.ts');
  const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
  assert.equal(runHook(payload, { PCF_SKIP_WRITE_GUARD: '1' }).status, 0);
});

test('PCF_SKIP_WRITE_GUARD=true also bypasses the guard (exit 0)', () => {
  const outside = path.join(path.parse(cwd).root, 'pcf-guard-evil', 'evil.ts');
  const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
  assert.equal(runHook(payload, { PCF_SKIP_WRITE_GUARD: 'true' }).status, 0);
});

test('missing file_path is not our concern (exit 0)', () => {
  const payload = { tool_name: 'Write', tool_input: { content: 'x' }, cwd };
  assert.equal(runHook(payload).status, 0);
});

test('Windows: in-cwd target with different drive-letter casing is allowed (exit 0)', { skip: process.platform !== 'win32' }, () => {
  // A tool may emit `d:\...` while cwd is `D:\...`; case-insensitive containment
  // on Windows must not reject a legitimate in-project write.
  const target = path.join(cwd, 'sub', 'page.tsx');
  const lowered = target.charAt(0).toLowerCase() + target.slice(1);
  const payload = { tool_name: 'Write', tool_input: { file_path: lowered, content: 'x' }, cwd };
  assert.equal(runHook(payload).status, 0);
});

test('PCF_DISABLE_HOOKS=1 disables the guard (exit 0 for an outside write)', () => {
  const outside = path.join(path.parse(cwd).root, 'pcf-guard-evil', 'evil.ts');
  const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
  assert.equal(runHook(payload, { PCF_DISABLE_HOOKS: '1' }).status, 0);
});

test('PCF_DISABLE_HOOKS=1 exits 0 even when skill discovery would throw', () => {
  const preload = path.join(cwd, 'hook-readdir-throw-preload.js');
  assert.equal(isInsideOrSame(__dirname, preload), false);
  fs.writeFileSync(preload, [
    "const fs = require('node:fs');",
    'const real = fs.readdirSync;',
    "fs.readdirSync = function patched(p, ...args) {",
    "  if (String(p).includes('plugins' + require('node:path').sep + 'pcf' + require('node:path').sep + 'skills')) {",
    "    const err = new Error('EACCES: permission denied, scandir skills');",
    "    err.code = 'EACCES';",
    "    throw err;",
    '  }',
    '  return real.call(this, p, ...args);',
    '};',
  ].join('\n'));
  try {
    const outside = path.join(path.parse(cwd).root, 'pcf-guard-evil', 'evil.ts');
    const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
    const res = spawnSync(process.execPath, ['-r', preload, HOOK], {
      input: JSON.stringify(payload),
      encoding: 'utf8',
      env: { ...process.env, PCF_DISABLE_HOOKS: '1' },
    });
    assert.equal(res.status, 0, res.stderr);
  } finally {
    fs.rmSync(preload, { force: true });
  }
});

test('write-safety guard: an unreadable skills folder cannot crash the ENABLED hook', () => {
  // The hook needs only the stdin reader, not skill discovery. Loading discovery would scan the skills
  // folder at require time, so an EACCES there would crash the hook even though it never uses it.
  const preload = path.join(cwd, 'hook-readdir-throw-preload-enabled.js');
  assert.equal(isInsideOrSame(__dirname, preload), false);
  fs.writeFileSync(preload, [
    "const fs = require('node:fs');",
    'const real = fs.readdirSync;',
    "fs.readdirSync = function patched(p, ...args) {",
    "  if (String(p).includes('plugins' + require('node:path').sep + 'pcf' + require('node:path').sep + 'skills')) {",
    "    const err = new Error('EACCES: permission denied, scandir skills');",
    "    err.code = 'EACCES';",
    "    throw err;",
    '  }',
    '  return real.call(this, p, ...args);',
    '};',
  ].join('\n'));
  try {
    const env = { ...process.env };
    delete env.PCF_DISABLE_HOOKS;
    const res = spawnSync(process.execPath, ['-r', preload, HOOK], { input: 'not json', encoding: 'utf8', env });
    assert.equal(res.status, 0, res.stderr);
  } finally {
    fs.rmSync(preload, { force: true });
  }
});

test('hook stdin decoding preserves multibyte paths split across pipe chunks', async () => {
  const outside = path.join(path.parse(cwd).root, 'pcf-guard-東京', 'evil.ts');
  const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
  const { status, stderr } = await runHookWithSplitStdin(payload, '東京');
  assert.equal(status, 1);
  assert.match(stderr, /outside your project folder/);
  assert.match(stderr, new RegExp(outside.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
});

test('unparseable stdin does not block (exit 0)', () => {
  const res = spawnSync(process.execPath, [HOOK], { input: 'not json', encoding: 'utf8' });
  assert.equal(res.status, 0);
});