Skip to content

Open-Source Readiness Remediation Plan

This plan addresses the security, maintainability, modularity, test reliability, and release-engineering issues identified during the StackPilot readiness review. It is deliberately divided into small, independently testable tasks so local LLM coding agents can execute it safely on a machine with an RTX 3060 and 12 GB of VRAM.

Execution Principles

Use a coordinator agent plus short-lived implementation and review agents:

Role Responsibility Context provided
Coordinator Tracks dependencies, assigns tasks, and accepts changes Plan, architecture summary, status, and latest diffs
Implementer Makes one bounded change Relevant AGENTS.md, task, invariants, and 3–6 files
Test agent Adds or adjusts tests independently Changed code and adjacent tests
Review agent Searches for regressions and security gaps Final diff, invariants, and test results

For a 12 GB GPU, prefer a quantized 7B–14B coding model with a 16K–32K context. Do not load the entire repository into every prompt. Give each agent:

  1. One narrowly scoped objective.
  2. The applicable AGENTS.md instructions.
  3. The exact files it may change.
  4. Behavioral and security invariants.
  5. Exact validation commands.
  6. The current diff rather than unrelated source files.

Agents must not commit, push, create branches, or delete files unless explicitly authorized. Any eventual commit must use Conventional Commits, include the executing model identity, and receive explicit user approval.

Phase 0: Establish a Reliable Baseline

0.1 Preserve the current worktree

The existing modification to src/hub/public/css/style.css belongs to the user and must remain untouched.

Record the starting state:

git status --short
git diff --stat
git diff -- src/hub/public/css/style.css
git rev-parse HEAD

Do not stash, reset, restore, or overwrite unrelated changes.

0.2 Synchronize before creating a remediation branch

Follow the repository branching policy:

git fetch origin
git checkout main
git pull --ff-only origin main
git branch --merged main

Before removing a stale branch, verify that it contains no unique commits. Create the remediation branch only from the updated main branch:

git checkout -b security/open-source-readiness

0.3 Define supported development platforms

Document two categories:

  • Release-blocking: Ubuntu/Linux CI, supported Python versions, and supported Node.js versions.
  • Developer convenience: Windows test compatibility where practical.

Do not weaken Linux tests merely to make Windows pass.

0.4 Capture baseline results correctly

Run Hub commands from the Hub directory because its build scripts use relative paths:

Set-Location src/hub
npm run check
npm test
Set-Location ../agent
python -m pytest tests -q

On Linux or WSL, also run:

npm --prefix src/hub run check
npm --prefix src/hub test
pytest src/agent/tests -q

Classify every failure as one of:

  • Product defect.
  • Test isolation defect.
  • Unsupported-platform behavior.
  • Sandbox or environment limitation.

Exit criterion: A written baseline records the commands, platform, tool versions, failures, and pre-existing worktree changes.

Phase 1: Make the Agent Fail Closed Without TLS

This is the highest-priority security change. The relevant startup flow is in src/agent/stackpilot_agent.py.

1.1 Define the transport invariant

The invariant is:

A remotely reachable StackPilot agent must never start without TLS.

Adopt these rules:

  • Certificate generation failure terminates startup.
  • Missing or unreadable certificate/key material terminates startup.
  • Plain HTTP is allowed only through an explicit development-only setting.
  • Development HTTP binds only to 127.0.0.1.
  • Production defaults to TLS and a configurable management interface.

Use explicit settings rather than overloading existing ones:

STACKPILOT_AGENT_BIND=0.0.0.0
STACKPILOT_AGENT_ALLOW_INSECURE_HTTP=false

1.2 Add failing tests first

Add tests for:

  1. Existing valid certificate starts TLS.
  2. Missing certificate triggers generation.
  3. Certificate generation failure exits without opening a socket.
  4. A missing key does not trigger an HTTP fallback.
  5. Insecure HTTP is rejected unless explicitly enabled.
  6. Explicit insecure HTTP binds only to loopback.
  7. Invalid bind addresses are rejected.

Mock socket creation so unit tests never open public ports.

1.3 Implement fail-closed startup

Extract certificate preparation into a small function that either returns validated certificate paths or raises a specific exception.

