Skip to content

fix: sanitize branch names for valid domain generation - #11245

Merged
hmacr merged 15 commits into
1.8.xfrom
ser-1102
Feb 19, 2026
Merged

hmacr merged 15 commits into
1.8.xfrom
ser-1102

Conversation

@hmacr

@hmacr hmacr commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

Branch names containing invalid domain characters (like '/') were being used directly when creating VCS preview domains, resulting in invalid domains like 'branch-abc/test.appwrite.network'. This adds a Domain helper class that sanitizes branch names by replacing invalid characters with hyphens before generating domains.

Closes SER-1102

@coderabbitai

coderabbitai Bot commented Feb 4, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR introduces a new Filter/Adapter architecture for constructing VCS branch domains. It adds three foundational classes: an abstract Adapter base class defining input/output contracts, a concrete BranchDomain adapter that generates domain strings from branch name and project identifiers, and a Filter class orchestrating adapter pipelines. The PR then refactors three existing files to use this new approach, replacing manual domain construction logic with Filter-based transformations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'fix: sanitize branch names for valid domain generation' accurately summarizes the main change—adding sanitization of branch names to prevent invalid characters in generated VCS preview domains.
Description check ✅ Passed The PR description clearly explains the problem (invalid domain characters in branch names) and the solution (adding sanitization logic), which aligns with the changeset introducing the BranchDomain adapter and Filter/Transformation classes.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into 1.8.x

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ser-1102

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.

@github-actions

github-actions Bot commented Feb 4, 2026 •

Copy link
Copy Markdown

Security Scan Results for PR

Docker Image Scan Results

Package Version Vulnerability Severity
libecpg 18.1-r0 CVE-2026-2004 HIGH
libecpg 18.1-r0 CVE-2026-2005 HIGH
libecpg 18.1-r0 CVE-2026-2006 HIGH
libecpg 18.1-r0 CVE-2026-2007 HIGH
libecpg-dev 18.1-r0 CVE-2026-2004 HIGH
libecpg-dev 18.1-r0 CVE-2026-2005 HIGH
libecpg-dev 18.1-r0 CVE-2026-2006 HIGH
libecpg-dev 18.1-r0 CVE-2026-2007 HIGH
libpq 18.1-r0 CVE-2026-2004 HIGH
libpq 18.1-r0 CVE-2026-2005 HIGH
libpq 18.1-r0 CVE-2026-2006 HIGH
libpq 18.1-r0 CVE-2026-2007 HIGH
libpq-dev 18.1-r0 CVE-2026-2004 HIGH
libpq-dev 18.1-r0 CVE-2026-2005 HIGH
libpq-dev 18.1-r0 CVE-2026-2006 HIGH
libpq-dev 18.1-r0 CVE-2026-2007 HIGH
postgresql18-dev 18.1-r0 CVE-2026-2004 HIGH
postgresql18-dev 18.1-r0 CVE-2026-2005 HIGH
postgresql18-dev 18.1-r0 CVE-2026-2006 HIGH
postgresql18-dev 18.1-r0 CVE-2026-2007 HIGH

Source Code Scan Results

🎉 No vulnerabilities found!

