Skip to content

Commit d0ae0f1

Browse files
SteveL-MSFTCopilot
andcommitted
Split code review instructions into area-specific files
Reorganize the monolithic code-review.instructions.md into 11 focused instruction files under .github/instructions/code-review/, each with applyTo patterns targeting the relevant paths: - engine: configure, discovery, resource dispatch, functions, settings - resource: individual resource implementations - adapter: PowerShell/WMI adapter bridge code - extension: extension discovery and lifecycle - cli: command-line interface, subcommands, server mode - tests: Pester and Rust integration tests - library: shared libraries (dsc-lib, jsonschema, osinfo, etc.) - security: ACLs, policy, credentials, elevated resources - performance: allocations, caching, serialization hot paths - windows: FFI, COM, registry, DISM, services - linux: SSH config, apt/brew, platform-specific paths The top-level file now serves as a routing table mapping paths to areas, plus universal guidance (false-positive avoidance, documentation, CI/CD). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent a59d9c9 commit d0ae0f1

12 files changed

Lines changed: 421 additions & 151 deletions

.github/instructions/code-review.instructions.md

Lines changed: 36 additions & 151 deletions
Large diffs are not rendered by default.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
applyTo: 'adapters/**'
3+
description: 'Code review guidance for DSC adapters (PowerShell, WMI, etc.)'
4+
---
5+
6+
# Adapter Code Review
7+
8+
Adapters bridge DSC to external resource ecosystems (PowerShell DSC v1/v2 resources, WMI, etc.).
9+
They run PowerShell runspaces, manage module loading, and translate between DSC and native formats.
10+
11+
## Module Import Safety
12+
13+
- **Module import can return arrays**: `Get-Module` can return multiple `PSModuleInfo` objects when multiple versions are loaded. Always select a single module (highest version) before calling methods.
14+
- **Error handling around module imports**: Wrap import probes in try/catch so one failing module doesn't abort entire resource enumeration during cache refresh.
15+
- **`$using:` in parallel blocks**: Variables from parent scope are not available inside `ForEach-Object -Parallel`. Use `$using:variableName`.
16+
17+
## Error Handling
18+
19+
- **Distinguish terminating vs non-terminating errors**: Non-terminating errors in `$ps.HadErrors` should not produce non-zero exit. Only terminating errors (exceptions) should cause adapter failure.
20+
- **Use `$_` in catch blocks, not `$error`**: `$error` is the global error collection. Use `$_` (the caught exception) for condition checks.
21+
- **Flush trace queues before exit on all paths**: If a catch/finally path exits the script, drain the trace queue first to avoid losing diagnostic messages.
22+
23+
## Concurrency and Event Handling
24+
25+
- **`ConcurrentQueue` draining**: Do not loop on `.IsEmpty` followed by `TryDequeue`. Use `while queue.TryDequeue(...)` as the single loop condition -- `IsEmpty` is only an approximation.
26+
- **Event subscriber cleanup**: Filter by `-SourceIdentifier`, not blanket `Get-EventSubscriber | Unregister-Event`.
27+
28+
## Secrets and Security
29+
30+
- **Prevent command injection**: Flag code that embeds user-controlled values (secrets, vault names, paths) into PowerShell command strings. Prefer passing arguments/JSON.
31+
- **Never leak secrets into logs**: Verify redaction is applied when logging resource output that may contain secure values.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
applyTo: 'dsc/src/**'
3+
description: 'Code review guidance for DSC CLI (command-line interface, subcommands, server mode)'
4+
---
5+
6+
# CLI Code Review
7+
8+
The `dsc` crate is the main CLI binary. It handles argument parsing, subcommand dispatch,
9+
output formatting (JSON/YAML/table), and the MCP server mode.
10+
11+
## Output Formatting
12+
13+
- **Deterministic output**: JSON format (compact vs pretty) must be consistent regardless of internal state.
14+
- **Table output is not a stable API**: JSON/YAML are canonical. Table changes are not breaking.
15+
- **Extract shared formatting logic**: When table/list formatting appears in multiple subcommands, extract a helper rather than duplicating.
16+
17+
## Error Handling
18+
19+
- **Prefer `Result` over panics**: Avoid `unwrap()`/`expect()` on user input or parsed data. Return clear error messages and exit codes.
20+
- **Names must match semantics**: Flag singular/plural mismatches, stale help text, and deprecated options still visibly advertised.
21+
22+
## Server Mode (MCP)
23+
24+
- **Schema/typing for tool parameters**: Prefer typed parameters over generic `serde_json::Value` with runtime validation. This gives clients correct schemas.
25+
- **Tool name accuracy**: Ensure locale strings and schema descriptions reference the correct tool name (e.g., `list_dsc_functions` not `list_dsc_function`).
26+
27+
## Backward Compatibility
28+
29+
- **CLI flag changes are compatibility events**: Renaming, removing, or changing the semantics of CLI flags requires consideration of existing users and scripts.
30+
- **Breaking test expectations**: If existing tests must change due to CLI behavior changes, that signals a potential breaking change needing discussion.
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
applyTo: 'lib/dsc-lib/src/configure/**,lib/dsc-lib/src/discovery/**,lib/dsc-lib/src/dscresources/**,lib/dsc-lib/src/functions/**,lib/dsc-lib/src/settings/**'
3+
description: 'Code review guidance for DSC engine (configure, discovery, resource dispatch, functions, settings)'
4+
---
5+
6+
# Engine Code Review
7+
8+
The engine is the core of DSC: configuration processing, resource discovery, function evaluation,
9+
schema caching, and settings resolution. Changes here have broad impact.
10+
11+
## Caching
12+
13+
- **Cache key correctness**: Cache keys must account for all dimensions affecting the cached value. For adapter resources with `target_resource`, cache by target identity, not just adapter type/version.
14+
- **Centralize cache logic**: Flag duplicate cache writes or wrapper layers that both cache the same result. A single cache owner reduces redundant work and prevents divergent keying.
15+
- **Avoid JSON serialize/parse roundtrips**: If you already have a `serde_json::Value`, cache or return it directly rather than stringifying and re-parsing.
16+
17+
## Settings Precedence
18+
19+
- **Full precedence chain**: Policy > CommandLine > Environment > Workspace > User > Install. Missing scopes allow bypasses.
20+
- **Resolved fields vs containers**: Each leaf setting should be individually resolvable with source scope tracked.
21+
- **`allow_override` enforcement**: When false (policy-scoped), must prevent override from both env vars and CLI args.
22+
23+
## Discovery
24+
25+
- **Short-circuit redundant work**: Flag loops that keep scanning after all matches are found, or `contains_key` + `insert` patterns where entry APIs would do one pass.
26+
- **Error promotion risk**: Converting previously-ignored errors into hard errors (e.g., `join_paths` failure) can break existing environments. Prefer warnings or graceful degradation unless truly unrecoverable.
27+
28+
## Resource Dispatch Consistency
29+
30+
- **Behavior must be consistent across get/set/test/export**: If a validation, parameter, or output shape applies to one operation, verify it applies to all siblings.
31+
- **Deterministic output**: JSON format (compact vs pretty) must be consistent regardless of cache state.
32+
- **Resource filtering logic**: (1) if resource supports filtering, let it handle it; (2) if not, use engine filtering with INFO message.
33+
34+
## What-If / Dry-Run
35+
36+
- **No side effects during what-if**: Verify no code path before the what-if gate can mutate state. Functions like `ensure_config_exists()` that create/copy files must be gated.
37+
- **Consistent platform enforcement**: If an operation is platform-restricted, what-if mode must enforce the same restriction.
38+
39+
## API Surface
40+
41+
- **Default to private/`pub(crate)`**: New modules, helpers, globals, and cache types should be private or `pub(crate)`. Require a clear external use case before exposing `pub`.
42+
- **Breaking changes to public APIs**: Adding required parameters to public functions is a breaking change. Consider backward-compatible wrappers.
43+
- **Public signature changes are compatibility events**: Adding parameters, changing flags, or exposing new modules should trigger compatibility review.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
applyTo: 'extensions/**,lib/dsc-lib/src/extensions/**'
3+
description: 'Code review guidance for DSC extensions (discovery, lifecycle)'
4+
---
5+
6+
# Extension Code Review
7+
8+
Extensions extend DSC's discovery and resource capabilities. They have their own discovery
9+
protocol and manifest format.
10+
11+
## Discovery Protocol
12+
13+
- **Manifest content handling**: When deserializing discovered manifests, ensure the expected shape (`ImportedManifest` enum with `Resource`/`Extension` variants) matches what extensions actually emit.
14+
- **Unused variables after refactoring**: When switching from reused helpers (e.g., `process_get_args`) to dedicated ones (e.g., `process_discover_args`), remove intermediate variables and imports that are no longer needed.
15+
- **Doc comments must match parameter semantics**: If a doc comment says "file path" but the parameter actually receives an argument name or extension list, update the comment.
16+
17+
## Schema Updates
18+
19+
- **Update JSON schemas when adding protocol fields**: New fields in extension stdout or args (e.g., `manifestContent`, `extensionsArg`) must be reflected in the checked-in JSON schemas under `schemas/`.
20+
21+
## PowerShell Extensions
22+
23+
- **`$using:` in parallel blocks**: Variables from parent scope are not available inside `ForEach-Object -Parallel`. Use `$using:variableName`.
24+
- **Error isolation**: One extension failing discovery should not abort the entire extension enumeration.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
applyTo: 'lib/**'
3+
description: 'Code review guidance for DSC libraries (dsc-lib, jsonschema, osinfo, pal, registry, security_context)'
4+
---
5+
6+
# Library Code Review
7+
8+
Libraries under `lib/` provide shared functionality consumed by the engine, CLI, and resources.
9+
They define the public API surface of the DSC codebase.
10+
11+
## API Surface and Visibility
12+
13+
- **Default to private/`pub(crate)`**: New modules, helpers, globals, and cache types should be private or `pub(crate)`. Require a clear external use case before `pub`.
14+
- **Breaking changes**: Adding required parameters to public functions is breaking. Consider wrappers or new function names.
15+
- **Remove dead code immediately**: Unused imports, variables, and enums should be deleted -- Rust warnings become CI failures.
16+
- **Extract shared logic into helpers**: Deduplicate common patterns, but don't demand full trait redesigns in focused PRs.
17+
18+
## Error Handling
19+
20+
- **Prefer `Result` over panics for user input**: Return clear `Result` or stable exit codes.
21+
- **Return `Option` for fallible lookups**: Rather than empty strings that resolve to `.`.
22+
- **`unwrap_or_default()` on serialization is a bug**: Surface the error and exit non-zero.
23+
24+
## Serde and Schema
25+
26+
- **Be precise with serde**: Review `rename_all`, `deny_unknown_fields`, `Option` vs default, and wire-format names.
27+
- **Names must match semantics**: Singular/plural, stale doc comments, misleading function names.
28+
- **Schema version catalogs**: `lib/dsc-lib-jsonschema/.versions.json` is auto-generated by build. Do not flag version entries as unintentional.
29+
30+
## Performance
31+
32+
- **Reduce allocations only when semantics stay intact**: Good: repeated `to_lowercase()`, cloning data that can be borrowed. Bad: clone removal that changes ownership semantics.
33+
- **Avoid serialize/parse roundtrips**: If you have a `Value`, don't stringify and re-parse.
34+
- **Short-circuit redundant work**: Use entry APIs instead of `contains_key` + `insert`.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
applyTo: 'resources/apt/**,resources/sshdconfig/**,pal/linux/**,resources/brew/**'
3+
description: 'Code review guidance for Linux/macOS-specific code (SSH, apt, platform abstraction)'
4+
---
5+
6+
# Linux/macOS Code Review
7+
8+
Linux and macOS resources manage SSH configuration, package managers, and platform-specific state.
9+
Cross-platform correctness is a recurring theme since the same test suite runs on all platforms.
10+
11+
## Cross-Platform Path Handling
12+
13+
- **Never hard-code path separators**: Use platform-appropriate path joining. Rust's `PathBuf`/`Path::join` handles this automatically.
14+
- **Platform-conditional logic**: Gate Linux-specific behavior (like `/etc/dsc` permissions) on the correct platform check. Don't assume "not Windows" means "Linux" -- it could be macOS.
15+
16+
## SSH Config Resource
17+
18+
- **Quoting preservation**: Understand what the parser actually preserves vs strips. Comments claiming "retains quoting" when code strips quotes are misleading.
19+
- **Match block handling**: Ensure match/criteria blocks are included in export results and not accidentally filtered out.
20+
- **Repeatable keywords with operators**: Keywords with `+`/`-`/`^` operators have specific semantics about repetition. Operators on non-repeatable keywords are invalid.
21+
22+
## Permission Checks (Linux)
23+
24+
- **Fail closed on stat failures**: If `fs::metadata` fails for `/etc/dsc`, do not proceed as if the folder is trusted.
25+
- **Correct permission checks**: Use PowerShell's `Get-Item` or explicit `$IsLinux` gating rather than GNU-specific `stat -c` (which fails on macOS).
26+
27+
## Package Managers
28+
29+
- **Idempotent operations**: Package install/remove operations should be safe to run repeatedly without error.
30+
- **Version comparison**: OS and package versions don't follow semver. Don't assume semver parsing applies.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
applyTo: '**/*.rs'
3+
description: 'Code review guidance for performance (Rust allocations, caching, serialization)'
4+
---
5+
6+
# Performance Code Review
7+
8+
Performance matters most in the engine hot paths: resource discovery (many manifests),
9+
schema caching, and configuration processing.
10+
11+
## Caching
12+
13+
- **Cache key correctness**: Keys must include all dimensions that affect the value. Adapter schemas vary by `target_resource`.
14+
- **Centralize cache writes**: Duplicate cache mutations lead to inconsistent keying and redundant work.
15+
- **Avoid serialize/parse roundtrips**: Don't stringify a `Value` just to re-parse it.
16+
- **Deterministic output**: Cache hits and misses must produce identical format (compact vs pretty).
17+
18+
## Allocations
19+
20+
- **Reduce allocations only when semantics stay intact**: Flag repeated `to_lowercase()` or cloning owned data that can be borrowed. Do NOT flag clone removal that changes ownership or breaks compilation.
21+
- **Short-circuit redundant work**: Use entry APIs instead of `contains_key` + `insert`. Exit loops early when all matches are found.
22+
- **Avoid cloning before parsing**: Parse first, then return the original owned value.
23+
24+
## Native Interop
25+
26+
- **Resource cleanup as performance issue**: Missing `Drop`/RAII cleanup for handles, DLLs, or `VARIANT`s is both correctness and long-run efficiency problem. Especially in loops (firewall enumeration, registry key iteration).
27+
28+
## False Positives to Avoid
29+
30+
- **Do not flag performance when call order makes it moot**: If `get` always runs before `set`/`test`, redundant validation in later operations doesn't affect real-world performance.
31+
- **Compact vs pretty JSON**: Maintainers have noted "doesn't matter here" for format differences in non-user-facing internal paths. Only flag when the difference is externally observable.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
---
2+
applyTo: 'resources/**'
3+
description: 'Code review guidance for DSC resources (individual resource implementations)'
4+
---
5+
6+
# Resource Code Review
7+
8+
Resources are individual components that manage specific system state (registry, services,
9+
firewall, SSH config, DISM features, etc.). They run as separate executables invoked by the engine.
10+
11+
## Manifest and Schema Coherence
12+
13+
- **Schema must match implementation**: Required properties in schema must be enforced in code and vice versa.
14+
- **Behavior must match manifest metadata**: Versions, `requireSecurityContext`, adapter args, and defaults must reflect what the resource actually does.
15+
- **Schema/manifest version consistency**: When bumping a version in `Cargo.toml`, ensure the corresponding `.dsc.resource.json` manifest is also updated.
16+
- **`noFiltering` semantics**: Export input should be treated as empty when `noFiltering` is declared.
17+
- **Canonical property naming**: Leading underscore (`_`) is only for cross-resource canonical properties. Resource-specific properties use descriptive names (e.g., `sshd_config_filepath`).
18+
19+
## Operation Consistency
20+
21+
- **All operations must validate consistently**: If a parameter is validated in `get`, it should also be validated in `set`, `test`, and `export`.
22+
- **What-if must not mutate state**: Verify no code path before the what-if gate can create files, modify config, or change system state.
23+
- **Consistent platform enforcement in what-if**: Platform-restricted operations must enforce restrictions even in what-if mode.
24+
25+
## Error Handling
26+
27+
- **Prefer `Result` over panics**: Avoid `unwrap()`/`expect()` on user input or manifest data. Return clear error messages and stable exit codes.
28+
- **`unwrap_or_default()` on serialization is a bug**: `serde_json::to_string(...).unwrap_or_default()` silently emits empty string on failure. Surface the error and exit non-zero.
29+
- **Return `Option` for fallible lookups**: Return `Option<PathBuf>` rather than empty string (which resolves to `.`).
30+
31+
## Destructive Operations
32+
33+
- **Watch for unresolvable system objects**: In list-reconciling resources (firewall, services), flag logic that disables/removes system-created entries (AppX/UWP rules) that users cannot reliably reference in their declared state.
34+
- **Semantic versioning**: Resources below 1.0 are not design-stable. Breaking changes to input/output shapes require a minor version bump.
35+
36+
## Regex and Wildcard Handling
37+
38+
- **Escape all metacharacters**: When converting wildcards to regex, escape `[`, `(`, `+`, `^`, `$`, `|`, `\` -- not just `.`. Unescaped metacharacters cause panics or unexpected matching.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
applyTo: 'lib/dsc-lib/src/util.rs,lib/dsc-lib-security_context/**,lib/dsc-lib-registry/**,resources/registry/**,resources/windows_firewall/**,resources/windows_service/**,resources/dism_dsc/**'
3+
description: 'Code review guidance for security-sensitive code (ACLs, policy, credentials, elevated resources)'
4+
---
5+
6+
# Security Code Review
7+
8+
This repo manages system configuration. Many resources run elevated and modify security-sensitive
9+
state (ACLs, registry, services, firewall rules, policy files). Security review is critical.
10+
11+
## Fail Closed
12+
13+
- **All security checks must fail closed**: If reading a security descriptor, enumerating ACEs, or calling stat fails, return the restrictive/denied result -- never fail open.
14+
- **NULL DACL detection**: A NULL DACL means full access to everyone. Treat `p_dacl.is_null()` as insecure.
15+
- **Do not cache or trust failed verifications**: Trust caches (Authenticode, ACL checks) should only be updated on successful validation.
16+
17+
## ACL and Permission Checks
18+
19+
- **Complete write-access checks**: Cover `GENERIC_WRITE` and `GENERIC_ALL` in addition to specific write flags.
20+
- **Inherit-only ACEs**: ACEs with `INHERIT_ONLY_ACE` flag don't apply to the object itself -- don't treat them as granting access to the folder.
21+
- **Non-standard ACE variants**: Callback ACEs and object ACEs can still grant write access. Don't skip them.
22+
23+
## Policy Bypass Prevention
24+
25+
- **User inputs must not bypass policy**: CLI flags, env vars, or config changes must not override policy-enforced settings. Policy sources remain authoritative.
26+
- **Enforce declared security context**: If manifests declare `requireSecurityContext`, verify runtime enforcement for every operation.
27+
28+
## DLL and Native Code Safety
29+
30+
- **DLL loading security**: Use `LoadLibraryExW` with `LOAD_LIBRARY_SEARCH_SYSTEM32` instead of `LoadLibraryW` to prevent DLL hijacking. Critical for elevated resources.
31+
- **Resource cleanup with `Drop`**: COM objects, `VARIANT`s, and library handles must be cleaned up on all paths including error paths.
32+
- **Check HRESULT returns**: Don't silently ignore Windows API return codes.
33+
34+
## Secrets
35+
36+
- **Never leak secrets into logs or output**: Verify redaction when logging output that may contain secure values.
37+
- **Prevent command injection**: Don't embed user-controlled values into PowerShell command strings. Pass arguments/JSON instead.
38+
39+
## Destructive Operations
40+
41+
- **Unresolvable system objects**: In list-reconciling resources (firewall, services), skip system-created entries (AppX/UWP rules) that users cannot reliably reference.
42+
- **Service credential changes**: Flag service-configuration code that switches accounts without secure credential handling.

0 commit comments

Comments
 (0)