Ensure:

  • The certificate directory has private permissions.
  • The private key is mode 0600.
  • Existing certificate files are readable.
  • Certificate and private key material are validated together.
  • Exceptions never continue into plaintext mode.
  • Logs never contain key material or tokens.

1.4 Update service templates and installation behavior

Update all agent service templates and their snapshots to set secure defaults explicitly:

  • User service.
  • System service.
  • Self-heal scripts and services.
  • Generated installation script.

A local health check may use curl -k against 127.0.0.1 to query an already installed self-signed agent. That exception must never be reused for executable downloads, policy downloads, or enrollment requests.

1.5 Validate

pytest src/agent/tests/api/test_security.py -q
pytest src/agent/tests/api/test_handler.py -q
pytest src/agent/tests -q
npm --prefix src/hub test

Perform a Linux integration test:

  1. Start with valid certificates and confirm HTTPS responds.
  2. Remove or invalidate the key.
  3. Confirm startup fails.
  4. Confirm port 9091 does not serve HTTP.

Exit criterion: No normal execution path exposes the agent API over plaintext HTTP.

Phase 2: Remove Installer TLS-Verification Bypass

The unsafe fallback is generated by src/hub/lib/agent-source.js.

2.1 Define secure enrollment modes

Support only:

  1. HTTPS with an embedded or pinned Hub certificate.
  2. HTTPS using the operating-system trust store.
  3. Explicit local-development HTTP on loopback, if required.

Do not support HTTPS with curl -k, disabled hostname checking, or an unverified Python SSL context.

2.2 Add regression tests

Update source-generation and installer snapshot tests to assert:

  • Generated remote installers never contain curl -k.
  • Generated installers never set verify_mode to CERT_NONE.
  • Generated installers never disable hostname checking.
  • Enrollment requests use verified HTTPS.
  • Missing certificate material produces an actionable error.
  • HTTP deployment is rejected for non-loopback hosts.

2.3 Replace fallback behavior

In src/hub/lib/agent-source.js:

  • Remove the backward-compatible skip-verification branch.
  • Require readable Hub certificate material when certificate pinning is selected.
  • Permit system trust only as an explicit, documented mode.
  • Fail before generating an installation command if trust cannot be established.
  • Ensure enrollment secrets never appear in logs.

2.4 Reduce shell-pipeline risk

Replace direct download-to-shell behavior with:

  1. Create a secure temporary file.
  2. Download the installer using verified TLS.
  3. Verify a supplied SHA-256 digest where available.
  4. Execute the verified local file with Bash.
  5. Remove the temporary file.

Avoid embedding enrollment tokens in shell history where practical. Prefer a protected environment variable or temporary credential file.

2.5 Validate

npm --prefix src/hub run check
npm --prefix src/hub test
pytest src/agent/tests/api/test_security.py -q

Test installation against an untrusted certificate. It must fail before downloading the agent.

Exit criterion: No generated installer or enrollment request bypasses certificate validation.

Phase 3: Harden Agent Authentication and Network Exposure

3.1 Add bounded authentication rate limiting

The constant-time token comparison in stackpilot_agent_modules/handler.py is a good foundation. Add an in-memory limiter keyed by source address:

  • Use a short failure window.
  • Bound the number of stored entries.
  • Expire entries automatically.
  • Never log token values.
  • Clear or reduce penalties after successful authentication.
  • Preserve normal Hub health polling.

3.2 Restrict sensitive error information

Review Hub and agent errors so production responses do not expose:

  • Local filesystem paths.
  • Full command lines.
  • Environment values.
  • Tokens or secrets.
  • Sensitive subprocess output.

Keep detailed diagnostics in protected local logs. Return uniform authentication errors and generic production errors.

3.3 Add agent response headers

Add at least:

  • X-Content-Type-Options: nosniff.
  • Cache-Control: no-store for sensitive responses.
  • Strict JSON content types.
  • No permissive CORS headers.

3.4 Review terminal authorization

The Hub currently allows operators to open interactive container terminals. Make this an explicit policy decision.

Recommended design:

  • Default terminal access to administrators.
  • If operators require access, define a separate terminal.execute permission.
  • Add session lifetime and inactivity limits.
  • Cap terminal input size and output buffering.
  • Tie sessions to the initiating user, host, and container.
  • Audit start, close, timeout, and abnormal termination events.

