Skip to content

Fix: prevent global environment pollution in multi-site ls check#2174

Open
Dana-Johnson wants to merge 1 commit into
TryGhost:mainfrom
Dana-Johnson:fix-env-pollution
Open

Fix: prevent global environment pollution in multi-site ls check#2174
Dana-Johnson wants to merge 1 commit into
TryGhost:mainfrom
Dana-Johnson:fix-env-pollution

Conversation

@Dana-Johnson

Copy link
Copy Markdown

The Issue:
In environments managing multiple Ghost instances, the ghost ls command misreports the environment mode of running production instances if a preceding instance in the registry is stopped.

Root Cause Analysis:

  1. State Pollution: During the isRunning() check for a stopped site, the envIsRunning helper is called to probe for a development process. This calls this.system.setEnvironment(true), which globally mutates the singleton System object without restoring it.
  2. Race Condition: Because ghost ls evaluates all instances concurrently using Promise.all(), a stopped site can temporarily flip the global this.system.environment variable in the exact microsecond a running site evaluates its summary().

The Fix:

  • Modified envIsRunning in lib/instance.js to save and restore the global environment state before and after the probe.
  • Modified summary() in lib/instance.js to prioritize reading the local instance configuration (this._cliConfig.get('running')) rather than relying exclusively on the thread-unsafe global this.system.environment.

@coderabbitai

coderabbitai Bot commented May 17, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

This PR modifies environment state tracking within the Instance class. The isRunning() method now saves the current system environment before checking if a process is running in a target environment, persists the running state to CLI config when applicable, and restores the original environment before returning—ensuring cleanup even on early exit paths. The summary() method updates its mode field to use the CLI-tracked running environment when present, falling back to this.system.environment otherwise, enabling the instance to report the tracked running state instead of always reporting the system environment.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix: prevent global environment pollution in multi-site ls check' clearly and concisely describes the main change: fixing a global environment pollution issue in the multi-site ls command.
Description check ✅ Passed The description provides detailed context about the issue, root cause analysis, and the fixes applied, all directly related to the changeset in lib/instance.js.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/instance.js`:
- Around line 210-222: The environment is not restored if
this.process.isRunning(this.dir) throws in envIsRunning; refactor env switch to:
capture originalEnv, set the desired environment, declare let running = false,
then call running = await this.process.isRunning(this.dir) inside a try block
(and inside the try update this._cliConfig.set('running', environment).save()
when running is truthy), and in a finally block always call
this.system.setEnvironment(originalEnv === 'development') to restore global
state before returning running.
- Around line 395-398: The summary() method currently mixes environments: it
sets mode from this._cliConfig.get('running') || this.system.environment but
then reads url/port/process from the mutable global config, which can cause
inconsistent results under concurrent "ghost ls" calls; fix by capturing the
tracked environment into a local variable (e.g. const trackedEnv =
this._cliConfig.get('running') || this.system.environment) immediately before
reading the other fields, and then use that trackedEnv to obtain
environment-scoped values for url, port and process (either via an
environment-specific config accessor or by reloading the config for trackedEnv)
so all returned fields (mode, url, port, process) are derived from the same
environment inside summary().
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9ff26299-b655-4949-ab84-b9834facbab5

📥 Commits

Reviewing files that changed from the base of the PR and between 6d5b9db and 9074914.

📒 Files selected for processing (1)
  • lib/instance.js

Comment thread lib/instance.js
Comment on lines +210 to 222
// 1. Save original environment state
const originalEnv = this.system.environment;

this.system.setEnvironment(environment === 'development');
const running = await this.process.isRunning(this.dir);
if (running) {
this._cliConfig.set('running', environment).save();
}

// 2. Restore original environment state
this.system.setEnvironment(originalEnv === 'development');

return running;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Ensure environment restoration on exceptions in envIsRunning.

At Line 214, if this.process.isRunning(this.dir) throws, Line 220 never runs, leaving global environment mutated. Wrap the switch/restore block in try/finally.

Proposed fix
-                // 1. Save original environment state
-                const originalEnv = this.system.environment;
-
-                this.system.setEnvironment(environment === 'development');
-                const running = await this.process.isRunning(this.dir);
-                if (running) {
-                    this._cliConfig.set('running', environment).save();
-                }
-
-                // 2. Restore original environment state
-                this.system.setEnvironment(originalEnv === 'development');
-
-                return running;
+                const originalEnv = this.system.environment;
+                this.system.setEnvironment(environment === 'development');
+                try {
+                    const running = await this.process.isRunning(this.dir);
+                    if (running) {
+                        this._cliConfig.set('running', environment).save();
+                    }
+                    return running;
+                } finally {
+                    this.system.setEnvironment(originalEnv === 'development');
+                }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/instance.js` around lines 210 - 222, The environment is not restored if
this.process.isRunning(this.dir) throws in envIsRunning; refactor env switch to:
capture originalEnv, set the desired environment, declare let running = false,
then call running = await this.process.isRunning(this.dir) inside a try block
(and inside the try update this._cliConfig.set('running', environment).save()
when running is truthy), and in a finally block always call
this.system.setEnvironment(originalEnv === 'development') to restore global
state before returning running.

Comment thread lib/instance.js
Comment on lines +395 to 398
mode: this._cliConfig.get('running') || this.system.environment,
url: this.config.get('url'),
port: this.config.get('server.port'),
process: this.process.name

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep summary() environment-consistent for all returned fields.

Line 395 fixes mode, but url/port/process still depend on mutable global environment and can mismatch under concurrent ghost ls calls. Re-load the tracked running environment immediately before reading those fields.

Proposed fix
         if (!running) {
             return {
                 name: this.name,
                 dir: this.dir.replace(os.homedir(), '~'),
                 version: this.version,
                 running: false
             };
         }
 
+        this.loadRunningEnvironment();
+
         return {
             name: this.name,
             dir: this.dir.replace(os.homedir(), '~'),
             running: true,
             version: this.version,
             mode: this._cliConfig.get('running') || this.system.environment,
             url: this.config.get('url'),
             port: this.config.get('server.port'),
             process: this.process.name
         };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/instance.js` around lines 395 - 398, The summary() method currently mixes
environments: it sets mode from this._cliConfig.get('running') ||
this.system.environment but then reads url/port/process from the mutable global
config, which can cause inconsistent results under concurrent "ghost ls" calls;
fix by capturing the tracked environment into a local variable (e.g. const
trackedEnv = this._cliConfig.get('running') || this.system.environment)
immediately before reading the other fields, and then use that trackedEnv to
obtain environment-scoped values for url, port and process (either via an
environment-specific config accessor or by reloading the config for trackedEnv)
so all returned fields (mode, url, port, process) are derived from the same
environment inside summary().

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