All files / agent/src/executors nativeExecutor.ts

87.98% Statements 315/358
75% Branches 39/52
100% Functions 12/12
87.98% Lines 315/358

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 3591x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x   1x 1x 11x 11x 11x 11x 1x 1x 1x 1x   1x 1x 1x 11x 11x 1x 1x 11x 11x 11x 8x 8x 8x 8x 8x 33x 25x 25x 25x 33x 11x 11x 11x 11x                   11x 11x 11x 11x 11x 11x 1x 1x 11x 11x 2x 11x 9x 9x 11x 11x 11x             11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x                     11x 1x 1x 14x 11x 11x 11x     14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 99x 66x 66x 99x 11x 11x 11x 11x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x     11x   11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x   1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 9x 9x 2x 2x 2x 2x 11x 3x 3x 3x 3x 3x 1x 1x 1x 3x 3x 2x 2x 11x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 5x 5x 2x 2x 5x 3x 3x 5x 4x     4x 4x 4x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x  
/**
 * Native Executor - Non-Docker job execution
 *
 * Runs build commands directly on the host OS in an isolated temp workspace.
 * Designed for iOS/macOS builds that require native toolchains (Xcode, etc.)
 * which are not available inside Docker containers.
 *
 * Security model:
 * - Jobs run in an isolated temp directory (not the developer's workspace)
 * - Environment variables are explicitly injected (PATH preserved)
 * - Timeout enforcement with graceful shutdown (SIGTERM → 10s → SIGKILL)
 */
 
import { Executor, ExecutionOptions, ExecutionResult } from './types.js';
import { spawn, ChildProcess } from 'child_process';
import { promises as fs } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
 
export interface NativeExecutorConfig {
  allowedPaths?: string[];
  userIsolation?: boolean;
  sandboxProfile?: string;
  defaultTimeout?: number; // milliseconds
}
 
export class NativeExecutor implements Executor {
  readonly type = 'native' as const;
  private tempWorkspaces: Set<string> = new Set();
 
  constructor(private config: NativeExecutorConfig = {}) {}
 
  async validate(): Promise<{ valid: boolean; errors: string[] }> {
    const errors: string[] = [];
 
    // 1. Check OS is macOS or Linux
    const platform = process.platform;
    if (platform !== 'darwin' && platform !== 'linux') {
      errors.push(`Native execution is not supported on ${platform}. Requires macOS or Linux.`);
    }
 
    // 2. Check temp directory is writable
    const testDir = join(tmpdir(), `buildhive-validate-${randomUUID()}`);
    try {
      await fs.mkdir(testDir, { recursive: true });
      const testFile = join(testDir, 'test');
      await fs.writeFile(testFile, 'test');
      await fs.rm(testDir, { recursive: true, force: true });
    } catch {
      errors.push(`Temp directory ${tmpdir()} is not writable`);
    }
 
    // 3. Check shell is available
    const shellAvailable = await this.checkShellAvailable();
    if (!shellAvailable) {
      errors.push('No supported shell found (bash or zsh)');
    }
 
    return {
      valid: errors.length === 0,
      errors,
    };
  }
 
  async execute(options: ExecutionOptions): Promise<ExecutionResult> {
    const startTime = Date.now();
    const timeout = options.timeout ?? this.config.defaultTimeout ?? 600_000; // 10 min default
 
    // 1. Create isolated workspace
    const workspace = join(tmpdir(), `buildhive-native-${randomUUID()}`);
    await fs.mkdir(workspace, { recursive: true });
    this.tempWorkspaces.add(workspace);
 
    // Ensure workDir exists (may be the workspace itself or a subdirectory)
    const workDir = options.workDir || workspace;
    await fs.mkdir(workDir, { recursive: true });
 
    let stdout = '';
    let stderr = '';
    let logs = '';
 
    try {
      // 2. Build environment: preserve PATH and SDK paths, merge user env
      const environment = this.buildEnvironment(options.environment);
 
      // 3. Resolve shell
      const shell = await this.resolveShell();
 
      // 4. Spawn child process
      const result = await new Promise<{ exitCode: number }>((resolve, reject) => {
        const proc: ChildProcess = spawn(shell, ['-c', options.command], {
          cwd: workDir,
          env: environment,
          stdio: ['ignore', 'pipe', 'pipe'],
        });
 
        let killed = false;
        let killTimer: ReturnType<typeof setTimeout> | undefined;
 
        // Timeout enforcement: SIGTERM then SIGKILL after 10s
        const timeoutTimer = setTimeout(() => {
          if (!killed) {
            killed = true;
            proc.kill('SIGTERM');
            killTimer = setTimeout(() => {
              proc.kill('SIGKILL');
            }, 10_000);
          }
        }, timeout);
 
        // Abort signal handling
        const onAbort = () => {
          if (!killed) {
            killed = true;
            proc.kill('SIGTERM');
            killTimer = setTimeout(() => {
              proc.kill('SIGKILL');
            }, 10_000);
          }
        };
 
        if (options.abortSignal) {
          options.abortSignal.addEventListener('abort', onAbort, { once: true });
        }
 
        // Stream stdout
        proc.stdout?.on('data', (data: Buffer) => {
          const text = data.toString();
          stdout += text;
          // Stream line by line to onLog
          const lines = text.split('\n');
          for (const line of lines) {
            if (line.length > 0) {
              logs += line + '\n';
              options.onLog?.(line);
            }
          }
        });
 
        // Stream stderr
        proc.stderr?.on('data', (data: Buffer) => {
          const text = data.toString();
          stderr += text;
          const lines = text.split('\n');
          for (const line of lines) {
            if (line.length > 0) {
              logs += line + '\n';
              options.onLog?.(line);
            }
          }
        });
 
        proc.on('close', (code: number | null) => {
          clearTimeout(timeoutTimer);
          if (killTimer) clearTimeout(killTimer);
          if (options.abortSignal) {
            options.abortSignal.removeEventListener('abort', onAbort);
          }
 
          if (killed && code === null) {
            resolve({ exitCode: 143 }); // SIGTERM exit code
          } else {
            resolve({ exitCode: code ?? 1 });
          }
        });
 
        proc.on('error', (err: Error) => {
          clearTimeout(timeoutTimer);
          if (killTimer) clearTimeout(killTimer);
          if (options.abortSignal) {
            options.abortSignal.removeEventListener('abort', onAbort);
          }
          reject(err);
        });
      });
 
      // 5. Collect artifacts
      const artifacts = await this.collectArtifacts(
        workDir,
        options.artifactPaths || []
      );
 
      const durationMs = Date.now() - startTime;
 
      return {
        exitCode: result.exitCode,
        stdout,
        stderr,
        durationMs,
        artifacts,
        logs,
      };
    } catch (error) {
      const durationMs = Date.now() - startTime;
      return {
        exitCode: 1,
        stdout,
        stderr: stderr + (error instanceof Error ? error.message : String(error)),
        durationMs,
        artifacts: [],
        logs,
      };
    }
  }
 