Exit criterion: Brute-force exposure is bounded, sensitive errors are sanitized, and terminal access has a documented permission model.

Phase 4: Correct Forward-Authentication Semantics

The documentation describes trusted CIDRs, while the current middleware performs exact address matching.

4.1 Select one supported contract

Choose one:

  • Implement tested IPv4 and IPv6 CIDR matching using a small maintained dependency.
  • Document that only exact trusted proxy addresses are supported.

Implementation decision: support exact IPv4 and IPv6 socket-peer addresses plus the localhost loopback alias. Reject CIDRs, arbitrary hostnames, and address-plus-port values during startup validation.

Do not implement ad hoc CIDR parsing without comprehensive tests.

4.2 Test trust boundaries

Add tests proving:

  • Identity headers from an untrusted socket are ignored.
  • Spoofed X-Forwarded-For cannot establish trust.
  • Exact trusted addresses work.
  • IPv4-mapped IPv6 addresses normalize correctly.
  • Empty socket addresses are never implicitly trusted.
  • Multiple proxy hops have defined behavior.
  • CIDR boundaries work correctly if CIDRs are implemented.

4.3 Align documentation and configuration validation

Fail startup when forward-auth configuration is incomplete or ambiguous. Update the security policy, forward-auth guide, configuration examples, and threat model to describe the implemented behavior exactly.

Exit criterion: Code, examples, and security claims share the same proxy trust model.

Phase 5: Repair Test Isolation and Platform Behavior

Several tests currently escape temporary directories and attempt to access real user locations on Windows.

5.1 Remove configuration initialization from imports

stackpilot_agent_modules/config_state.py currently initializes global configuration during import. Replace it with one of:

  • Lazy initialization.
  • An explicit initialize_config() call.
  • An injected configuration service.

The smallest initial change is lazy initialization with a reset helper used only by tests.

5.2 Centralize filesystem dependencies

Create a small path/configuration context containing:

  • User home.
  • StackPilot home.
  • Agent executable path.
  • Configuration path.
  • Systemd directory.
  • Backup directory.
  • Certificate directory.

Production builds the context from environment variables and defaults. Tests build it entirely below tmp_path.

5.3 Fix tests without weakening assertions

For each failing test:

  1. Identify the unpatched path dependency.
  2. Inject or monkeypatch it before importing the target module.
  3. Ensure it never writes below the real user profile.
  4. Ensure it never writes beside the Python or pytest executable.
  5. Add a guard fixture that fails when a test writes outside its temporary root.

Mark a test Linux-only only when it genuinely requires Linux facilities.

5.4 Detect order-dependent tests

Run the suite at least three times:

python -m pytest src/agent/tests -q
python -m pytest src/agent/tests -q
python -m pytest src/agent/tests -q

Add a randomized-order CI job if practical.

Exit criterion: Tests do not access real user directories, Linux CI is green, and supported Windows tests are deterministic.

Phase 6: Decompose the Agent Incrementally

Start this phase only after the security fixes and baseline tests are green. Do not mix broad refactoring with transport-security changes.

6.1 Remove wildcard legacy imports

Replace the wildcard import in src/agent/stackpilot_agent.py:

  1. Find every referenced legacy symbol.
  2. Import only those symbols explicitly.
  3. Run the complete agent test suite.
  4. Move one logical symbol group at a time from legacy.py.
  5. Remove symbols only after all references are gone.

6.2 Split handler responsibilities

Extract responsibilities from stackpilot_agent_modules/handler.py in this order:

  1. Request parsing and response helpers.
  2. Authentication and rate limiting.
  3. Background-task registry.
  4. Subprocess execution abstraction.
  5. Route registration and dispatch.
  6. Filesystem cleanup service.
  7. Backup and rollback service.

Each extraction must preserve public method names initially, retain compatibility wrappers where needed, and include focused tests.

6.3 Introduce narrow service interfaces

Prefer simple objects or constructor arguments rather than a dependency-injection framework:

CommandRunner
PathPolicy
ConfigRepository
TaskRegistry
ContainerRuntime
BackupService
TerminalService

