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.1 KB
Raw Blame
'use strict';

const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');

const {
  WORK_DIRECTORY_PREFIX,
  cleanupPackedTemplateSolution,
  isGeneratedWorkDirectoryPath,
  isOwnedWorkDirectory,
  packTemplateSolution,
  parseArgs,
} = require('../pack-template-solution');
const { PAC_LOG_TAIL_BYTES, commandError, runPac } = require('../lib/pac-command');

function tempDir() {
  return fs.mkdtempSync(path.join(os.tmpdir(), 'pack-template-solution-test-'));
}

function createSolutionSource(root) {
  const other = path.join(root, 'Other');
  fs.mkdirSync(other, { recursive: true });
  fs.writeFileSync(path.join(other, 'Solution.xml'), [
    '<ImportExportXml><SolutionManifest>',
    '<UniqueName>test_template</UniqueName>',
    '<Version>1.0.0.0</Version>',
    '<Managed>0</Managed>',
    '</SolutionManifest></ImportExportXml>',
  ].join(''));
  fs.writeFileSync(path.join(other, 'Customizations.xml'), '<ImportExportXml />');
}

function fakeSolutionZip() {
  const name = Buffer.from('solution.xml');
  const header = Buffer.alloc(30);
  header.writeUInt32LE(0x04034b50, 0);
  header.writeUInt16LE(name.length, 26);
  return Buffer.concat([header, name]);
}

test('parseArgs accepts pack and cleanup inputs', () => {
  assert.deepEqual(parseArgs(['--solutionPath', '/tmp/source']), {
    solutionPath: '/tmp/source',
  });
  assert.deepEqual(parseArgs(['--cleanup', '--workDirectory', '/tmp/work']), {
    cleanup: true,
    workDirectory: '/tmp/work',
  });
  assert.deepEqual(parseArgs([
    '--cleanup',
    '--workDirectory', '/tmp/work',
    '--cleanupMarker', '/tmp/marker.json',
    '--cleanupToken', 'secret',
  ]), {
    cleanup: true,
    workDirectory: '/tmp/work',
    cleanupMarker: '/tmp/marker.json',
    cleanupToken: 'secret',
  });
});

test('packTemplateSolution packs an unmanaged source tree into an owned temp directory', (t) => {
  const root = tempDir();
  const tmpRoot = path.join(root, 'tmp');
  const source = path.join(root, 'solution');
  fs.mkdirSync(tmpRoot);
  createSolutionSource(source);
  t.after(() => fs.rmSync(root, { recursive: true, force: true }));
  const calls = [];

  const result = packTemplateSolution({ solutionPath: source }, {
    tmpRoot,
    runPac(args) {
      calls.push(args);
      fs.writeFileSync(args[args.indexOf('--zipfile') + 1], fakeSolutionZip());
      return { status: 0, stdout: 'packed', stderr: '' };
    },
  });

  assert.equal(result.ok, true);
  assert.equal(result.solutionPath, path.resolve(source));
  assert.equal(isGeneratedWorkDirectoryPath(result.workDirectory, tmpRoot), true);
  assert.equal(isOwnedWorkDirectory(result.workDirectory, {
    tmpRoot,
    cleanupMarker: result.cleanupMarker,
    cleanupToken: result.cleanupToken,
  }), true);
  assert.deepEqual(calls, [[
    'solution', 'pack',
    '--zipfile', result.zipPath,
    '--folder', path.resolve(source),
    '--packagetype', 'Unmanaged',
  ]]);
  assert.equal(fs.existsSync(result.zipPath), true);
  assert.deepEqual(cleanupPackedTemplateSolution(result.workDirectory, {
    tmpRoot,
    cleanupMarker: result.cleanupMarker,
    cleanupToken: 'wrong-token',
  }), {
    ok: false,
    error: 'workDirectory ownership could not be verified',
  });
  assert.equal(fs.existsSync(result.workDirectory), true);
  assert.deepEqual(cleanupPackedTemplateSolution(result.workDirectory, {
    tmpRoot,
    cleanupMarker: result.cleanupMarker,
    cleanupToken: result.cleanupToken,
  }), {
    ok: true,
    removed: true,
  });
  assert.equal(fs.existsSync(result.workDirectory), false);
  assert.equal(fs.existsSync(result.cleanupMarker), false);
});

test('packTemplateSolution rejects invalid source and removes partial output after PAC failure', (t) => {
  const root = tempDir();
  const tmpRoot = path.join(root, 'tmp');
  fs.mkdirSync(tmpRoot);
  t.after(() => fs.rmSync(root, { recursive: true, force: true }));
  let calls = 0;

  const invalid = packTemplateSolution({ solutionPath: path.join(root, 'missing') }, {
    tmpRoot,
    runPac() {
      calls++;
      return { status: 0, stdout: '', stderr: '' };
    },
  });
  assert.equal(invalid.ok, false);
  assert.equal(invalid.step, 'validation');
  assert.equal(calls, 0);

  const source = path.join(root, 'solution');
  createSolutionSource(source);
  const failed = packTemplateSolution({ solutionPath: source }, {
    tmpRoot,
    runPac() {
      calls++;
      return { status: 1, stdout: '', stderr: 'pack rejected' };
    },
  });
  assert.equal(failed.ok, false);
  assert.equal(failed.step, 'pack');
  assert.match(failed.error, /pack rejected/);
  assert.equal(fs.readdirSync(tmpRoot).length, 0);
});

test('cleanup rejects arbitrary paths outside generated work directories', (t) => {
  const root = tempDir();
  t.after(() => fs.rmSync(root, { recursive: true, force: true }));
  assert.equal(isGeneratedWorkDirectoryPath(root, path.dirname(root)), false);
  assert.deepEqual(cleanupPackedTemplateSolution(root, { tmpRoot: path.dirname(root) }), {
    ok: false,
    error: 'workDirectory ownership could not be verified',
  });
});

test('cleanup rejects matching temporary directories without the ownership token', (t) => {
  const root = tempDir();
  const tmpRoot = path.join(root, 'tmp');
  const unrelated = path.join(tmpRoot, `${WORK_DIRECTORY_PREFIX}unrelated`);
  fs.mkdirSync(unrelated, { recursive: true });
  fs.writeFileSync(path.join(unrelated, 'keep.txt'), 'keep');
  t.after(() => fs.rmSync(root, { recursive: true, force: true }));

  assert.equal(isGeneratedWorkDirectoryPath(unrelated, tmpRoot), true);
  assert.deepEqual(cleanupPackedTemplateSolution(unrelated, { tmpRoot }), {
    ok: false,
    error: 'workDirectory ownership could not be verified',
  });
  assert.equal(fs.readFileSync(path.join(unrelated, 'keep.txt'), 'utf8'), 'keep');
});

test('packTemplateSolution rejects a symlinked ZIP output without reading its target', (t) => {
  const root = tempDir();
  const tmpRoot = path.join(root, 'tmp');
  const source = path.join(root, 'solution');
  const outsideZip = path.join(root, 'outside.zip');
  fs.mkdirSync(tmpRoot);
  createSolutionSource(source);
  fs.writeFileSync(outsideZip, fakeSolutionZip());
  t.after(() => fs.rmSync(root, { recursive: true, force: true }));
  let symlinksUnavailable = false;

  const result = packTemplateSolution({ solutionPath: source }, {
    tmpRoot,
    runPac(args) {
      const zipPath = args[args.indexOf('--zipfile') + 1];
      try {
        fs.symlinkSync(outsideZip, zipPath);
      } catch (err) {
        if (err.code === 'EPERM' || err.code === 'EACCES') {
          symlinksUnavailable = true;
          t.skip(`symlinks are unavailable: ${err.code}`);
          return { status: 1, stdout: '', stderr: err.message };
        }
        throw err;
      }
      return { status: 0, stdout: 'packed', stderr: '' };
    },
  });

  if (symlinksUnavailable) return;
  assert.equal(result.ok, false);
  assert.equal(result.step, 'output');
  assert.equal(fs.readFileSync(outsideZip).equals(fakeSolutionZip()), true);
  assert.deepEqual(fs.readdirSync(tmpRoot), []);
});

