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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
Harden export solution ZIP validation (#385)
Priyanshu Agrawal4afc4e0b9e90
diff --git a/plugins/power-pages/scripts/tests/validate-export.test.js b/plugins/power-pages/scripts/tests/validate-export.test.jsnew file mode 100644index 000000000..e45926fc3--- /dev/null+++ b/plugins/power-pages/scripts/tests/validate-export.test.js@@ -0,0 +1,280 @@+const test = require('node:test');+const assert = require('node:assert/strict');+const crypto = require('node:crypto');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const zlib = require('node:zlib');+const { spawnSync } = require('node:child_process');++const VALIDATOR_PATH = path.join(+ __dirname,+ '..',+ '..',+ 'skills',+ 'export-solution',+ 'scripts',+ 'validate-export.js'+);++function crc32(data) {+ let crc = 0xffffffff;+ for (const byte of data) {+ crc ^= byte;+ for (let bit = 0; bit < 8; bit++) {+ crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1));+ }+ }+ return (crc ^ 0xffffffff) >>> 0;+}++function createZip(entries) {+ const localRecords = [];+ const centralRecords = [];+ let localOffset = 0;++ for (const entry of entries) {+ const name = Buffer.from(entry.name, 'utf8');+ const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data, 'utf8');+ const method = entry.method ?? 0;+ const compressedData = method === 8 ? zlib.deflateRawSync(data) : data;+ const checksum = crc32(data);++ const localHeader = Buffer.alloc(30);+ localHeader.writeUInt32LE(0x04034b50, 0);+ localHeader.writeUInt16LE(20, 4);+ localHeader.writeUInt16LE(0x0800, 6);+ localHeader.writeUInt16LE(method, 8);+ localHeader.writeUInt32LE(checksum, 14);+ localHeader.writeUInt32LE(compressedData.length, 18);+ localHeader.writeUInt32LE(data.length, 22);+ localHeader.writeUInt16LE(name.length, 26);+ localRecords.push(localHeader, name, compressedData);++ const centralHeader = Buffer.alloc(46);+ centralHeader.writeUInt32LE(0x02014b50, 0);+ centralHeader.writeUInt16LE(20, 4);+ centralHeader.writeUInt16LE(20, 6);+ centralHeader.writeUInt16LE(0x0800, 8);+ centralHeader.writeUInt16LE(method, 10);+ centralHeader.writeUInt32LE(checksum, 16);+ centralHeader.writeUInt32LE(compressedData.length, 20);+ centralHeader.writeUInt32LE(data.length, 24);+ centralHeader.writeUInt16LE(name.length, 28);+ centralHeader.writeUInt32LE(localOffset, 42);+ centralRecords.push(centralHeader, name);++ localOffset += localHeader.length + name.length + compressedData.length;+ }++ const centralDirectory = Buffer.concat(centralRecords);+ const endRecord = Buffer.alloc(22);+ endRecord.writeUInt32LE(0x06054b50, 0);+ endRecord.writeUInt16LE(entries.length, 8);+ endRecord.writeUInt16LE(entries.length, 10);+ endRecord.writeUInt32LE(centralDirectory.length, 12);+ endRecord.writeUInt32LE(localOffset, 16);++ return Buffer.concat([...localRecords, centralDirectory, endRecord]);+}++function makeProject(t) {+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'validate-export-'));+ t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+ return projectRoot;+}++function validSolutionEntries(extraEntries = []) {+ return [+ {+ name: 'Solution.xml',+ data: `<ImportExportXml>${crypto.randomBytes(1400).toString('hex')}</ImportExportXml>`,+ method: 8,+ },+ ...extraEntries,+ ];+}++function runValidator(projectRoot, env = process.env) {+ return spawnSync(process.execPath, [VALIDATOR_PATH], {+ cwd: projectRoot,+ input: JSON.stringify({ cwd: projectRoot }),+ encoding: 'utf8',+ timeout: 10000,+ env,+ });+}++test('approves when no exported solution ZIP exists', (t) => {+ const projectRoot = makeProject(t);+ const result = runValidator(projectRoot);++ assert.equal(result.status, 0, result.stderr);+});++test('approves a valid deflated solution ZIP containing Solution.xml', (t) => {+ const projectRoot = makeProject(t);+ fs.writeFileSync(+ path.join(projectRoot, 'release_unmanaged.zip'),+ createZip(validSolutionEntries())+ );++ const result = runValidator(projectRoot);++ assert.equal(result.status, 0, result.stderr);+});++test('handles malicious archive and path names without invoking a shell', (t) => {+ const projectRoot = makeProject(t);+ const markerName = 'validator-command-ran';+ const zipName = `release_$(touch ${markerName})_unmanaged.zip`;+ fs.writeFileSync(+ path.join(projectRoot, zipName),+ createZip(validSolutionEntries([+ {+ name: 'assets/"quoted"; $(ignored) & payload.txt',+ data: 'not executable',+ },+ ]))+ );++ const result = runValidator(projectRoot);++ assert.equal(result.status, 0, result.stderr);+ assert.equal(fs.existsSync(path.join(projectRoot, markerName)), false);+});++test('handles spaces, quotes, and cross-platform filename metacharacters', (t) => {+ const projectRoot = makeProject(t);+ const zipPath = path.join(projectRoot, "release 'review copy' & (final); 100%_managed.zip");+ fs.writeFileSync(zipPath, createZip(validSolutionEntries()));++ const result = runValidator(projectRoot);++ assert.equal(result.status, 0, result.stderr);+});++test('blocks a corrupt ZIP instead of approving by file size', (t) => {+ const projectRoot = makeProject(t);+ fs.writeFileSync(+ path.join(projectRoot, 'corrupt_unmanaged.zip'),+ crypto.randomBytes(1500)+ );++ const result = runValidator(projectRoot);++ assert.equal(result.status, 2);+ assert.match(result.stderr, /could not be validated/i);+});++test('blocks a structurally valid ZIP that does not contain Solution.xml', (t) => {+ const projectRoot = makeProject(t);+ fs.writeFileSync(+ path.join(projectRoot, 'missing_solution_managed.zip'),+ createZip([+ {+ name: 'Other.xml',+ data: crypto.randomBytes(1400),+ },+ ])+ );++ const result = runValidator(projectRoot);++ assert.equal(result.status, 2);+ assert.match(result.stderr, /does not contain solution\.xml/i);+});++test('blocks a ZIP when the Solution.xml payload fails its integrity check', (t) => {+ const projectRoot = makeProject(t);+ const archive = createZip([+ {+ name: 'Solution.xml',+ data: crypto.randomBytes(1400),+ method: 0,+ },+ ]);+ archive[30 + Buffer.byteLength('Solution.xml')] ^= 0xff;+ fs.writeFileSync(path.join(projectRoot, 'damaged_managed.zip'), archive);++ const result = runValidator(projectRoot);++ assert.equal(result.status, 2);+ assert.match(result.stderr, /integrity check/i);+});++test('blocks duplicate root Solution.xml entries', (t) => {+ const projectRoot = makeProject(t);+ fs.writeFileSync(+ path.join(projectRoot, 'duplicate_unmanaged.zip'),+ createZip([+ ...validSolutionEntries(),+ {+ name: 'solution.XML',+ data: crypto.randomBytes(1400),+ },+ ])+ );++ const result = runValidator(projectRoot);++ assert.equal(result.status, 2);+ assert.match(result.stderr, /duplicate Solution\.xml/i);+});++test('blocks a ZIP with a corrupt non-manifest local header', (t) => {+ const projectRoot = makeProject(t);+ const archive = createZip(validSolutionEntries([+ {+ name: 'Customizations.xml',+ data: crypto.randomBytes(1400),+ },+ ]));+ const secondLocalHeader = archive.indexOf(Buffer.from([0x50, 0x4b, 0x03, 0x04]), 4);+ archive.writeUInt32LE(0, secondLocalHeader);+ fs.writeFileSync(path.join(projectRoot, 'corrupt_entry_managed.zip'), archive);++ const result = runValidator(projectRoot);++ assert.equal(result.status, 2);+ assert.match(result.stderr, /local header.*invalid signature/i);+});++test('blocks local-header metadata that disagrees with the central directory', (t) => {+ const projectRoot = makeProject(t);+ const archive = createZip(validSolutionEntries());+ archive.writeUInt32LE(1, 18);+ fs.writeFileSync(path.join(projectRoot, 'corrupt_metadata_managed.zip'), archive);++ const result = runValidator(projectRoot);++ assert.equal(result.status, 2);+ assert.match(result.stderr, /sizes or checksum.*disagree/i);+});++test('blocks oversized archives before reading them into memory', (t) => {+ const projectRoot = makeProject(t);+ const zipPath = path.join(projectRoot, 'oversized_unmanaged.zip');+ fs.writeFileSync(zipPath, Buffer.alloc(0));+ fs.truncateSync(zipPath, 100 * 1024 * 1024 + 1);++ const result = runValidator(projectRoot);++ assert.equal(result.status, 2);+ assert.match(result.stderr, /exceeds the supported 100 MiB/i);+});++test('validates without unzip, grep, or any executable available on PATH', (t) => {+ const projectRoot = makeProject(t);+ fs.writeFileSync(+ path.join(projectRoot, 'windows-compatible_unmanaged.zip'),+ createZip(validSolutionEntries())+ );++ const envWithoutPath = Object.fromEntries(+ Object.entries(process.env).filter(([key]) => key.toLowerCase() !== 'path')+ );+ const result = runValidator(projectRoot, { ...envWithoutPath, PATH: '' });++ assert.equal(result.status, 0, result.stderr);+});diff --git a/plugins/power-pages/skills/export-solution/scripts/validate-export.js b/plugins/power-pages/skills/export-solution/scripts/validate-export.jsindex fd34487ca..9571dac59 100644--- a/plugins/power-pages/skills/export-solution/scripts/validate-export.js+++ b/plugins/power-pages/skills/export-solution/scripts/validate-export.js@@ -6,8 +6,234 @@const fs = require('fs');const path = require('path');-const { execSync } = require('child_process');-const { approve, block, runValidation, findProjectRoot, findPath, readDeferralMarker } = require('../../../scripts/lib/validation-helpers');+const zlib = require('zlib');+const { approve, block, runValidation, findProjectRoot, readDeferralMarker } = require('../../../scripts/lib/validation-helpers');++const END_OF_CENTRAL_DIRECTORY_SIGNATURE = 0x06054b50;+const CENTRAL_DIRECTORY_HEADER_SIGNATURE = 0x02014b50;+const LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50;+const MAX_ZIP_COMMENT_LENGTH = 0xffff;+const MIN_END_OF_CENTRAL_DIRECTORY_SIZE = 22;+const MAX_SOLUTION_ZIP_SIZE = 100 * 1024 * 1024;+const MAX_SOLUTION_XML_SIZE = 100 * 1024 * 1024;++function findEndOfCentralDirectory(archive) {+ const firstPossibleOffset = Math.max(+ 0,+ archive.length - MIN_END_OF_CENTRAL_DIRECTORY_SIZE - MAX_ZIP_COMMENT_LENGTH+ );++ for (let offset = archive.length - MIN_END_OF_CENTRAL_DIRECTORY_SIZE; offset >= firstPossibleOffset; offset--) {+ if (archive.readUInt32LE(offset) !== END_OF_CENTRAL_DIRECTORY_SIGNATURE) continue;++ const commentLength = archive.readUInt16LE(offset + 20);+ if (offset + MIN_END_OF_CENTRAL_DIRECTORY_SIZE + commentLength === archive.length) {+ return offset;+ }+ }++ throw new Error('the ZIP end-of-central-directory record is missing');+}++/**+ * Reads ZIP entry metadata without extracting files.+ *+ * ZIP archives end with an EOCD record that points to central-directory entries:+ * 0x02014b50 | metadata | name length | extra length | comment length | file name+ * The offsets and lengths are untrusted, so every read is bounded before use. ZIP64+ * and multi-disk archives are rejected because Power Platform solution packages do+ * not need either format and partially parsing them could approve a malformed file.+ * See: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT+ */+function readZipEntries(archive) {+ const eocdOffset = findEndOfCentralDirectory(archive);+ const diskNumber = archive.readUInt16LE(eocdOffset + 4);+ const centralDirectoryDisk = archive.readUInt16LE(eocdOffset + 6);+ const entriesOnDisk = archive.readUInt16LE(eocdOffset + 8);+ const totalEntries = archive.readUInt16LE(eocdOffset + 10);+ const centralDirectorySize = archive.readUInt32LE(eocdOffset + 12);+ const centralDirectoryOffset = archive.readUInt32LE(eocdOffset + 16);++ if (diskNumber !== 0 || centralDirectoryDisk !== 0 || entriesOnDisk !== totalEntries) {+ throw new Error('multi-disk ZIP archives are not supported');+ }+ if (+ totalEntries === 0xffff ||+ centralDirectorySize === 0xffffffff ||+ centralDirectoryOffset === 0xffffffff+ ) {+ throw new Error('ZIP64 archives are not supported');+ }++ const centralDirectoryEnd = centralDirectoryOffset + centralDirectorySize;+ if (centralDirectoryEnd > eocdOffset || centralDirectoryEnd > archive.length) {+ throw new Error('the ZIP central directory is outside the archive');+ }++ const entries = [];+ let offset = centralDirectoryOffset;+ for (let index = 0; index < totalEntries; index++) {+ if (offset + 46 > centralDirectoryEnd) {+ throw new Error('a ZIP central-directory entry is truncated');+ }+ if (archive.readUInt32LE(offset) !== CENTRAL_DIRECTORY_HEADER_SIGNATURE) {+ throw new Error('a ZIP central-directory entry has an invalid signature');+ }++ const flags = archive.readUInt16LE(offset + 8);+ const compressionMethod = archive.readUInt16LE(offset + 10);+ const crc = archive.readUInt32LE(offset + 16);+ const compressedSize = archive.readUInt32LE(offset + 20);+ const uncompressedSize = archive.readUInt32LE(offset + 24);+ const fileNameLength = archive.readUInt16LE(offset + 28);+ const extraFieldLength = archive.readUInt16LE(offset + 30);+ const commentLength = archive.readUInt16LE(offset + 32);+ const startingDisk = archive.readUInt16LE(offset + 34);+ const localHeaderOffset = archive.readUInt32LE(offset + 42);+ const entryEnd = offset + 46 + fileNameLength + extraFieldLength + commentLength;++ if (entryEnd > centralDirectoryEnd) {+ throw new Error('a ZIP central-directory entry exceeds its declared bounds');+ }+ if (startingDisk !== 0) {+ throw new Error('multi-disk ZIP entries are not supported');+ }+ if (+ compressedSize === 0xffffffff ||+ uncompressedSize === 0xffffffff ||+ localHeaderOffset === 0xffffffff+ ) {+ throw new Error('ZIP64 entries are not supported');+ }++ const nameBytes = archive.subarray(offset + 46, offset + 46 + fileNameLength);+ entries.push({+ name: nameBytes.toString((flags & 0x0800) !== 0 ? 'utf8' : 'latin1'),+ nameBytes,+ flags,+ compressionMethod,+ crc,+ compressedSize,+ uncompressedSize,+ localHeaderOffset,+ centralDirectoryStart: centralDirectoryOffset,+ });+ offset = entryEnd;+ }++ if (offset !== centralDirectoryEnd) {+ throw new Error('the ZIP central directory size does not match its entries');+ }++ return entries;+}++function crc32(data) {+ let crc = 0xffffffff;+ for (const byte of data) {+ crc ^= byte;+ for (let bit = 0; bit < 8; bit++) {+ crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1));+ }+ }+ return (crc ^ 0xffffffff) >>> 0;+}++function readCompressedEntryData(archive, entry) {+ const localHeaderEnd = entry.localHeaderOffset + 30;+ if (localHeaderEnd > entry.centralDirectoryStart || localHeaderEnd > archive.length) {+ throw new Error(`the local header for '${entry.name}' is truncated`);+ }+ if (archive.readUInt32LE(entry.localHeaderOffset) !== LOCAL_FILE_HEADER_SIGNATURE) {+ throw new Error(`the local header for '${entry.name}' has an invalid signature`);+ }++ const localFlags = archive.readUInt16LE(entry.localHeaderOffset + 6);+ const localCompressionMethod = archive.readUInt16LE(entry.localHeaderOffset + 8);+ const localCrc = archive.readUInt32LE(entry.localHeaderOffset + 14);+ const localCompressedSize = archive.readUInt32LE(entry.localHeaderOffset + 18);+ const localUncompressedSize = archive.readUInt32LE(entry.localHeaderOffset + 22);+ const localFileNameLength = archive.readUInt16LE(entry.localHeaderOffset + 26);+ const localExtraFieldLength = archive.readUInt16LE(entry.localHeaderOffset + 28);+ const fileNameStart = localHeaderEnd;+ const dataStart = fileNameStart + localFileNameLength + localExtraFieldLength;+ const dataEnd = dataStart + entry.compressedSize;++ if (dataEnd > entry.centralDirectoryStart || dataEnd > archive.length) {+ throw new Error(`the compressed data for '${entry.name}' is truncated`);+ }+ if (localFlags !== entry.flags || localCompressionMethod !== entry.compressionMethod) {+ throw new Error(`the local header for '${entry.name}' disagrees with the central directory`);+ }+ if (+ (entry.flags & 0x0008) === 0 &&+ (+ localCrc !== entry.crc ||+ localCompressedSize !== entry.compressedSize ||+ localUncompressedSize !== entry.uncompressedSize+ )+ ) {+ throw new Error(`the local header sizes or checksum for '${entry.name}' disagree with the central directory`);+ }+ if (!archive.subarray(fileNameStart, fileNameStart + localFileNameLength).equals(entry.nameBytes)) {+ throw new Error(`the local header name for '${entry.name}' disagrees with the central directory`);+ }++ return archive.subarray(dataStart, dataEnd);+}++function readEntryData(archive, entry) {+ const compressedData = readCompressedEntryData(archive, entry);+ if ((entry.flags & 0x0001) !== 0) {+ throw new Error(`the required entry '${entry.name}' is encrypted`);+ }+ if (entry.uncompressedSize > MAX_SOLUTION_XML_SIZE) {+ throw new Error(`the required entry '${entry.name}' is unexpectedly large`);+ }++ let data;+ if (entry.compressionMethod === 0) {+ data = compressedData;+ } else if (entry.compressionMethod === 8) {+ data = zlib.inflateRawSync(compressedData, {+ maxOutputLength: Math.max(1, entry.uncompressedSize + 1),+ });+ } else {+ throw new Error(`the required entry '${entry.name}' uses unsupported compression method ${entry.compressionMethod}`);+ }++ if (data.length !== entry.uncompressedSize || crc32(data) !== entry.crc) {+ throw new Error(`the required entry '${entry.name}' failed its integrity check`);+ }++ return data;+}++function validateZipContainsSolutionXml(zipPath) {+ const archive = fs.readFileSync(zipPath);+ const entries = readZipEntries(archive);++ // Checking every local header catches truncated payloads and mismatched metadata+ // without expanding arbitrary entries. Only Solution.xml is decompressed because+ // it is the required manifest and its CRC must prove the entry itself is intact.+ for (const entry of entries) {+ readCompressedEntryData(archive, entry);+ }++ const solutionEntries = entries.filter((entry) => {+ return entry.name.replace(/\\/g, '/').toLowerCase() === 'solution.xml';+ });++ if (solutionEntries.length === 0) {+ return false;+ }+ if (solutionEntries.length > 1) {+ throw new Error('the ZIP contains duplicate Solution.xml entries');+ }++ readEntryData(archive, solutionEntries[0]);+ return true;+}runValidation(async (cwd) => {if (readDeferralMarker(findProjectRoot(cwd) || cwd)) return approve(); // ALM deferred — silent-approve.@@ -37,25 +263,26 @@ runValidation(async (cwd) => {// Validate each zip foundfor (const zipPath of zipFiles) {- const stat = fs.statSync(zipPath);+ let stat;+ try {+ stat = fs.statSync(zipPath);+ } catch (error) {+ return block(`Solution zip '${path.basename(zipPath)}' could not be read: ${error.message}`);+ }if (stat.size < 1000) {return block(`Solution zip '${path.basename(zipPath)}' is too small (${stat.size} bytes). The export may have been truncated or failed.`);}+ if (stat.size > MAX_SOLUTION_ZIP_SIZE) {+ return block(`Solution zip '${path.basename(zipPath)}' exceeds the supported 100 MiB package size.`);+ }- // Verify Solution.xml is inside the ziptry {- const output = execSync(`unzip -l "${zipPath}" 2>/dev/null | grep -i solution.xml`, {- encoding: 'utf8',- timeout: 10000,- });- if (!output || !output.toLowerCase().includes('solution.xml')) {+ if (!validateZipContainsSolutionXml(zipPath)) {return block(`Solution zip '${path.basename(zipPath)}' does not contain solution.xml. The export appears corrupt.`);}- } catch {- // unzip not available or grep returned no match- // Fall back to just checking file size — already done above- // Don't block if unzip is unavailable+ } catch (error) {+ return block(`Solution zip '${path.basename(zipPath)}' could not be validated: ${error.message}`);}}