6.4 Adopt maintainability limits

  • New modules should preferably remain below 500 lines.
  • Functions should preferably remain below 60 lines.
  • Route handlers coordinate services rather than execute subprocess logic.
  • Do not add wildcard imports.
  • Do not perform filesystem writes during import.
  • Keep direct subprocess calls in the command-execution layer.

Exit criterion: The central handler becomes primarily a dispatcher and composition layer without changing behavior.

Phase 7: Reduce Hub and Mock-Server Drift

7.1 Inventory duplicated behavior

Compare production and mock implementations for:

  • Routes.
  • Validation.
  • Response transformations.
  • Update-risk calculations.
  • Filtering.
  • Authorization assumptions.

Create a parity table before changing code.

7.2 Extract pure shared logic

Share only environment-independent behavior:

  • Input validation.
  • Request and response schemas.
  • Filtering and normalization.
  • Risk calculations.
  • Route constants.

Do not import the production Express application into the mock server.

7.3 Add contract tests

Run representative request/response fixtures against production route logic with mocked services and against the mock-server logic. Verify status codes, required fields, and authorization behavior without matching volatile timestamps.

7.4 Enforce parity in CI

Fail CI when:

  • A required production route is absent from the mock server.
  • A shared response field diverges.
  • A mutating route lacks CSRF or role middleware.
  • A route lacks an audit identifier.

Exit criterion: Mock parity is enforced by tests instead of policy alone.

Implementation status: production route registrations and actual mock path branches are compared by tests/route-parity.test.js. The suite rejects missing or stale mock coverage, unreasoned exclusions, protected mutations without CSRF and role middleware, mutations without audit identifiers, and duplicate audit identifiers. The mock now covers configuration dry-run validation; narrow exclusions document first-use setup and agent distribution or certificate-enrollment flows that are intentionally not emulated.

Phase 8: Harden CI and Release Workflows

8.1 Pin GitHub Actions

Replace mutable action tags with full commit SHAs in:

  • .github/workflows/ci.yml.
  • .github/workflows/docs.yml.
  • .github/workflows/release.yml.

Add comments identifying the corresponding action release. Configure Dependabot or Renovate to propose future SHA updates.

8.2 Apply least-privilege permissions

Use a read-only workflow default:

permissions:
  contents: read

Grant elevated permissions only to the jobs that need them:

  • Version/tag job: contents: write.
  • Package publication: packages: write.
  • Documentation deployment: only the permissions required for Pages or the selected deployment method.

Test jobs must not receive write tokens.

8.3 Add release concurrency protection

Prevent overlapping releases:

concurrency:
  group: stackpilot-release
  cancel-in-progress: false

8.4 Validate release inputs

For manual releases:

  • Require a strict semantic version.
  • Confirm the tag matches all project manifests.
  • Reject an existing tag.
  • Reject a version below the latest release.
  • Confirm the selected commit is intended for release.

8.5 Require complete release gates

Direct tag and manual releases must run:

  • Hub syntax and vendor build.
  • Hub tests.
  • Agent tests.
  • Strict documentation build.
  • Container build.
  • Version consistency.
  • Security scans.

Do not allow manually pushed tags to bypass validation.

Implementation status: workflow actions are pinned to immutable SHAs and tracked by Dependabot; workflows default to read-only permissions; release jobs use scoped write permissions and a non-cancelling concurrency lock; manual and direct-tag releases validate semantic versions, manifests, tag state, and commit identity; and all existing build/test/documentation/container gates run before publication. The security-scan gate is added in Phase 9.

Exit criterion: Only fully tested commits publish artifacts, test jobs are read-only, and workflow dependencies are immutable.

Phase 9: Add Automated Security Scanning

Introduce scanners one at a time, triage their output, and only then make high-confidence rules blocking.

9.1 Secret scanning

Use Gitleaks or an equivalent scanner to inspect current content and Git history. Add only narrow, documented allowlist entries. Never suppress broad file types.

9.2 Dependency scanning

For Node.js:

npm --prefix src/hub audit --omit=dev
npm audit --omit=dev

Scan the root and Hub lockfiles independently. Add dependency update automation for Node, Python, and GitHub Actions.

9.3 Static analysis

Add:

  • CodeQL for JavaScript and Python.
  • ShellCheck for release and installer scripts.
  • Ruff or another lightweight Python checker.
  • A focused ESLint configuration if needed, without a repository-wide formatting rewrite.