@hmacr
hmacr requested a review from Meldiron February 4, 2026 10:18

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@app/controllers/api/vcs.php`:
- Line 7: The PSR-12 ordered_imports error is caused by the Appwrite\Vcs\Domain
import being out of alphabetical order; update the use statements in api/vcs.php
so all Appwrite\SDK\* imports come first and then place use Appwrite\Vcs\Domain
after them, ensuring imports within the Appwrite namespace are sorted
alphabetically (and run the linter to confirm); reference the use statement for
Domain to locate and reorder it.

In `@src/Appwrite/Platform/Modules/Compute/Base.php`:
- Line 8: The PSR-12 ordered_imports lint is failing because the `use
Appwrite\Vcs\Domain;` import in src/Appwrite/Platform/Modules/Compute/Base.php
is out of alphabetical order; move the `use Appwrite\Vcs\Domain;` statement so
it appears after other `Appwrite\Platform\*` imports and before any `Utopia\*`
imports (i.e., reorder the `use` block around the `Base` class imports), then
re-run the linter to confirm the `ordered_imports` violation is resolved.

In `@src/Appwrite/Vcs/Domain.php`:
- Around line 41-52: In generateBranchPrefix, handle the case where
sanitizeBranchName(substr(...)) returns an empty string or yields a leading
hyphen: after computing $branchPrefix = self::sanitizeBranchName(...), if
$branchPrefix is empty then derive a safe base by stripping invalid chars from
the original substring (or fallback to a short fixed token like 'br') before
appending the hash; when adding the hash suffix (using self::HASH_SUFFIX_LENGTH)
only prepend the '-' separator if the base is non-empty, and finally trim any
leading '-' from the combined result and ensure it is not empty before
returning; reference generateBranchPrefix, sanitizeBranchName,
BRANCH_PREFIX_MAX_LENGTH, and HASH_SUFFIX_LENGTH when making the change.
🧹 Nitpick comments (1)
tests/unit/Vcs/DomainTest.php (1)

108-127: Consider adding a test for all-invalid prefix edge case.

The test suite is comprehensive. Consider adding a test case for when the first 16 characters are all invalid (e.g., "////////////////something"). This would verify the behavior mentioned in my comment on Domain.php.

Suggested test case
public function testGenerateBranchPrefixAllInvalidFirstChars(): void
{
    // First 16 chars are all slashes, remainder has valid chars
    $prefix = Domain::generateBranchPrefix('////////////////validpart');
    // Verify the prefix doesn't start with a hyphen (invalid DNS label)
    $this->assertDoesNotMatchRegularExpression('/^-/', $prefix);
}

Comment thread app/controllers/api/vcs.php Resolved
Comment thread src/Appwrite/Vcs/Domain.php Resolved
Branch names containing invalid domain characters (like '/') were being
used directly when creating VCS preview domains, resulting in invalid
domains like 'branch-abc/test.appwrite.network'. This adds a Domain
helper class that sanitizes branch names by replacing invalid characters
with hyphens before generating domains.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@github-actions

github-actions Bot commented Feb 4, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

  • Requests per second: 1,870
  • Requests with 200 status code: 336,619
  • P99 latency: 0.086085831

⚡ Benchmark Comparison

Metric This PR Latest version
RPS 1,870 1,125
200 336,619 202,624
P99 0.086085831 0.195354017

Comment thread src/Appwrite/Vcs/Domain.php Resolved

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/Appwrite/Vcs/Domain.php`:
- Around line 18-31: The sanitizeBranchName function currently allows
underscores; update it to forbid underscores by changing the regex in
sanitizeBranchName from '/[^a-zA-Z0-9_-]+/' to '/[^a-zA-Z0-9-]+/' so only
letters, digits, and hyphens are permitted, and update the docblock text to
reflect that underscores are not allowed (mentioning RFC 1035/1123 LDH rules and
CA/Browser requirements if desired).

Comment thread src/Appwrite/Vcs/Domain.php Resolved
Comment thread src/Appwrite/Vcs/Domain.php Resolved

// VCS branch preview
if (!empty($providerBranch)) {
$branchPrefix = substr($providerBranch, 0, 16);

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.

Note for future: We will need to apply same fix in Cloud vcs.php

Comment thread src/Appwrite/Vcs/Domain.php Resolved
hmacr and others added 4 commits February 4, 2026 17:11
Replace regex with explicit character validation using Utopia Text
constants for better readability and maintainability.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@src/Appwrite/Platform/Modules/Functions/Workers/Builds.php`:
- Around line 12-16: Reorder the import statements to satisfy PSR-12
ordered_imports: sort the Appwrite imports alphabetically by their fully
qualified names (e.g., Appwrite\Transformation\Transformation,
Appwrite\Transformation\Adapter\BranchDomain,
Appwrite\Utopia\Response\Model\Deployment, Appwrite\Vcs\Comment) and place the
global Exception import after a single blank line following the Appwrite group;
update the import block containing Transformation, BranchDomain, Deployment,
Comment, and Exception accordingly.

In `@src/Appwrite/Transformation/Adapter/BranchDomain.php`:
- Around line 78-103: sanitizeBranchName currently preserves uppercase because
allowedChars includes upper and lower; normalize the input to lowercase before
building allowedCharsFlip and iterating. In sanitizeBranchName(string $branch):
string, convert the branch string to lowercase (e.g. $branch =
strtolower($branch) or mb_strtolower for multibyte safety) immediately at the
start so the subsequent loop, allowedChars/allowedCharsFlip checks,
dash-collapsing logic and final trim(...) produce a lowercase sanitized branch
(e.g. 'feature/SER-1234' -> 'branch-feature-ser-1234-') and avoid case-variant
duplicates.

Comment thread src/Appwrite/Filter/BranchDomain.php Resolved

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

Actionable comments posted: 0

Caution

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

⚠️ Outside diff range comments (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)

1056-1074: ⚠️ Potential issue | 🟠 Major

Bug: deploymentResourceId should reference the site resource, not the deployment.

Lines 1066-1067 incorrectly use $deployment->getId() and $deployment->getSequence() for deploymentResourceId and deploymentResourceInternalId. Based on the pattern in Base.php (lines 258-259, 284-285, 324-326) and the semantic meaning of "deploymentResource", these fields should reference the site being deployed, not the deployment itself.

🐛 Proposed fix
                         'deploymentId' => $deployment->getId(),
                         'deploymentInternalId' => $deployment->getSequence(),
                         'deploymentResourceType' => 'site',
-                        'deploymentResourceId' => $deployment->getId(),
-                        'deploymentResourceInternalId' => $deployment->getSequence(),
+                        'deploymentResourceId' => $resource->getId(),
+                        'deploymentResourceInternalId' => $resource->getSequence(),
                         'deploymentVcsProviderBranch' => $branchName,
🧹 Nitpick comments (2)
src/Appwrite/Transformation/Adapter/BranchDomain.php (2)

20-26: Consider removing unused $traits parameter or marking it intentionally unused.

The static analysis tool correctly identifies that the $traits parameter in isValid() is never used since the method always returns true. If this is intentional for interface compliance with the parent Adapter class, consider adding a @SuppressWarnings(PHPMD.UnusedFormalParameter) annotation or prefixing with underscore to indicate intentional non-use.

♻️ Suggested fix
     /**
-     * `@param` array<mixed> $traits
+     * `@param` array<mixed> $traits Unused, required by Adapter interface
+     * `@SuppressWarnings`(PHPMD.UnusedFormalParameter)
      */
     public function isValid(array $traits): bool
     {
         return true;
     }

37-47: Consider validating required inputs to avoid malformed domains.

When branch, resourceId, projectId, or sitesDomain are empty, the generated domain could be malformed (e.g., branch---abc1234. if sitesDomain is also empty). Consider adding validation or throwing an exception for missing required inputs.

🛡️ Suggested validation
     public function transform(): void
     {
         $branch = $this->input['branch'] ?? '';
         $resourceId = $this->input['resourceId'] ?? '';
         $projectId = $this->input['projectId'] ?? '';
         $sitesDomain = $this->input['sitesDomain'] ?? '';

+        if (empty($branch) || empty($resourceId) || empty($projectId) || empty($sitesDomain)) {
+            throw new \InvalidArgumentException('Missing required input: branch, resourceId, projectId, and sitesDomain are required');
+        }
+
         $branchPrefix = $this->generateBranchPrefix($branch);

Comment thread app/controllers/api/vcs.php Resolved

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 fixes a bug where branch names containing invalid domain characters (like '/') were being used directly when creating VCS preview domains, resulting in invalid domains. The fix introduces a new BranchDomain transformation adapter class that sanitizes branch names by replacing invalid characters with hyphens before generating domains.

Changes:

  • Created a new BranchDomain transformation adapter class that sanitizes branch names and generates valid domain names
  • Refactored three locations where branch domain generation was implemented inline to use the new adapter
  • Added comprehensive unit tests covering various real-world branch naming patterns

Reviewed changes

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

Show a summary per file
File Description
src/Appwrite/Transformation/Adapter/BranchDomain.php New adapter class that sanitizes branch names and generates valid domains with proper character handling
tests/unit/Transformation/TransformationTest.php Added comprehensive tests for the BranchDomain adapter covering various branch naming patterns
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php Refactored to use the new BranchDomain adapter instead of inline domain generation
src/Appwrite/Platform/Modules/Compute/Base.php Refactored to use the new BranchDomain adapter instead of inline domain generation
app/controllers/api/vcs.php Refactored to use the new BranchDomain adapter instead of inline domain generation

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

Comment thread src/Appwrite/Filter/BranchDomain.php Resolved
Comment thread src/Appwrite/Filter/BranchDomain.php Resolved

$branchPrefix = $this->generateBranchPrefix($branch);
$resourceProjectHash = substr(hash('sha256', $resourceId . $projectId), 0, self::HASH_SUFFIX_LENGTH);
$this->output = strtolower("branch-{$branchPrefix}-{$resourceProjectHash}.{$sitesDomain}");

Copilot AI Feb 5, 2026

Copy link

Choose a reason for hiding this comment

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

The new implementation converts the entire domain to lowercase, while the old implementation didn't explicitly do this. While this is good practice for domain names and DNS is case-insensitive, for existing deployments with branch names containing uppercase letters (without special characters), this will generate a different rule ID and create a new rule instead of updating the existing one. Consider documenting this behavior change in release notes or migration guide.

Copilot uses AI. Check for mistakes.

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

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In `@app/controllers/api/vcs.php`:
- Around line 321-331: The code calls $filter->filter() but ignores its boolean
return value and then unconditionally calls $filter->getOutput(), which will
throw if validation failed; update the block around Filter (the $filter variable
created with new Filter([new FilterBranchDomain()])) to check the result of
$filter->filter() and handle the false case before calling getOutput() — e.g. if
filter() returns false, obtain validation errors from the Filter (or fail fast)
and return or throw a controlled error/response instead of proceeding to compute
$domain and $ruleId; ensure getOutput() is only called when filter() succeeded
so $domain and $ruleId are derived from a valid output.

In `@src/Appwrite/Filter/Adapter.php`:
- Around line 1-29: Remove the trailing whitespace at the end of the file and
ensure it terminates with a single newline to satisfy the
no_trailing_whitespace_in_eof Pint rule; also remove the empty public function
__construct() in the Adapter class (or keep it only if subclasses will
explicitly call parent::__construct()) since it serves no purpose—update the
Adapter class by deleting the empty constructor while leaving setInput,
getOutput, isValid, and filter intact.

In `@src/Appwrite/Filter/Adapter/BranchDomain.php`:
- Line 1: Remove any trailing whitespace at the end of the file BranchDomain.php
and ensure the file ends with exactly one newline character (no extra spaces or
blank lines after the final newline) so it satisfies the
no_trailing_whitespace_in_eof check.
- Around line 64-75: generateBranchPrefix may produce an empty sanitized prefix
(sanitizeBranchName returns '') which leads to a double-hyphen when you append
'-' + hash; update generateBranchPrefix to guard for an empty sanitized result
and use a hash-only prefix instead of prefix + '-' + hash: compute the hash
suffix from the remaining chars as currently done, but if
sanitizeBranchName(...) yields an empty string, set branchPrefix to that hash
suffix (or a deterministic hash-based label) rather than joining with a leading
'-', otherwise keep existing behavior; reference generateBranchPrefix,
sanitizeBranchName, BRANCH_PREFIX_MAX_LENGTH and HASH_SUFFIX_LENGTH when making
the change.
🧹 Nitpick comments (2)
src/Appwrite/Filter/Filter.php (2)

41-61: Validation uses the original input for all adapters, but the pipeline transforms it — mismatch in multi-adapter scenarios.

isValid() is called on every adapter with $this->input (the original Filter input), but the second loop feeds each adapter the output of the previous one. If a second adapter is ever added to the pipeline, its isValid() would validate against the wrong data shape (the original input instead of the transformed intermediate).

This isn't a bug today (single-adapter usage), but it's a design inconsistency worth noting. Consider either:

  • Validating each adapter against its actual input inside the pipeline loop, or
  • Documenting that this class is intended for single-adapter use only.

7-10: PHPDoc mismatch: @var array<mixed> should be @var array<Adapter>.

The property holds Adapter instances (as the constructor's @param correctly states). The @var annotation should match.

-    /**
-     * `@var` array<mixed> $adapters
-     */
+    /**
+     * `@var` array<Adapter> $adapters
+     */

Comment thread app/controllers/api/vcs.php Resolved
Comment thread src/Appwrite/Filter/Adapter.php Resolved
Comment thread src/Appwrite/Filter/BranchDomain.php Resolved
Comment thread src/Appwrite/Filter/BranchDomain.php Resolved
@hmacr
hmacr merged commit e902d3b into 1.8.x Feb 19, 2026
113 of 114 checks passed
pull Bot pushed a commit to pgoslatara/appwrite that referenced this pull request Sep 28, 2026
Before appwrite#11245 sanitized branch names, a "/" in the branch was stored in the
preview rule's domain. No browser, edge or CDN can address such a name, and
the rules still fail CDN purges on Cloud today. BranchDomain now validates its
own result, and its callers skip only the branch preview rule when it throws,
so the deployment itself still goes ahead.
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.

3 participants