test('packTemplateSolution preserves the PAC error when cleanup also fails', (t) => {
  const root = tempDir();
  const tmpRoot = path.join(root, 'tmp');
  const source = path.join(root, 'solution');
  fs.mkdirSync(tmpRoot);
  createSolutionSource(source);
  t.after(() => fs.rmSync(root, { recursive: true, force: true }));
  const fsWithBlockedCleanup = {
    ...fs,
    rmSync() {
      throw new Error('EPERM');
    },
  };

  const result = packTemplateSolution({ solutionPath: source }, {
    fs: fsWithBlockedCleanup,
    tmpRoot,
    runPac() {
      return { status: 1, stdout: '', stderr: 'pack rejected' };
    },
  });

  assert.equal(result.ok, false);
  assert.equal(result.step, 'pack');
  assert.match(result.error, /pack rejected/);
  assert.match(result.cleanupError, /EPERM/);
  assert.equal(result.workDirectory.startsWith(tmpRoot), true);
});

test('runPac invokes pac.exe directly on Windows without a command shell', () => {
  const calls = [];
  runPac(['solution', 'pack', '--folder', 'source'], {
    platform: 'win32',
    runCommand(command, args, options) {
      calls.push([command, args, options]);
      return 'ok';
    },
  });
  assert.equal(calls[0][0], 'pac.exe');
  assert.deepEqual(calls[0][1], ['solution', 'pack', '--folder', 'source']);
  assert.equal(calls[0][2].shell, false);
  assert.equal(calls[0][2].maxBuffer, undefined);
  assert.equal(calls[0][2].stdio[0], 'ignore');
  assert.equal(typeof calls[0][2].stdio[1], 'number');
  assert.equal(calls[0][2].stdio[1], calls[0][2].stdio[2]);
});

test('runPac streams verbose output to disk and returns only its bounded tail', (t) => {
  const root = tempDir();
  t.after(() => fs.rmSync(root, { recursive: true, force: true }));
  const marker = 'PAC upload completed';

  const result = runPac(['pages', 'upload-code-site'], {
    tmpRoot: root,
    runCommand(command, args, options) {
      assert.equal(command, process.platform === 'win32' ? 'pac.exe' : 'pac');
      fs.writeSync(options.stdio[1], `${'x'.repeat(PAC_LOG_TAIL_BYTES * 2)}\n${marker}`);
    },
  });

  assert.equal(result.status, 0);
  assert.equal(Buffer.byteLength(result.stdout), PAC_LOG_TAIL_BYTES);
  assert.match(result.stdout, new RegExp(`${marker}$`));
  assert.deepEqual(fs.readdirSync(root), []);
});

test('runPac keeps the PAC log tail when the command fails', (t) => {
  const root = tempDir();
  t.after(() => fs.rmSync(root, { recursive: true, force: true }));

  const result = runPac(['pages', 'upload-code-site'], {
    tmpRoot: root,
    runCommand(command, args, options) {
      fs.writeSync(options.stdio[2], 'Upload failed after processing site files');
      const error = new Error('Command failed without captured stdio');
      error.status = 1;
      throw error;
    },
  });

  assert.equal(result.status, 1);
  assert.match(result.stderr, /Upload failed after processing site files/);
  assert.match(commandError('pac pages upload-code-site', result), /processing site files/);
  assert.doesNotMatch(commandError('pac pages upload-code-site', result), /without captured stdio/);
  assert.deepEqual(fs.readdirSync(root), []);
});