9.4 Container scanning

Scan the final image using Trivy or Grype. Block known critical/high vulnerabilities when a fix exists. Any exception must have an owner, reason, and expiration date.

9.5 Generate SBOMs

Create SPDX or CycloneDX SBOMs for:

  • Hub container images.
  • Release archives.
  • Agent zipapp contents.

Attach them to releases.

Exit criterion: Pull requests and releases scan secrets, source, dependencies, shell scripts, and final container images.

Implementation status: a dedicated security workflow scans Git history with Gitleaks, audits both Node lockfiles, runs focused ShellCheck and Ruff rules, analyzes JavaScript and Python with CodeQL, blocks fixed high/critical container vulnerabilities with Trivy, and generates SPDX SBOM artifacts. Release publication repeats the blocking secret, dependency, shell, Python, and image checks and attaches container, agent, and release-archive SBOMs. Dependabot tracks root npm, Hub npm, agent Python, and GitHub Actions dependencies. All JavaScript-based actions use Node 24-compatible releases pinned to immutable commits.

Phase 10: Sign and Attest Releases

10.1 Sign container images

Use keyless Sigstore/cosign with GitHub OIDC. Publish:

  • Image signatures.
  • Build-provenance attestations.
  • SBOM attestations.

Document verification commands.

10.2 Sign downloadable artifacts

Continue publishing SHA-256 files, and also:

  • Sign release files with cosign blobs or another maintained system.
  • Publish signatures and certificates alongside artifacts.
  • Sign SHA256SUMS.txt.

10.3 Publish provenance

Use GitHub artifact attestations or SLSA provenance recording the repository, commit, workflow, builder, inputs, and produced digest.

10.4 Verify during installation

Where practical, the standalone installer verifies:

  1. Artifact digest.
  2. Signature or attestation.
  3. Expected publisher identity.

Do not silently continue when verification tooling is unavailable. Provide a documented manual verification path.

Exit criterion: Users can verify that images and downloadable artifacts were produced by the official StackPilot workflow.

Implementation status: the release workflow keylessly signs image digests and downloadable artifacts with GitHub OIDC, publishes SLSA provenance and SPDX SBOM attestations, and attaches Sigstore bundles. The fail-closed cross-platform verifier checks both SHA-256 and the official release workflow identity on protected main or a version tag. Verification commands are documented for files and OCI images.

Phase 11: Correct Public Documentation and Governance

11.1 Establish a real security contact

Replace security@stackpilot.local with a monitored security email and/or GitHub private vulnerability reporting. Verify the channel before publishing it.

11.2 Make security claims testable

Compare each security claim with implementation and tests:

  • TLS behavior.
  • Certificate pinning.
  • Forward-auth proxy handling.
  • Path jailing.
  • Secret masking.
  • Token rotation.
  • RBAC permissions.
  • Terminal access.
  • Docker privilege implications.

Avoid absolute claims when exceptions exist.

11.3 Update stale version examples

Replace hard-coded old versions such as 0.9.8 with <version> placeholders or values maintained by release automation. Verify artifact names and repository ownership in all quickstart commands.

11.4 Add standard open-source project files

Create or confirm:

  • CONTRIBUTING.md.
  • CODE_OF_CONDUCT.md.
  • Issue templates.
  • Pull-request template.
  • Support policy.
  • Compatibility matrix.
  • Deprecation policy.
  • Release process.
  • Maintainer and reviewer expectations.
  • DCO or CLA decision.
  • Plain-language AGPL network-use guidance.

11.5 Clarify Docker security

State clearly that Docker-group membership or Docker socket access is effectively root-equivalent on typical hosts. Explain the security differences between:

  • Rootless Podman mode.
  • Docker mode.
  • System-scoped agents.
  • User-scoped agents.

Exit criterion: A new user can install, verify, operate, update, and report vulnerabilities without relying on undocumented knowledge.

Implementation status: public guidance now uses current placeholders and qualified security language; private GitHub advisories replace the placeholder email. Contribution, conduct, support, compatibility, deprecation, release, maintainer, DCO, AGPL network-use, issue, and pull-request guidance is present. Docker's root-equivalent trust boundary and supported deployment differences are explicit.

