diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9602a73..4954026 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 @@ -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 @@ -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' @@ -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 diff --git a/README.md b/README.md index 5245114..6584785 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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: @@ -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. @@ -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. diff --git a/app/Config/Services.php b/app/Config/Services.php index 4682b0b..9d29c58 100644 --- a/app/Config/Services.php +++ b/app/Config/Services.php @@ -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; @@ -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 @@ -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)); } diff --git a/app/Controllers/Api/V1/ChannelsController.php b/app/Controllers/Api/V1/ChannelsController.php index 6ae593e..9c80457 100644 --- a/app/Controllers/Api/V1/ChannelsController.php +++ b/app/Controllers/Api/V1/ChannelsController.php @@ -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.'; } diff --git a/app/Models/ChannelModel.php b/app/Models/ChannelModel.php index de1d60a..40005e0 100644 --- a/app/Models/ChannelModel.php +++ b/app/Models/ChannelModel.php @@ -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, @@ -159,24 +163,28 @@ 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', @@ -184,15 +192,26 @@ public function findOrCreateDm(int $firstUserId, int $secondUserId): int|false '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; @@ -224,6 +243,19 @@ public function messageChannelId(int $messageId): ?int return is_array($row) ? (int) $row['channel_id'] : null; } + /** @param array $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 */ private function memberUsernames(int $channelId): array { diff --git a/app/Services/CodeIgniterWebhookHttpClient.php b/app/Services/CodeIgniterWebhookHttpClient.php index 577561a..8143c3a 100644 --- a/app/Services/CodeIgniterWebhookHttpClient.php +++ b/app/Services/CodeIgniterWebhookHttpClient.php @@ -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) { } diff --git a/app/Services/PinnedWebhookCURLRequest.php b/app/Services/PinnedWebhookCURLRequest.php new file mode 100644 index 0000000..c4cf5bf --- /dev/null +++ b/app/Services/PinnedWebhookCURLRequest.php @@ -0,0 +1,50 @@ +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; + } +} diff --git a/app/Services/WebhookUrlValidator.php b/app/Services/WebhookUrlValidator.php index 0908a1e..0088c1e 100644 --- a/app/Services/WebhookUrlValidator.php +++ b/app/Services/WebhookUrlValidator.php @@ -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 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 */ diff --git a/biome.json b/biome.json index c43ed36..11cfa6a 100644 --- a/biome.json +++ b/biome.json @@ -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", diff --git a/docs/setup-guide.md b/docs/setup-guide.md index 1c060c4..701bbe8 100644 --- a/docs/setup-guide.md +++ b/docs/setup-guide.md @@ -32,10 +32,10 @@ Before you begin, ensure you have the following installed on your system: - **Composer** (Dependency Manager for PHP) - Verify your Composer installation: `composer --version` -- **Node.js and NPM** (for frontend development) - - Recommended: Node.js 16+ and NPM 8+ +- **Node.js and pnpm** (for frontend development) + - Required: Node.js 22.12.0 or higher and pnpm 10.34.5 (see `package.json`) - Verify your Node.js version: `node -v` - - Verify your NPM version: `npm -v` + - Verify your pnpm version: `pnpm -v` - **Git** (for version control) - Verify your Git installation: `git --version` @@ -60,7 +60,7 @@ This will install all the required PHP packages, including CodeIgniter 4 framewo ### 3. Install Frontend Dependencies ```bash -npm install +pnpm install --frozen-lockfile ``` This will install all the required frontend packages, including jQuery, Vue.js, and other dependencies specified in `package.json`. @@ -68,7 +68,7 @@ This will install all the required frontend packages, including jQuery, Vue.js, ### 4. Build Frontend Assets ```bash -npm run build +pnpm build ``` This will compile and bundle all frontend assets (JavaScript, CSS) using Vite. @@ -76,7 +76,7 @@ This will compile and bundle all frontend assets (JavaScript, CSS) using Vite. For development with hot reloading: ```bash -npm run dev +pnpm dev ``` ### 5. Database Configuration @@ -295,9 +295,9 @@ Start your web server and navigate to: - Clear Composer cache: `composer clear-cache` 5. **Frontend Asset Issues** - - Ensure Node.js and NPM are installed correctly - - Try clearing the NPM cache: `npm cache clean --force` - - Rebuild assets: `npm run build` + - Ensure Node.js 22.12.0+ and pnpm 10.34.5 are installed correctly + - Reinstall dependencies: `pnpm install --frozen-lockfile` + - Rebuild assets: `pnpm build` ### Debugging Tips @@ -324,7 +324,7 @@ Start your web server and navigate to: 2. Start the Vite development server for frontend assets: ```bash - npm run dev + pnpm dev ``` 3. Make your changes to the codebase @@ -336,7 +336,7 @@ Start your web server and navigate to: 5. Build frontend assets for production: ```bash - npm run build + pnpm build ``` ## Alternative: Docker Setup diff --git a/package.json b/package.json index 99e5134..28f3970 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "type": "module", "packageManager": "pnpm@12.15.0", "engines": { - "node": ">=20.19" + "node": ">=22.12.0" }, "scripts": { "dev": "vite", diff --git a/tests/Tests/Integration/ChannelApiIntegrationTest.php b/tests/Tests/Integration/ChannelApiIntegrationTest.php index 0b11143..e08f0bf 100644 --- a/tests/Tests/Integration/ChannelApiIntegrationTest.php +++ b/tests/Tests/Integration/ChannelApiIntegrationTest.php @@ -114,6 +114,48 @@ public function testDirectMessageCreationIsIdempotentAndPrivate(): void $this->assertSame(404, $reactionDenied->response()->getStatusCode()); } + public function testPublicChannelCreateAndUpdateRejectReservedDirectMessageNamespace(): void + { + $alice = $this->createUser('alice'); + $channels = new ChannelModel(); + $channelId = $channels->createPublic('Team', 'team-room', null, (int) $alice['id']); + $this->assertIsInt($channelId); + + foreach (['dm-1-2', 'dm-anything', ' dm-3-4 '] as $slug) { + $created = $this->jsonRequest($alice, 'post', '/api/v1/channels', ['name' => 'Impersonated DM', 'slug' => $slug]); + $this->assertSame(400, $created->response()->getStatusCode()); + $this->assertSame('validation', $this->json($created)['error']['type']); + + $updated = $this->jsonRequest($alice, 'patch', "/api/v1/channels/{$channelId}", ['slug' => $slug]); + $this->assertSame(400, $updated->response()->getStatusCode()); + $this->assertSame('validation', $this->json($updated)['error']['type']); + } + $this->seeInDatabase('channels', ['id' => $channelId, 'slug' => 'team-room']); + } + + public function testLegacyPublicCollisionCannotBeOpenedAsADirectMessage(): void + { + $alice = $this->createUser('alice'); + $bob = $this->createUser('bob'); + $mallory = $this->createUser('mallory'); + $channels = new ChannelModel(); + $this->db->table('channels')->insert([ + 'name' => 'Legacy public collision', + 'slug' => "dm-{$alice['id']}-{$bob['id']}", + 'channel_type' => 'public', + 'created_by' => $mallory['id'], + ]); + $channelId = (int) $this->db->insertID(); + $channels->join($channelId, (int) $mallory['id']); + + $opened = $this->jsonRequest($alice, 'post', '/api/v1/dms', ['user_id' => $bob['id']]); + $this->assertSame(500, $opened->response()->getStatusCode()); + $this->assertSame([(int) $mallory['id']], $channels->memberIds($channelId)); + $message = $this->jsonRequest($alice, 'post', "/api/v1/channels/{$channelId}/messages", ['message' => 'Private message']); + $this->assertSame(403, $message->response()->getStatusCode()); + $this->dontSeeInDatabase('messages', ['channel_id' => $channelId]); + } + public function testChannelMessagesRequireMembershipAndAreChannelScoped(): void { $alice = $this->createUser('alice'); diff --git a/tests/Tests/Integration/ChannelModelIntegrationTest.php b/tests/Tests/Integration/ChannelModelIntegrationTest.php index b94e74e..91e7fb2 100644 --- a/tests/Tests/Integration/ChannelModelIntegrationTest.php +++ b/tests/Tests/Integration/ChannelModelIntegrationTest.php @@ -77,6 +77,105 @@ public function testDirectMessagesAreIdempotentAndHaveExactlyTwoMembers(): void $this->seeInDatabase('channels', ['id' => $first, 'channel_type' => 'dm']); } + public function testPublicChannelsCannotClaimDirectMessageSlugs(): void + { + $creatorId = $this->createUser('creator'); + $channels = new ChannelModel(); + + $this->assertFalse($channels->createPublic('Impersonated DM', 'dm-1-2', null, $creatorId)); + $this->assertFalse($channels->createPublic('Impersonated DM', ' DM-1-2 ', null, $creatorId)); + $channelId = $channels->createPublic('Team', 'team-room', null, $creatorId); + $this->assertIsInt($channelId); + $this->assertFalse($channels->updateChannel($channelId, ['slug' => 'dm-anything'])); + $this->seeInDatabase('channels', ['id' => $channelId, 'slug' => 'team-room']); + } + + public function testLegacyPublicSlugCollisionCannotAcquireDirectMessageMembers(): void + { + $aliceId = $this->createUser('alice'); + $bobId = $this->createUser('bob'); + $malloryId = $this->createUser('mallory'); + $channels = new ChannelModel(); + $this->db->table('channels')->insert([ + 'name' => 'Legacy public collision', + 'slug' => "dm-{$aliceId}-{$bobId}", + 'channel_type' => 'public', + 'created_by' => $malloryId, + ]); + $channelId = (int) $this->db->insertID(); + $channels->join($channelId, $malloryId); + + $this->assertFalse($channels->findOrCreateDm($aliceId, $bobId)); + $this->assertFalse($channels->findOrCreateDm($bobId, $aliceId)); + $this->assertSame([$malloryId], $channels->memberIds($channelId)); + $this->seeInDatabase('channels', ['id' => $channelId, 'channel_type' => 'public']); + } + + public function testContaminatedDirectMessageCannotBeReusedOrRepaired(): void + { + $aliceId = $this->createUser('alice'); + $bobId = $this->createUser('bob'); + $malloryId = $this->createUser('mallory'); + $channels = new ChannelModel(); + $channelId = $channels->findOrCreateDm($aliceId, $bobId); + $this->assertIsInt($channelId); + $channels->join($channelId, $malloryId); + + $this->assertFalse($channels->findOrCreateDm($aliceId, $bobId)); + $this->assertEqualsCanonicalizing([$aliceId, $bobId, $malloryId], $channels->memberIds($channelId)); + + $channels->leave($channelId, $bobId); + $this->assertFalse($channels->findOrCreateDm($bobId, $aliceId)); + $this->assertEqualsCanonicalizing([$aliceId, $malloryId], $channels->memberIds($channelId)); + + $channels->leave($channelId, $malloryId); + $this->assertFalse($channels->findOrCreateDm($aliceId, $bobId)); + $this->assertSame([$aliceId], $channels->memberIds($channelId)); + } + + public function testIgnoredInsertRechecksChannelTypeAndMembers(): void + { + if ($this->db->getPlatform() !== 'SQLite3') { + $this->markTestSkipped('The deterministic ignored-insert trigger uses SQLite syntax.'); + } + + $aliceId = $this->createUser('alice'); + $bobId = $this->createUser('bob'); + $malloryId = $this->createUser('mallory'); + $channels = new ChannelModel(); + $table = $this->db->prefixTable('channels'); + $members = $this->db->prefixTable('channel_members'); + $slug = "dm-{$aliceId}-{$bobId}"; + + foreach (['public', 'polluted-dm', 'valid-dm'] as $collision) { + $type = $collision === 'public' ? 'public' : 'dm'; + $outsider = $collision === 'valid-dm' ? '' : "INSERT INTO {$members} (channel_id, user_id, joined_at) SELECT id, {$malloryId}, CURRENT_TIMESTAMP FROM {$table} WHERE slug = '{$slug}';"; + // Simulate a competing insert after the first lookup but before INSERT OR IGNORE. + $this->db->query("CREATE TRIGGER dm_insert_collision BEFORE INSERT ON {$table} + WHEN NEW.slug = '{$slug}' BEGIN + INSERT INTO {$table} (name, slug, channel_type, created_by) VALUES ('Collision', '{$slug}', '{$type}', {$aliceId}); + INSERT INTO {$members} (channel_id, user_id, joined_at) SELECT id, {$aliceId}, CURRENT_TIMESTAMP FROM {$table} WHERE slug = '{$slug}'; + INSERT INTO {$members} (channel_id, user_id, joined_at) SELECT id, {$bobId}, CURRENT_TIMESTAMP FROM {$table} WHERE slug = '{$slug}'; + {$outsider} + SELECT RAISE(IGNORE); + END"); + + try { + $channelId = $channels->findOrCreateDm($bobId, $aliceId); + if ($collision === 'valid-dm') { + $this->assertIsInt($channelId); + $this->assertEqualsCanonicalizing([$aliceId, $bobId], $channels->memberIds($channelId)); + $this->assertSame($channelId, $channels->findOrCreateDm($aliceId, $bobId)); + } else { + $this->assertFalse($channelId, $collision); + } + } finally { + $this->db->query('DROP TRIGGER dm_insert_collision'); + $this->db->table('channels')->where('slug', $slug)->delete(); + } + } + } + private function createUser(string $username): int { $id = (new UserModel())->createUser($username, "{$username}@example.com", 'Password123!'); diff --git a/tests/Tests/Integration/WebhookIntegrationTest.php b/tests/Tests/Integration/WebhookIntegrationTest.php index 2c35379..4a2c63c 100644 --- a/tests/Tests/Integration/WebhookIntegrationTest.php +++ b/tests/Tests/Integration/WebhookIntegrationTest.php @@ -9,7 +9,6 @@ use App\Models\MessageReactionModel; use App\Models\UserModel; use App\Models\WebhookModel; -use App\Services\CodeIgniterWebhookHttpClient; use App\Services\WebhookDeliveryService; use App\Services\WebhookUrlValidator; use CodeIgniter\Test\TestResponse; @@ -126,21 +125,23 @@ public function testDeliveryPostsVerifiableSignatureToLocalHttpEndpoint(): void $webhooks, (int) $alice['id'], ['message.created'], - "http://127.0.0.1:{$port}/receive", + "http://localhost:{$port}/receive", 'test-signing-secret', ); $this->assertSame(1, $webhooks->enqueue('message.created', ['message' => ['id' => 42]])); - $client = new CodeIgniterWebhookHttpClient(Services::curlrequest([], null, null, false)); + $client = Services::webhookHttpClient(false); $result = (new WebhookDeliveryService( $webhooks, $client, static fn (): int => 1_700_000_000, new WebhookUrlValidator(allowHttpLoopback: true), ))->deliver(); - $this->assertSame(['processed' => 1, 'delivered' => 1, 'retrying' => 0, 'dropped' => 0], $result); + $deliveryError = db_connect('tests')->table('webhook_deliveries')->where('webhook_id', $webhookId)->get()->getRowArray()['last_error'] ?? ''; + $this->assertSame(['processed' => 1, 'delivered' => 1, 'retrying' => 0, 'dropped' => 0], $result, (string) $deliveryError); $this->seeInDatabase('webhook_deliveries', ['webhook_id' => $webhookId, 'status' => 'delivered', 'attempts' => 1]); $capture = json_decode((string) file_get_contents($captureFile), true, flags: JSON_THROW_ON_ERROR); + $this->assertSame("localhost:{$port}", $capture['headers']['host']); $this->assertSame('message.created', $capture['headers']['x-webhook-event']); $this->assertSame('1700000000', $capture['headers']['x-webhook-timestamp']); $expected = 'v1=' . hash_hmac('sha256', '1700000000.' . $capture['body'], 'test-signing-secret'); diff --git a/tests/Tests/Unit/WebhookTransportTest.php b/tests/Tests/Unit/WebhookTransportTest.php new file mode 100644 index 0000000..1e066c0 --- /dev/null +++ b/tests/Tests/Unit/WebhookTransportTest.php @@ -0,0 +1,155 @@ +transport($validator); + $client = new CodeIgniterWebhookHttpClient($transport); + $this->assertSame(['status' => 204, 'body' => ''], $client->send('https://hooks.example:8443/events', '{}', [])); + + $this->assertSame(1, $resolutions); + $this->assertSame('https://hooks.example:8443/events', $transport->sentOptions[CURLOPT_URL]); + $this->assertSame(['hooks.example:8443:8.8.8.8,[2606:4700:4700::1111]'], $transport->sentOptions[CURLOPT_RESOLVE]); + + // A later delivery must revalidate; the now-private DNS result never reaches cURL. + try { + $client->send('https://hooks.example:8443/events', '{}', []); + $this->fail('The changed DNS result must be rejected.'); + } catch (InvalidArgumentException) { + $this->assertSame(2, $resolutions); + $this->assertSame(1, $transport->connections); + } + } + + public function testPrivateAndMixedDnsAnswersNeverReachTheTransport(): void + { + foreach ([[], ['10.0.0.1'], ['8.8.8.8', '127.0.0.1'], ['8.8.8.8', '::1'], ['::ffff:127.0.0.1']] as $addresses) { + $transport = $this->transport(new WebhookUrlValidator(static fn (string $host): array => $addresses)); + try { + (new CodeIgniterWebhookHttpClient($transport))->send('https://hooks.example/events', '{}', []); + $this->fail('Every DNS address must be public.'); + } catch (InvalidArgumentException) { + $this->assertSame(0, $transport->connections); + } + } + } + + public function testTransportForcesTlsValidationAndDisablesRedirectsProxiesAndConnectionReuse(): void + { + $transport = $this->transport(new WebhookUrlValidator(static fn (string $host): array => ['8.8.8.8'])); + $transport->post('https://hooks.example/events', [ + 'allow_redirects' => true, + 'proxy' => 'http://127.0.0.1:8080', + 'verify' => false, + 'fresh_connect' => false, + ]); + + $this->assertTrue($transport->sentOptions[CURLOPT_SSL_VERIFYPEER]); + $this->assertSame(2, $transport->sentOptions[CURLOPT_SSL_VERIFYHOST]); + $this->assertFalse($transport->sentOptions[CURLOPT_FOLLOWLOCATION]); + $this->assertSame('', $transport->sentOptions[CURLOPT_PROXY]); + $this->assertSame('*', $transport->sentOptions[CURLOPT_NOPROXY]); + $this->assertTrue($transport->sentOptions[CURLOPT_FRESH_CONNECT]); + $this->assertTrue($transport->sentOptions[CURLOPT_FORBID_REUSE]); + $this->assertArrayNotHasKey(CURLOPT_SHARE, $transport->sentOptions); + $this->assertSame(CURLPROTO_HTTP | CURLPROTO_HTTPS, $transport->sentOptions[CURLOPT_PROTOCOLS]); + $this->assertSame(['hooks.example:443:8.8.8.8'], $transport->sentOptions[CURLOPT_RESOLVE]); + } + + public function testDevelopmentLocalhostExceptionUsesAPinnedLoopbackAddressWithoutDns(): void + { + $validator = new WebhookUrlValidator(static function (string $host): array { + self::fail('The loopback exception must never use DNS.'); + }, allowHttpLoopback: true); + $transport = $this->transport($validator); + (new CodeIgniterWebhookHttpClient($transport))->send('http://localhost:8080/receive', '{}', []); + + $this->assertSame(['localhost:8080:127.0.0.1'], $transport->sentOptions[CURLOPT_RESOLVE]); + $this->assertSame(['127.0.0.1'], $validator->resolveAllowedAddresses('http://127.0.0.1:8080/receive')); + $this->assertSame(['::1'], $validator->resolveAllowedAddresses('http://[::1]:8080/receive')); + $this->assertFalse((new WebhookUrlValidator())->isAllowed('http://localhost:8080/receive')); + $this->assertFalse($validator->isAllowed('https://localhost/receive')); + $this->assertFalse($validator->isAllowed('http://hooks.example/receive')); + } + + public function testPublicIpLiteralsDoNotRequireDns(): void + { + $transport = $this->transport(new WebhookUrlValidator(static function (string $host): array { + self::fail('IP literals must never use DNS.'); + })); + foreach (['https://8.8.8.8/events', 'https://[2606:4700:4700::1111]:8443/events'] as $url) { + (new CodeIgniterWebhookHttpClient($transport))->send($url, '{}', []); + $this->assertSame([], $transport->sentOptions[CURLOPT_RESOLVE]); + $this->assertSame($url, $transport->sentOptions[CURLOPT_URL]); + } + } + + public function testSchemeAndHostnameCaseKeepThePinOnTheActualUrlPort(): void + { + $transport = $this->transport(new WebhookUrlValidator(static fn (string $host): array => ['8.8.8.8'])); + foreach ([ + ['HTTPS://Hooks.Example/events', 'hooks.example:443:8.8.8.8'], + ['hTtPs://Hooks.Example./events', 'hooks.example.:443:8.8.8.8'], + ['HTTPS://Hooks.Example.:9443/events', 'hooks.example.:9443:8.8.8.8'], + ] as [$url, $resolve]) { + (new CodeIgniterWebhookHttpClient($transport))->send($url, '{}', []); + $this->assertSame($url, $transport->sentOptions[CURLOPT_URL]); + $this->assertSame([$resolve], $transport->sentOptions[CURLOPT_RESOLVE]); + } + } + + public function testFactoryUsesTheRuntimeEnvironmentWhenRequestGlobalsAreReset(): void + { + $this->assertSame('testing', ENVIRONMENT); + $serverEnvironment = $_SERVER['CI_ENVIRONMENT'] ?? null; + $processEnvironment = getenv('CI_ENVIRONMENT'); + unset($_SERVER['CI_ENVIRONMENT']); + putenv('CI_ENVIRONMENT'); + + try { + $this->assertTrue(Services::webhookUrlValidator(false)->isAllowed('http://localhost:8080/receive')); + $this->assertFalse((new WebhookUrlValidator())->isAllowed('http://localhost:8080/receive')); + $this->assertFalse((new WebhookUrlValidator())->isAllowed('http://127.0.0.1:8080/receive')); + } finally { + if ($serverEnvironment !== null) { + $_SERVER['CI_ENVIRONMENT'] = $serverEnvironment; + } + putenv($processEnvironment === false ? 'CI_ENVIRONMENT' : 'CI_ENVIRONMENT=' . $processEnvironment); + } + } + + private function transport(WebhookUrlValidator $validator): PinnedWebhookCURLRequest + { + return new class(config(App::class), $validator) extends PinnedWebhookCURLRequest { + public array $sentOptions = []; + public int $connections = 0; + + protected function sendRequest(array $curlOptions = []): string + { + ++$this->connections; + $this->sentOptions = $curlOptions; + + return "HTTP/1.1 204 No Content\r\n\r\n"; + } + }; + } +}