  async cleanup(): Promise<void> {
    const removePromises = Array.from(this.tempWorkspaces).map(async (dir) => {
      try {
        await fs.rm(dir, { recursive: true, force: true });
      } catch {
        // Ignore cleanup errors
      }
    });
    await Promise.all(removePromises);
    this.tempWorkspaces.clear();
  }
 
  /**
   * Build the environment for the child process.
   * Preserves PATH and common SDK paths from the system, then merges user-provided vars.
   */
  private buildEnvironment(
    userEnv?: Record<string, string>
  ): Record<string, string> {
    // Start with essential system env vars
    const base: Record<string, string> = {};
 
    // Preserve PATH
    if (process.env.PATH) {
      base.PATH = process.env.PATH;
    }
 
    // Preserve common SDK paths
    const sdkVars = [
      'HOME',
      'USER',
      'SHELL',
      'LANG',
      'JAVA_HOME',
      'ANDROID_HOME',
      'ANDROID_SDK_ROOT',
      'DEVELOPER_DIR', // Xcode
      'SDKROOT',
    ];
 
    for (const key of sdkVars) {
      if (process.env[key]) {
        base[key] = process.env[key] as string;
      }
    }
 
    // Merge user-provided environment (overrides base)
    return { ...base, ...(userEnv || {}) };
  }
 
  /**
   * Resolve the best available shell.
   */
  private async resolveShell(): Promise<string> {
    // Prefer bash, fall back to zsh, then sh
    for (const shell of ['/bin/bash', '/bin/zsh', '/bin/sh']) {
      try {
        await fs.access(shell);
        return shell;
      } catch {
        continue;
      }
    }
    return '/bin/sh';
  }
 
  /**
   * Check if a supported shell is available.
   */
  private async checkShellAvailable(): Promise<boolean> {
    for (const shell of ['/bin/bash', '/bin/zsh', '/bin/sh']) {
      try {
        await fs.access(shell);
        return true;
      } catch {
        continue;
      }
    }
    return false;
  }
 
  /**
   * Collect artifacts matching glob-like patterns from the workDir.
   * Walks the directory tree and matches files against the patterns.
   * Patterns can include ** for recursive matching and * for single-segment matching.
   */
  private async collectArtifacts(
    workDir: string,
    patterns: string[]
  ): Promise<string[]> {
    if (patterns.length === 0) {
      return [];
    }
 
    const allFiles = await this.walkDirectory(workDir);
    const matched: string[] = [];
 
    for (const filePath of allFiles) {
      // Get path relative to workDir
      const relativePath = filePath.substring(workDir.length + 1);
 
      for (const pattern of patterns) {
        if (this.matchPattern(relativePath, pattern)) {
          matched.push(filePath);
          break; // Don't add same file twice
        }
      }
    }
 
    return matched;
  }
 
  /**
   * Recursively walk a directory and return all file paths.
   */
  private async walkDirectory(dir: string): Promise<string[]> {
    const files: string[] = [];
 
    try {
      const entries = await fs.readdir(dir, { withFileTypes: true });
      for (const entry of entries) {
        const fullPath = join(dir, entry.name);
        if (entry.isDirectory()) {
          const subFiles = await this.walkDirectory(fullPath);
          files.push(...subFiles);
        } else {
          files.push(fullPath);
        }
      }
    } catch {
      // Directory doesn't exist or isn't readable
    }
 
    return files;
  }
 
  /**
   * Simple glob-like pattern matching.
   * Supports * (any segment chars) and ** (any path depth).
   */
  private matchPattern(filePath: string, pattern: string): boolean {
    // Convert glob to regex
    const regexStr = pattern
      .replace(/\./g, '\\.')
      .replace(/\*\*/g, '{{GLOBSTAR}}')
      .replace(/\*/g, '[^/]*')
      .replace(/\{\{GLOBSTAR\}\}/g, '.*');
 
    const regex = new RegExp(`^${regexStr}$`);
    return regex.test(filePath);
  }
}