Phase 12: Final Release Qualification

12.1 Run the complete validation matrix

npm --prefix src/hub run check
npm --prefix src/hub test
pytest src/agent/tests -q
mkdocs build --strict
python src/release/check-version.py "$(cat src/release/VERSION)" .

Also build and verify:

  • Containerfile on amd64.
  • Containerfile on arm64.
  • Standalone .run package.
  • Agent zipapp.
  • Documentation site.

12.2 Test fresh installation and upgrade

Use disposable Linux VMs. Never run destructive lifecycle tests against a real home-server host.

Test:

  1. Fresh rootless Podman installation.
  2. Fresh Docker installation.
  3. Hub installation.
  4. Local-agent installation.
  5. Remote-agent enrollment.
  6. Certificate mismatch rejection.
  7. Failed certificate generation.
  8. Upgrade from the previous stable version.
  9. Uninstall without purge.
  10. Uninstall with purge.
  11. Backup and rollback.
  12. Terminal authorization.
  13. Forward-auth deployment.

12.3 Perform negative security tests

Verify:

  • Invalid tokens fail.
  • Expired enrollment tokens fail.
  • Enrollment tokens cannot be reused.
  • Agent certificates cannot be silently replaced.
  • Path traversal fails through symlinks and encoded paths.
  • Notification URL validation rejects internal destinations.
  • CSRF-free mutations fail.
  • Viewer and operator privilege escalation fails.
  • Direct forward-auth header spoofing fails.
  • Oversized request bodies fail safely.
  • Terminal sessions expire.

12.4 Review the final diff independently

Give a review agent only the baseline commit, final diff, threat model, test results, and known exceptions. Ask it to identify:

  • Changed defaults.
  • Compatibility breaks.
  • Secrets in logs.
  • New subprocess paths.
  • New network listeners.
  • Missing authorization middleware.
  • Installer trust regressions.
  • Documentation and implementation contradictions.

12.5 Publish a release candidate

Publish a prerelease such as v0.23.0-rc.1. Run it on non-production hosts for several days, exercising restarts, reconnects, updates, backups, notifications, terminal sessions, forward authentication, and certificate enrollment.

Promote the exact tested commit and artifacts. Do not rebuild different artifacts for the stable release.

Implementation status: scripts/qualify_release.py provides quick and full fail-fast qualification profiles with optional JSON evidence, and docs/release-qualification.md defines the disposable-VM matrix, negative tests, blocker policy, and release-candidate soak. Physical VM qualification and a public release candidate remain operator sign-off activities for each release rather than repository changes.

Assign each item as a separate job:

  1. Baseline and test classification.
  2. Agent TLS fail-closed tests.
  3. Agent TLS fail-closed implementation.
  4. Installer TLS-verification tests.
  5. Installer TLS-verification implementation.
  6. Agent rate limiting and error sanitization.
  7. Terminal permission design and tests.
  8. Test filesystem isolation.
  9. Explicit legacy imports.
  10. First handler service extraction.
  11. Hub/mock contract inventory.
  12. Shared contract tests.
  13. Workflow permission hardening.
  14. GitHub Action SHA pinning.
  15. Security scanners.
  16. Release signing and attestations.
  17. Documentation and governance.
  18. Full release qualification.

Each agent must stop after its assigned task, report changed files and test results, and hand its diff to a separate review agent. This keeps prompts and diffs small enough for a 12 GB local model while reducing cross-cutting regressions.

Per-Task Agent Prompt Template

Use this template for each local implementation agent:

Objective:
<one narrow outcome>

Repository rules:
- Read and follow the applicable AGENTS.md files.
- Preserve unrelated worktree changes.
- Do not commit, push, create branches, or delete files.

Files allowed to change:
- <file 1>
- <file 2>
- <test file>

Required invariants:
- <security or compatibility invariant>
- <behavior that must remain unchanged>

Implementation constraints:
- Make the smallest coherent change.
- Do not refactor unrelated code.
- Add or update focused tests first where practical.
- Do not weaken assertions to make tests pass.

Validation:
- <targeted test command>
- <broader test command>

Deliverable:
- Summary of behavior changed.
- Files changed.
- Tests run and exact results.
- Remaining risks or assumptions.