Skip to content

Validate site slug and site URL in site create and generate commands - #632

Merged
swissspidy merged 4 commits into
mainfrom
fix/special-chars
Aug 3, 2026
Merged

Validate site slug and site URL in site create and generate commands#632
swissspidy merged 4 commits into
mainfrom
fix/special-chars

Conversation

@swissspidy

@swissspidy swissspidy commented Aug 3, 2026

Copy link
Copy Markdown
Member

Applying some slight hardening here

Summary by CodeRabbit

  • New Features

    • Added validation for site slugs during site creation and generation.
    • Valid slugs are normalized to lowercase.
    • Custom site URLs are checked for valid domains, paths, and supported components.
  • Bug Fixes

    • Invalid slugs, domains, paths, and URLs now display clear errors and prevent site creation or generation.
    • Invalid inputs return an appropriate failure status.

@swissspidy swissspidy added this to the 2.8.13 milestone Aug 3, 2026
@swissspidy
swissspidy requested a review from a team as a code owner August 3, 2026 08:04
Copilot AI review requested due to automatic review settings August 3, 2026 08:04
@swissspidy swissspidy added command:site-create Related to 'site create' command command:site-generate Related to 'site generate' command labels Aug 3, 2026
@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: da148b2d-b244-4028-ac2a-0c12d451f299

📥 Commits

Reviewing files that changed from the base of the PR and between 22e146b and 9c0ad0f.

📒 Files selected for processing (2)
  • features/site-create.feature
  • src/Site_Command.php
🚧 Files skipped from review as they are similar to previous changes (2)
  • features/site-create.feature
  • src/Site_Command.php

📝 Walkthrough

Walkthrough

site create and site generate validate slugs. site create also validates parsed URLs, custom domains, and paths. Acceptance scenarios verify validation errors and exit code 1.

Changes

Site input validation

Layer / File(s) Summary
Site create URL validation
src/Site_Command.php, features/site-create.feature
site create rejects malformed URLs, unsupported URL components, invalid domain labels, unsupported path characters, and duplicate slashes. URL-derived subdirectory slugs omit empty path components. Acceptance scenarios cover these errors.
Site slug validation
src/Site_Command.php, features/site-create.feature, features/site-generate.feature
site create and site generate reject slugs with characters other than letters, numbers, and dashes. Valid slugs are lowercased. Acceptance scenarios verify the rejection and exit code.

Estimated code review effort: 2 (Simple) | ~15 minutes

Suggested labels: bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes validation of site slugs and URLs in both affected commands.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/special-chars

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.

@codecov

codecov Bot commented Aug 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR hardens the wp site create and wp site generate commands by adding stricter validation for site slugs and --site-url components to prevent unsafe or unexpected input from being accepted.

Changes:

  • Added explicit validation for --site-url hostname and path formats in site create.
  • Changed slug handling in both site create and site generate to error out when invalid characters are present (instead of silently proceeding).
  • Added Behat coverage for invalid slug and invalid domain in wp site create.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
src/Site_Command.php Adds slug validation errors for create/generate, plus domain/path validation for --site-url.
features/site-create.feature Adds Behat scenarios asserting errors for invalid slug and invalid --site-url domain.
Suppressed comments (2)

src/Site_Command.php:597

  • --site-url hostnames are case-insensitive, but this code preserves case. That can produce inconsistent stored domains and can also trigger the later “different domain” warning purely due to casing. Canonicalize the host to lowercase after validating it.
			if ( ! preg_match( '|^[a-zA-Z0-9.-]+$|', $custom_domain ) ) {
				WP_CLI::error( 'Invalid domain format in --site-url.' );
			}

src/Site_Command.php:806

  • wp site generate now errors on invalid --slug, but there is no Behat scenario covering this new validation/error message. Add a test in the existing site-generate.feature to prevent regressions.
		if ( ! preg_match( '|^([a-zA-Z0-9-])+$|', $base ) ) {
			WP_CLI::error( 'Slug may only contain letters, numbers, and dashes.' );
		}

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/Site_Command.php Outdated
Comment thread src/Site_Command.php Outdated

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

🤖 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 `@features/site-create.feature`:
- Around line 253-262: Add a Behat scenario in site-generate.feature covering wp
site generate with an invalid --slug value, using the existing When I try step
and asserting the expected validation message on STDERR and a failure return
code. Follow the surrounding site-generate scenarios and use a slug containing
invalid special characters.

In `@src/Site_Command.php`:
- Around line 595-597: Update the custom domain validation before the existing
WP_CLI::error call to split $custom_domain into dot-separated labels and
validate each label individually. Reject empty labels, labels beginning or
ending with a hyphen, and labels containing characters outside letters, digits,
and hyphens, while preserving acceptance of valid domains before $newdomain is
passed to wpmu_create_blog().
- Around line 599-601: Update custom-path validation in the site URL handling
around $custom_path and derived $base so paths without an explicit --slug cannot
contain dots, underscores, or URL dot segments. Apply this before deriving
$base, or normalize those segments consistently, ensuring the derived slug
always satisfies the existing slug validation.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3a8947f2-c0e8-4994-ab80-034d9ad060a5

📥 Commits

Reviewing files that changed from the base of the PR and between 11b395a and fc849c2.

📒 Files selected for processing (2)
  • features/site-create.feature
  • src/Site_Command.php

Comment thread features/site-create.feature
Comment thread src/Site_Command.php Outdated
Comment thread src/Site_Command.php Outdated

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Site_Command.php (1)

671-674: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reject non-DNS label slugs for subdomain installs.

