Skip to content

feat: add strict input validation and robust plugin registration - #189

Merged
hustcer merged 1 commit into
developfrom
feature/refactor
Nov 19, 2025
Merged

feat: add strict input validation and robust plugin registration#189
hustcer merged 1 commit into
developfrom
feature/refactor

Conversation

@hustcer

@hustcer hustcer commented Nov 19, 2025

Copy link
Copy Markdown
Owner

feat: add strict input validation and robust plugin registration; improve target selection and caching

  • Validate and normalize features input ('default' | 'full'); narrow type and throw on invalid values
  • Throw on invalid version input (handled by top-level catch) for clearer failures
  • Use GITHUB_WORKSPACE or fallback to current working directory to support local runs
  • Ensure nu commands fail fast: add execOrThrow and apply to register and do-register steps
  • Simplify getTargets by selecting platform map by feature and throw explicit unsupported target errors
  • Cache fallback: when no nu_plugin_* binaries are found, cache extracted dir and emit a warning; keep permission fix
  • Minor logging improvements (current directory, clearer messages)

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced input validation with stricter feature verification and clear error messaging.
    • Improved error handling for shell commands to reliably detect and report failures.
    • Added safeguards for tool caching and target resolution to prevent silent errors.
  • Refactor

    • Simplified command execution logic for consistency across setup processes.

@coderabbitai

coderabbitai Bot commented Nov 19, 2025

Copy link
Copy Markdown

Walkthrough

The PR introduces stricter input validation for features (default/full), replaces GitHub Actions error signaling with exception throwing, refactors shell command execution with a new execOrThrow helper, simplifies conditional branching through map lookups, and improves workspace and cache directory handling.

Changes

Cohort / File(s) Summary
Input Validation & Error Handling
src/index.ts, src/setup.ts
Implements strict case-insensitive validation for features parameter (must be "default" or "full"), throws Error on invalid input instead of defaulting silently; changes version error handling from core.setFailed to exception throwing; adds guard clause in getTargets to throw on undefined targets.
Shell Command Execution Refactoring
src/plugins-tpl.ts, src/plugins.ts
Introduces execOrThrow helper to execute shell commands and throw on non-zero exit codes; consolidates separate legacy/non-legacy command branches into unified registerCommand string construction and single execOrThrow call for both registration and final execution.
Directory & Caching Logic
src/index.ts, src/setup.ts
Adds fallback logic for workspace directory handling (uses GITHUB_WORKSPACE or current directory); refactors cache source computation in checkOrInstallTool to search for nu_plugin_* binaries and cache their directory, or fall back to extraction root with warning if no binaries found.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • execOrThrow helper: Verify implementation handles edge cases (e.g., signal termination, command not found) consistently across both plugin files
  • Cache source computation: Review the binary search and fallback logic in checkOrInstallTool for robustness when no plugins are found
  • Workspace directory fallback: Confirm the fallback to current working directory doesn't introduce unintended side effects in CI environments
  • getTargets validation: Ensure the guard clause properly covers all error scenarios

Possibly related PRs

Poem

🐰 Shell commands now throw with grace,
Input validation finds its place,
Helpers consolidate the way,
Errors caught without delay,
Caching strategies at play!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: strict input validation for features (default/full) and robust plugin registration via execOrThrow helper.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/refactor

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

Copy link
Copy Markdown

Code Analysis

  • Input Validation: Added proper validation for features input with explicit type casting and error handling
  • Error Handling: Improved error propagation by replacing core.setFailed() with throw new Error() for better stack traces
  • Workspace Safety: Added fallback directory handling for local development scenarios
  • Command Execution: Centralized shell command execution with proper error handling in execOrThrow helper
  • Code Refactoring: Simplified conditional logic in getTargets() function with early returns and unified platform mapping
  • Caching Logic: Enhanced caching strategy with fallback to extract directory when no binaries found

Security Review

  • Command Injection Risk: ❗ Direct shell command execution with user inputs (enablePlugins, version) in lines like nu ${script} "'${enablePlugins}'" ${version} could be vulnerable to command injection if inputs are not properly sanitized
  • Path Traversal: ⚠️ Using process.env.GITHUB_WORKSPACE without validation could allow directory traversal attacks in certain contexts
  • Error Information Leakage: Error messages expose internal paths and command details that could aid attackers

Optimization Suggestions

  • Input Sanitization: Implement input validation and sanitization for shell command parameters using libraries like shell-escape
  • Error Handling: Create custom error types with sanitized messages for production environments
  • Caching Strategy: Consider implementing cache validation to prevent stale cache usage
  • Type Safety: Add runtime type validation for environment variables and inputs beyond TypeScript compilation

Overall Quality: 3

Note: While the code improvements show good architectural patterns and error handling, security concerns around command injection and path handling prevent a higher rating. The refactoring demonstrates solid TypeScript practices but requires additional security hardening.

@hustcer
hustcer changed the base branch from main to develop November 19, 2025 14:41
@hustcer
hustcer merged commit 4807a5a into develop Nov 19, 2025
9 of 10 checks passed
@hustcer
hustcer deleted the feature/refactor branch November 19, 2025 14:41
@github-actions github-actions Bot added this to the v3.22 milestone Nov 19, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/plugins.ts (1)

78-83: Consistent execOrThrow usage with the template; optional DRY opportunity

Mirroring the execOrThrow + registerCommand pattern from src/plugins-tpl.ts keeps the runtime implementation aligned with the template and ensures plugin registration failures are surfaced uniformly. If you find these helpers evolve further, consider extracting a small shared utility to avoid the two copies drifting over time, but it’s perfectly fine as-is.

Also applies to: 91-94, 99-99

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 93cada9 and 9385b16.

⛔ Files ignored due to path filters (1)
  • dist/index.js is excluded by !**/dist/**
📒 Files selected for processing (4)
  • src/index.ts (2 hunks)
  • src/plugins-tpl.ts (1 hunks)
  • src/plugins.ts (1 hunks)
  • src/setup.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
src/setup.ts (1)
dist/index.js (14)
  • PLATFORM_DEFAULT_MAP (57659-57668)
  • PLATFORM_FULL_MAP (57669-57678)
  • path (150-150)
  • path (641-641)
  • path (1266-1266)
  • path (2739-2739)
  • path (2928-2928)
  • path (3473-3473)
  • path (57654-57654)
  • core (3373-3373)
  • core (3467-3467)
  • core (57417-57417)
  • core (57655-57655)
  • tc (57656-57656)
src/plugins.ts (1)
dist/index.js (1)
  • pluginRegisterScript (57491-57553)
src/plugins-tpl.ts (1)
dist/index.js (1)
  • pluginRegisterScript (57491-57553)
🔇 Additional comments (5)
src/plugins-tpl.ts (1)

18-23: execOrThrow-based registration flow looks sound

Centralizing shell command handling via execOrThrow and driving both the register-plugins.nu and do-register.nu invocations through it makes failures explicit and keeps the registration logic straightforward. No issues spotted with the legacy flag handling or argument construction here.

Also applies to: 31-34, 39-39

src/setup.ts (2)

55-60: Explicit target resolution + error is a nice tightening

Selecting the platform map from features and throwing when no targets exist for selector makes failures much clearer than quietly returning undefined. The assertion cast to Platform is safely backed by the runtime guard.


305-310: Graceful cache fallback when no nu_plugin_ binaries are found*

Using extractDir as cacheSource when paths is empty and emitting a warning avoids the previous potential crash on paths[0] while still caching a usable directory. This should make odd/changed archive layouts more robust without affecting the common case.

src/index.ts (2)

19-23: Stricter input validation for features and version is appropriate

Constraining features to 'default' | 'full' and throwing on invalid values, plus throwing when semver.coerce/valid can’t produce a version, makes misconfiguration fail fast and keeps downstream code simpler. This also aligns well with the typed features in Tool.

Also applies to: 29-29


46-48: Workspace directory fallback improves local run behavior

Deriving workspaceDir from GITHUB_WORKSPACE with a fallback to process.cwd() is a sensible improvement over assuming the env var is always set. The cd then applies cleanly to both CI and local use cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant