Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.19'
node-version: '22.12.0'
cache: pnpm

- name: Install frontend dependencies
Expand Down Expand Up @@ -61,6 +61,7 @@ jobs:
php-version: ${{ matrix.php }}
extensions: mbstring, xml, curl, intl, json, mysqlnd, sockets
coverage: pcov
ini-values: pcov.directory=${{ github.workspace }}/app

- name: Get Composer cache directory
id: composer-cache
Expand Down Expand Up @@ -95,7 +96,7 @@ jobs:

- name: Run PHPUnit tests with coverage
if: github.event_name == 'pull_request'
run: composer test:coverage
run: composer test:all -- --coverage-clover build/logs/clover.xml --coverage-html build/logs/html

- name: Upload PHP coverage to Codecov
if: github.event_name == 'pull_request'
Expand All @@ -111,10 +112,6 @@ jobs:
if: github.event_name != 'pull_request'
run: composer test

- name: Run database integration tests
if: github.event_name == 'pull_request'
run: composer test:integration

- name: Run Composer audit
run: composer audit

Expand Down
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ PHP version 8.4 or higher is required, with the following extensions installed:
- [mysqlnd](http://php.net/manual/en/mysqlnd.install.php) for MySQL database (production)
- [libcurl](http://php.net/manual/en/curl.requirements.php) if you plan to use the HTTP\CURLRequest library

Frontend development and asset builds require Node.js 22.12.0 or higher and pnpm 10.34.5, as specified in `package.json`.

## Installation

1. Clone the repository:
Expand All @@ -37,12 +39,12 @@ PHP version 8.4 or higher is required, with the following extensions installed:

3. Install Node.js dependencies (for front-end build system):
```bash
npm install
pnpm install --frozen-lockfile
```

4. Build front-end assets:
```bash
npm run build
pnpm build
```

5. Database Configuration:
Expand Down Expand Up @@ -186,7 +188,7 @@ This project uses [Vite](https://vitejs.dev/) as a front-end build system to pro
To start the development server:

```bash
npm run dev
pnpm dev
```

This will start a development server at http://localhost:5173/ that will automatically reload when you make changes to the source files.
Expand All @@ -196,7 +198,7 @@ This will start a development server at http://localhost:5173/ that will automat
To build the assets for production:

```bash
npm run build
pnpm build
```

This will generate optimized files in the `public/dist/` directory.
Expand Down
7 changes: 5 additions & 2 deletions app/Config/Services.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
use App\Services\CodeIgniterWebhookHttpClient;
use App\Services\CorrelationId;
use App\Services\NullAuditLogger;
use App\Services\PinnedWebhookCURLRequest;
use App\Services\WebhookDeliveryService;
use App\Services\WebhookUrlValidator;
use CodeIgniter\CodeIgniter;
Expand Down Expand Up @@ -173,7 +174,7 @@ public static function webhookHttpClient(bool $getShared = true): WebhookHttpCli
return static::getSharedInstance('webhookHttpClient');
}

return new CodeIgniterWebhookHttpClient(parent::curlrequest([], null, null, false));
return new CodeIgniterWebhookHttpClient(new PinnedWebhookCURLRequest(config(App::class), static::webhookUrlValidator()));
}

public static function webhookUrlValidator(bool $getShared = true): WebhookUrlValidator
Expand All @@ -182,7 +183,9 @@ public static function webhookUrlValidator(bool $getShared = true): WebhookUrlVa
return static::getSharedInstance('webhookUrlValidator');
}

$environment = strtolower((string) ($_SERVER['CI_ENVIRONMENT'] ?? getenv('CI_ENVIRONMENT') ?: 'production'));
$environment = strtolower((string) (defined('ENVIRONMENT')
? ENVIRONMENT
: ($_SERVER['CI_ENVIRONMENT'] ?? getenv('CI_ENVIRONMENT') ?: 'production')));

return new WebhookUrlValidator(allowHttpLoopback: in_array($environment, ['development', 'testing'], true));
}
Expand Down
3 changes: 3 additions & 0 deletions app/Controllers/Api/V1/ChannelsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,9 @@ private function validateChannelFields(array $input, bool $partial): ?string
if (! is_string($input['slug'] ?? null) || preg_match('/^[a-z0-9-]{3,50}$/', trim((string) $input['slug'])) !== 1) {
return 'Channel slug must match ^[a-z0-9-]{3,50}$.';
}
if (str_starts_with(trim((string) $input['slug']), 'dm-')) {
return 'The dm- slug prefix is reserved for direct messages.';
}
if (trim((string) $input['slug']) === 'general' && $partial) {
return 'The #general slug is reserved.';
}
Expand Down
54 changes: 43 additions & 11 deletions app/Models/ChannelModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ public function isCreator(int $channelId, int $userId): bool

public function createPublic(string $name, string $slug, ?string $topic, int $creatorId): int|false
{
if (str_starts_with(strtolower(trim($slug)), 'dm-')) {
return false;
}

$this->db->transStart();
$channelId = $this->insert([
'name' => $name,
Expand Down Expand Up @@ -159,40 +163,55 @@ public function leave(int $channelId, int $userId): bool

public function updateChannel(int $channelId, array $changes): bool
{
if (isset($changes['slug']) && str_starts_with(strtolower(trim((string) $changes['slug'])), 'dm-')) {
return false;
}

return $this->update($channelId, $changes);
}

public function findOrCreateDm(int $firstUserId, int $secondUserId): int|false
{
if ($firstUserId <= 0 || $secondUserId <= 0 || $firstUserId === $secondUserId) {
return false;
}

[$firstUserId, $secondUserId] = [min($firstUserId, $secondUserId), max($firstUserId, $secondUserId)];
$slug = "dm-{$firstUserId}-{$secondUserId}";
$existing = $this->select('id')->where('slug', $slug)->first();
$existing = $this->select('id, channel_type')->where('slug', $slug)->first();
if (is_array($existing)) {
$channelId = (int) $existing['id'];
$this->join($channelId, $firstUserId);
$this->join($channelId, $secondUserId);

return $channelId;
return $this->validatedDmId($existing, $firstUserId, $secondUserId);
}

$this->db->transStart();
$this->db->table('channels')->ignore(true)->insert([
$inserted = $this->db->table('channels')->ignore(true)->insert([
'name' => 'Direct message',
'slug' => $slug,
'channel_type' => 'dm',
'created_by' => $firstUserId,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$channel = $this->select('id')->where('slug', $slug)->first();
if (! is_array($channel)) {
$created = $inserted && $this->db->affectedRows() === 1;
$channel = $this->select('id, channel_type')->where('slug', $slug)->first();
if (! $inserted || ! is_array($channel) || $channel['channel_type'] !== 'dm') {
$this->db->transRollback();

return false;
}
$channelId = (int) $channel['id'];
$this->join($channelId, $firstUserId);
$this->join($channelId, $secondUserId);
// Only populate membership for our own insert. A competing row must already
// represent exactly this pair; never repair an untrusted slug collision.
if ($created && (! $this->join($channelId, $firstUserId) || ! $this->join($channelId, $secondUserId))) {
$this->db->transRollback();

return false;
}
if ($this->validatedDmId($channel, $firstUserId, $secondUserId) === false) {
$this->db->transRollback();

return false;
}
$this->db->transComplete();

return $this->db->transStatus() ? $channelId : false;
Expand Down Expand Up @@ -224,6 +243,19 @@ public function messageChannelId(int $messageId): ?int
return is_array($row) ? (int) $row['channel_id'] : null;
}

/** @param array<string, mixed> $channel */
private function validatedDmId(array $channel, int $firstUserId, int $secondUserId): int|false
{
if ($channel['channel_type'] !== 'dm') {
return false;
}
$channelId = (int) $channel['id'];
$members = $this->memberIds($channelId);
sort($members);

return $members === [$firstUserId, $secondUserId] ? $channelId : false;
}

/** @return list<string> */
private function memberUsernames(int $channelId): array
{
Expand Down
3 changes: 1 addition & 2 deletions app/Services/CodeIgniterWebhookHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
namespace App\Services;

use App\Contracts\WebhookHttpClient;
use CodeIgniter\HTTP\CURLRequest;

final class CodeIgniterWebhookHttpClient implements WebhookHttpClient
{
public function __construct(private readonly CURLRequest $client)
public function __construct(private readonly PinnedWebhookCURLRequest $client)
{
}

Expand Down
50 changes: 50 additions & 0 deletions app/Services/PinnedWebhookCURLRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace App\Services;

use CodeIgniter\HTTP\CURLRequest;
use CodeIgniter\HTTP\URI;
use Config\App;
use InvalidArgumentException;

/** Keeps the validated DNS result attached to the connection cURL actually opens. */
class PinnedWebhookCURLRequest extends CURLRequest
{
public function __construct(App $config, private readonly WebhookUrlValidator $urlValidator)
{
parent::__construct($config, new URI());
}

protected function setCURLOptions(array $curlOptions = [], array $config = [])
{
$curlOptions = parent::setCURLOptions($curlOptions, $config);
$url = (string) ($curlOptions[CURLOPT_URL] ?? '');
$addresses = $this->urlValidator->resolveAllowedAddresses($url);
if ($addresses === []) {
throw new InvalidArgumentException('Webhook endpoint does not resolve to an allowed address.');
}

$host = strtolower((string) parse_url($url, PHP_URL_HOST));
$scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
$port = parse_url($url, PHP_URL_PORT) ?? ($scheme === 'https' ? 443 : 80);
$curlOptions[CURLOPT_RESOLVE] = [];
if (filter_var(trim($host, '[]'), FILTER_VALIDATE_IP) === false) {
$resolved = array_map(static fn (string $address): string => str_contains($address, ':') ? '[' . $address . ']' : $address, $addresses);
$curlOptions[CURLOPT_RESOLVE] = [$host . ':' . $port . ':' . implode(',', $resolved)];
}

// Keep the URL hostname for Host/SNI/certificate validation. Proxies and
// pooled connections must not bypass this request's approved addresses.
unset($curlOptions[CURLOPT_SHARE]);
$curlOptions[CURLOPT_PROXY] = '';
$curlOptions[CURLOPT_NOPROXY] = '*';
$curlOptions[CURLOPT_FRESH_CONNECT] = true;
$curlOptions[CURLOPT_FORBID_REUSE] = true;
$curlOptions[CURLOPT_SSL_VERIFYPEER] = true;
$curlOptions[CURLOPT_SSL_VERIFYHOST] = 2;
$curlOptions[CURLOPT_FOLLOWLOCATION] = false;
$curlOptions[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;

return $curlOptions;
}
}
23 changes: 15 additions & 8 deletions app/Services/WebhookUrlValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,36 +16,43 @@ public function __construct(?Closure $resolver = null, private readonly bool $al
}

public function isAllowed(string $url): bool
{
return $this->resolveAllowedAddresses($url) !== [];
}

/** @return list<string> Addresses that the transport must use without resolving the host again. */
public function resolveAllowedAddresses(string $url): array
{
if ($url === '' || strlen($url) > 2_048 || filter_var($url, FILTER_VALIDATE_URL) === false) {
return false;
return [];
}

$scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
$host = strtolower((string) parse_url($url, PHP_URL_HOST));
$host = strtolower(trim((string) parse_url($url, PHP_URL_HOST), '[]'));
$loopback = in_array($host, ['127.0.0.1', '::1', 'localhost'], true);
if ($scheme === 'http') {
return $this->allowHttpLoopback && $loopback;
// Never let localhost go through DNS, even in the development exception.
return $this->allowHttpLoopback && $loopback ? [$host === 'localhost' ? '127.0.0.1' : $host] : [];
}
if ($scheme !== 'https' || $host === '' || $loopback || str_ends_with($host, '.localhost')) {
return false;
return [];
}
if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
return self::isPublicAddress($host);
return self::isPublicAddress($host) ? [$host] : [];
}

$addresses = ($this->resolver)($host);
if ($addresses === []) {
return false;
return [];
}

foreach ($addresses as $address) {
if (! self::isPublicAddress($address)) {
return false;
return [];
}
}

return true;
return array_values(array_unique($addresses));
}

/** @return list<string> */
Expand Down
2 changes: 1 addition & 1 deletion biome.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"$schema": "https://biomejs.dev/schemas/2.5.13/schema.json",
"$schema": "https://biomejs.dev/schemas/2.5.15/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
Expand Down
Loading
Loading