The current regex only checks allowed characters. It accepts leading/trailing hyphens, ---, and values with a trailing newline; in subdomain installs these become invalid $newdomain labels. Use one strict validator around both site create and site generate: match the final label name exactly, enforce an alphanumeric first and last character in subdomain mode, and cap the length at 63 ASCII characters before constructing the domain.

🤖 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 `@src/Site_Command.php` around lines 671 - 674, Update the shared slug
validation used by site create and site generate at Site_Command.php:671-674 and
Site_Command.php:813-816 to validate the complete final label, reject leading or
trailing hyphens and newline-suffixed values, require alphanumeric first and
last characters in subdomain mode, and enforce a maximum of 63 ASCII characters
before constructing the domain.
🤖 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 `@src/Site_Command.php`:
- Around line 608-610: Update the custom path handling in the site URL
validation and slug derivation flow: validate the raw URL path for duplicate
slashes before normalization removes them, while preserving the existing
allowed-character checks. When deriving the slug, filter only empty path
components so the valid component "0" remains for paths such as /0/ and /foo/0/.
- Line 582: Update the parsed URL validation around the $parsed_url host check
to require is_array($parsed_url) before accessing host, scheme, or path.
Preserve the existing invalid-URL error path so wp_parse_url() returning false
is handled there without offset access.

---

Outside diff comments:
In `@src/Site_Command.php`:
- Around line 671-674: Update the shared slug validation used by site create and
site generate at Site_Command.php:671-674 and Site_Command.php:813-816 to
validate the complete final label, reject leading or trailing hyphens and
newline-suffixed values, require alphanumeric first and last characters in
subdomain mode, and enforce a maximum of 63 ASCII characters before constructing
the domain.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 7cea0efe-26f0-4f8c-bbb6-5d60249e7a6d

📥 Commits

Reviewing files that changed from the base of the PR and between fc849c2 and ab707ca.

📒 Files selected for processing (3)
  • features/site-create.feature
  • features/site-generate.feature
  • src/Site_Command.php
🚧 Files skipped from review as they are similar to previous changes (1)
  • features/site-create.feature

Comment thread src/Site_Command.php Outdated
Comment thread src/Site_Command.php Outdated

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/Site_Command.php (3)

677-680: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use a strict end-of-string anchor for both slug validators.

Both validators use $, which can accept a final newline before the asserted end. If the slug comes from user input or is parsed from a path, reject final-newline variants so site create and site generate use the same strict rule. Use \A[a-zA-Z0-9-]+\z or add the D modifier in src/Site_Command.php:677 and src/Site_Command.php:819.

🤖 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 `@src/Site_Command.php` around lines 677 - 680, The slug validators in
src/Site_Command.php:677-680 and src/Site_Command.php:819-822 both use a
non-strict end anchor, allowing trailing newlines. Update the preg_match
patterns in both validators to use strict \A...\z anchors or the D modifier,
preserving the existing allowed characters and error behavior.

582-594: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate host and path before sanitizing.

is_array() rejects non-array parse results, but arrays can still contain non-string ['host'] or ['path'] values. Extract the raw components, require both to be strings, reject malformed components before validation, then sanitize the values before storage.

🤖 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 `@src/Site_Command.php` around lines 582 - 594, Update the URL handling around
$parsed_url to extract the raw host and path components first, require each to
be a string, and reject malformed values before sanitization or scheme
validation. Then sanitize the validated string components for $custom_domain and
$custom_path, preserving the default root path when path is absent.

Source: Linters/SAST tools


580-588: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reject unsupported --site-url components.

When --site-url is provided, only host and path are passed to wpmu_create_blog(). Inputs such as user, pass, port, query, or fragment are accepted and discarded, so the created URL can differ from the requested URL. Reject those components before deriving $custom_domain and $custom_path.

🤖 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 `@src/Site_Command.php` around lines 580 - 588, Update the `has_site_url`
validation in `Site_Command` to reject parsed URLs containing `user`, `pass`,
`port`, `query`, or `fragment` before deriving `$custom_domain` and
`$custom_path`. Preserve acceptance of URLs using only the supported host,
optional path, and validated http/https scheme.
🤖 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.

Outside diff comments:
In `@src/Site_Command.php`:
- Around line 677-680: The slug validators in src/Site_Command.php:677-680 and
src/Site_Command.php:819-822 both use a non-strict end anchor, allowing trailing
newlines. Update the preg_match patterns in both validators to use strict
\A...\z anchors or the D modifier, preserving the existing allowed characters
and error behavior.
- Around line 582-594: Update the URL handling around $parsed_url to extract the
raw host and path components first, require each to be a string, and reject
malformed values before sanitization or scheme validation. Then sanitize the
validated string components for $custom_domain and $custom_path, preserving the
default root path when path is absent.
- Around line 580-588: Update the `has_site_url` validation in `Site_Command` to
reject parsed URLs containing `user`, `pass`, `port`, `query`, or `fragment`
before deriving `$custom_domain` and `$custom_path`. Preserve acceptance of URLs
using only the supported host, optional path, and validated http/https scheme.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 366b1a32-b88a-440f-82fc-fa053bf966f5

📥 Commits

Reviewing files that changed from the base of the PR and between ab707ca and 22e146b.

📒 Files selected for processing (2)
  • features/site-create.feature
  • src/Site_Command.php
🚧 Files skipped from review as they are similar to previous changes (1)
  • features/site-create.feature

@swissspidy
swissspidy merged commit 61604c3 into main Aug 3, 2026
74 checks passed
@swissspidy
swissspidy deleted the fix/special-chars branch August 3, 2026 15:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

command:site-create Related to 'site create' command command:site-generate Related to 'site generate' command

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants