From 266b1d66580e6df1c68f0e1f93c63f48898947cf Mon Sep 17 00:00:00 2001 From: Ajmal Alkhaledi Date: Mon, 2 Nov 2026 16:45:51 +0000 Subject: [PATCH 1/2] chore: add license, tests, CI and governance; harden multipart file read - Add MIT LICENSE (composer.json already declared MIT; file was missing) - Add PHPUnit suite for pure-PHP units: MultipartEncoder, PacketBuffer, RequestOptions::toTransportArray() (27 tests, 51 assertions) - Add GitHub Actions CI: PHP 8.2-8.4 (validate/lint/test) + Go build/vet - Add CONTRIBUTING, SECURITY, CODE_OF_CONDUCT, CHANGELOG, issue/PR templates - MultipartEncoder::encode(): validate file readability before reading, so a missing/unreadable path throws AstraException cleanly instead of emitting a raw PHP warning - Align composer.json description; export-ignore dev files from the dist; gitignore composer.lock and .phpunit.cache Co-Authored-By: Claude Opus 4.8 --- .gitattributes | 9 ++ .github/ISSUE_TEMPLATE/bug_report.yml | 52 ++++++++ .github/ISSUE_TEMPLATE/config.yml | 5 + .github/ISSUE_TEMPLATE/feature_request.yml | 23 ++++ .github/PULL_REQUEST_TEMPLATE.md | 22 ++++ .github/workflows/ci.yml | 47 ++++++++ .gitignore | 2 + CHANGELOG.md | 43 +++++++ CODE_OF_CONDUCT.md | 35 ++++++ CONTRIBUTING.md | 62 ++++++++++ LICENSE | 21 ++++ SECURITY.md | 32 +++++ composer.json | 9 +- phpunit.xml | 19 +++ src/MultipartEncoder.php | 8 +- tests/MultipartEncoderTest.php | 100 +++++++++++++++ tests/PacketBufferTest.php | 71 +++++++++++ tests/RequestOptionsTest.php | 134 +++++++++++++++++++++ 18 files changed, 691 insertions(+), 3 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/ci.yml create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 SECURITY.md create mode 100644 phpunit.xml create mode 100644 tests/MultipartEncoderTest.php create mode 100644 tests/PacketBufferTest.php create mode 100644 tests/RequestOptionsTest.php diff --git a/.gitattributes b/.gitattributes index 383ff26..92c6c66 100644 --- a/.gitattributes +++ b/.gitattributes @@ -9,3 +9,12 @@ .gitignore export-ignore .gitattributes export-ignore + +/tests/ export-ignore +/.github/ export-ignore +/phpunit.xml export-ignore +/.phpunit.cache/ export-ignore +/CONTRIBUTING.md export-ignore +/CODE_OF_CONDUCT.md export-ignore +/CHANGELOG.md export-ignore +/SECURITY.md export-ignore diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..98e4941 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,52 @@ +name: Bug report +description: Report a reproducible problem in AstraHTTP +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to file a bug. Please provide a minimal + reproduction so the issue can be investigated quickly. + - type: textarea + id: what-happened + attributes: + label: What happened? + description: Describe the actual behavior and the behavior you expected. + placeholder: "The request to ... returned ... but I expected ..." + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Minimal reproduction + description: The smallest code snippet that reproduces the problem. + render: php + validations: + required: true + - type: input + id: php-version + attributes: + label: PHP version + placeholder: "8.3.x" + validations: + required: true + - type: input + id: platform + attributes: + label: OS and architecture + placeholder: "Ubuntu 24.04 / x86_64" + validations: + required: true + - type: input + id: package-version + attributes: + label: AstraHTTP version + placeholder: "2.0.0" + validations: + required: true + - type: textarea + id: logs + attributes: + label: Relevant logs / errors + description: Paste any exception messages or worker output. + render: shell diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..150a21e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Security report + url: https://github.com/astrahttp/http/security/advisories/new + about: Please report security vulnerabilities privately, not as public issues. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..f3f444f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,23 @@ +name: Feature request +description: Suggest an improvement or new capability +labels: ["enhancement"] +body: + - type: textarea + id: problem + attributes: + label: Problem / motivation + description: What are you trying to do, and what is missing or awkward today? + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposed solution + description: Describe the API or behavior you would like. Code sketches welcome. + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives considered + description: Other approaches you evaluated and why they fall short. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..0dcb48b --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,22 @@ +## Summary + + + +## Type of change + +- [ ] Bug fix (non-breaking) +- [ ] New feature (non-breaking) +- [ ] Breaking change +- [ ] Documentation only + +## Checklist + +- [ ] `composer lint` passes +- [ ] `composer test` passes +- [ ] Added/updated tests for the changed behavior +- [ ] Public API preserved, or the break is documented in `CHANGELOG.md` +- [ ] No secrets, credentials, or binaries committed + +## Notes for reviewers + + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..212fdc9 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,47 @@ +name: CI + +on: + push: + branches: ["1.x", "2.x", "main"] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + php: + name: PHP ${{ matrix.php }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ['8.2', '8.3', '8.4'] + steps: + - uses: actions/checkout@v4 + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: mbstring + coverage: none + tools: composer:v2 + - run: composer validate --strict + - run: composer install --prefer-dist --no-interaction --no-progress + - run: composer lint + - run: composer test + + go: + name: Go transport + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.26.x' + cache-dependency-path: src-go/go.sum + - name: Build + working-directory: src-go + run: go build ./... + - name: Vet + working-directory: src-go + run: go vet ./... diff --git a/.gitignore b/.gitignore index 3be0cf4..25b6b42 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ exec/ vendor/ +composer.lock +.phpunit.cache/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..70bf593 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,43 @@ +# Changelog + +All notable changes to this project are documented here. The format is based on +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project aims +to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +> Note: entries for releases before this file was introduced are reconstructed +> from Git tags. Where a tag's exact scope was not recorded in commit history, +> the entry is intentionally conservative rather than inventing detail. + +## [Unreleased] + +### Added +- `LICENSE` file (MIT) matching the license declared in `composer.json`. +- PHPUnit test suite covering `MultipartEncoder`, `PacketBuffer` and + `RequestOptions` transport normalization. +- `CONTRIBUTING.md`, `SECURITY.md`, `CODE_OF_CONDUCT.md`, issue/PR templates. +- GitHub Actions CI (PHP lint + unit tests on PHP 8.2–8.4, Go build/vet). + +### Changed +- `MultipartEncoder::encode()` now validates file readability before reading, + throwing `AstraException` cleanly instead of emitting a raw PHP warning on a + missing or unreadable upload path. + +## [2.0.0] +- Tagged release `v2.0.0`. See Git history for the included commits. + +## [1.3.1] +- Documentation updates. + +## [1.3.0] +- Executable path handling fixes and documentation updates. + +## [1.0.0] +- Initial public release: Go-transport-backed async HTTP client for PHP, + shared worker management, streaming responses, multipart encoding, + TLS fingerprint options, and WebSocket / SSE entry points. + +[Unreleased]: https://github.com/astrahttp/http/compare/v2.0.0...HEAD +[2.0.0]: https://github.com/astrahttp/http/releases/tag/v2.0.0 +[1.3.1]: https://github.com/astrahttp/http/releases/tag/v1.3.1 +[1.3.0]: https://github.com/astrahttp/http/releases/tag/v1.3.0 +[1.0.0]: https://github.com/astrahttp/http/releases/tag/v1.0.0 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..a4353e9 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,35 @@ +# Code of Conduct + +## Our pledge + +We as members, contributors, and maintainers pledge to make participation in +this project a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our standards + +Examples of behavior that contributes to a positive environment: + +- Demonstrating empathy and kindness toward other people. +- Being respectful of differing opinions, viewpoints, and experiences. +- Giving and gracefully accepting constructive feedback. +- Focusing on what is best for the community and the project. + +Unacceptable behavior includes: + +- Harassment, insulting or derogatory comments, and personal or political attacks. +- Public or private harassment. +- Publishing others' private information without explicit permission. +- Other conduct which could reasonably be considered inappropriate. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the maintainer at `ajmalalkhaledi@gmail.com`. All complaints will be +reviewed and investigated promptly and fairly. + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), +version 2.1. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..894053a --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,62 @@ +# Contributing to AstraHTTP + +Thanks for your interest in improving AstraHTTP. This document explains how to +set up the project, run the checks, and submit changes. + +## Project layout + +- `src/` — the PHP library (`Astra\Http` namespace, PSR-4). +- `src-go/` — the Go transport worker that PHP talks to over a local socket. +- `bin/astrahttp` — the installer/entry CLI shipped with the package. +- `tests/` — PHPUnit tests. Unit tests under `tests/` do **not** require a + running Go worker; they exercise pure-PHP units (encoding, buffer parsing, + request-option normalization). + +## Requirements + +- PHP 8.2+ with Composer. +- Go 1.22+ (only if you change the transport in `src-go/`). + +## Getting started + +```bash +git clone https://github.com/astrahttp/http.git +cd http +composer install +``` + +## Running the checks + +```bash +composer lint # php -l across src/ +composer test # PHPUnit unit suite +``` + +For the Go transport: + +```bash +cd src-go +go build ./... +go vet ./... +``` + +## Pull requests + +1. Create a topic branch from the default branch. +2. Keep changes focused; avoid unrelated refactors in the same PR. +3. Add or update tests for behavior you change. New pure-PHP logic should come + with unit tests. +4. Run `composer lint` and `composer test` locally before pushing. +5. Describe the motivation and the user-visible impact in the PR description. +6. Preserve the public API (`Astra\Http\Client`, `RequestOptions`, `Response`) + unless a breaking change is clearly justified and documented in + `CHANGELOG.md`. + +## Reporting bugs and requesting features + +Use the GitHub issue templates. Include PHP version, OS/architecture, a minimal +reproduction, and the actual vs. expected behavior. + +## Security + +Do not open public issues for security problems. See [SECURITY.md](SECURITY.md). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..cc29747 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Ajmal Alkhaledi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..ffd7c1b --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,32 @@ +# Security Policy + +## Supported versions + +Security fixes are provided for the latest released major version. Older +versions may receive fixes at the maintainer's discretion. + +| Version | Supported | +| ------- | --------- | +| 2.x | ✅ | +| < 2.0 | ❌ | + +## Reporting a vulnerability + +Please report security issues **privately**. Do not open a public GitHub issue. + +- Preferred: open a private advisory via GitHub Security Advisories + ("Report a vulnerability" on the repository Security tab). +- Alternatively, email the maintainer at `ajmalalkhaledi@gmail.com` with: + - a description of the issue and its impact, + - a minimal reproduction or proof of concept, + - affected version(s) and environment. + +You can expect an initial acknowledgement within a reasonable time frame. Please +allow time for a fix before any public disclosure. + +## Scope notes + +AstraHTTP exposes transport-level options such as `insecureSkipVerify` and +custom TLS fingerprints. These are powerful and can weaken connection security +if misused; that is expected behavior, not a vulnerability. Reports about the +library enabling such options by explicit user request are out of scope. diff --git a/composer.json b/composer.json index 313877f..5d84866 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "astrahttp/http", - "description": "A high-performance, async-first HTTP client for PHP 8.2+ powered by CycleTLS. Features shared worker management, JA3/JA4 fingerprinting, and full streaming support.", + "description": "Async PHP HTTP client with browser-grade TLS/HTTP fingerprint control (JA3/JA4), backed by a Go transport. Supports HTTP/2, HTTP/3, streaming, WebSockets and SSE.", "keywords": [ "php", "security", @@ -34,11 +34,18 @@ "src/functions.php" ] }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, "autoload-dev": { "psr-4": { "Astra\\Http\\Tests\\": "tests/" } }, + "scripts": { + "test": "phpunit", + "lint": "find src -name '*.php' -print0 | xargs -0 -n1 php -l" + }, "bin": [ "bin/astrahttp" ], diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..bf6fcb5 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,19 @@ + + + + + tests + + + + + src + + + diff --git a/src/MultipartEncoder.php b/src/MultipartEncoder.php index ec75f48..14bb157 100644 --- a/src/MultipartEncoder.php +++ b/src/MultipartEncoder.php @@ -27,9 +27,13 @@ public static function encode(array $fields): array $content = ''; if (isset($value['path'])) { - $content = file_get_contents((string) $value['path']); + $path = (string) $value['path']; + if (!is_file($path) || !is_readable($path)) { + throw new AstraException('Failed to read multipart file: ' . $path); + } + $content = file_get_contents($path); if ($content === false) { - throw new AstraException('Failed to read multipart file: ' . $value['path']); + throw new AstraException('Failed to read multipart file: ' . $path); } } else { $content = (string)($value['content'] ?? ''); diff --git a/tests/MultipartEncoderTest.php b/tests/MultipartEncoderTest.php new file mode 100644 index 0000000..f58ae85 --- /dev/null +++ b/tests/MultipartEncoderTest.php @@ -0,0 +1,100 @@ + 'Ali']); + + self::assertArrayHasKey('Content-Type', $headers); + self::assertStringStartsWith('multipart/form-data; boundary=----AstraHTTPBoundary', $headers['Content-Type']); + + // The declared boundary must actually appear in the body. + $boundary = substr($headers['Content-Type'], strlen('multipart/form-data; boundary=')); + self::assertStringContainsString('--' . $boundary . "\r\n", $body); + self::assertStringEndsWith('--' . $boundary . "--\r\n", $body); + } + + public function testScalarFieldIsEncodedAsFormData(): void + { + [$body] = MultipartEncoder::encode(['name' => 'Ali']); + + self::assertStringContainsString('Content-Disposition: form-data; name="name"', $body); + self::assertStringContainsString("\r\n\r\nAli\r\n", $body); + } + + public function testMultipartMarkerIsNotEmittedAsField(): void + { + [$body] = MultipartEncoder::encode(['_multipart' => true, 'name' => 'Ali']); + + self::assertStringNotContainsString('name="_multipart"', $body); + self::assertStringContainsString('name="name"', $body); + } + + public function testInMemoryFileContentIsEncodedWithFilenameAndMime(): void + { + [$body] = MultipartEncoder::encode([ + 'avatar' => [ + 'filename' => 'avatar.png', + 'mime' => 'image/png', + 'content' => 'BINARYDATA', + ], + ]); + + self::assertStringContainsString('name="avatar"; filename="avatar.png"', $body); + self::assertStringContainsString('Content-Type: image/png', $body); + self::assertStringContainsString("\r\n\r\nBINARYDATA\r\n", $body); + } + + public function testFileFromPathIsRead(): void + { + $tmp = tempnam(sys_get_temp_dir(), 'astra_mp_'); + self::assertIsString($tmp); + file_put_contents($tmp, 'from-disk'); + + try { + [$body] = MultipartEncoder::encode([ + 'doc' => ['path' => $tmp, 'mime' => 'text/plain'], + ]); + + self::assertStringContainsString('filename="' . basename($tmp) . '"', $body); + self::assertStringContainsString("\r\n\r\nfrom-disk\r\n", $body); + } finally { + @unlink($tmp); + } + } + + public function testMissingFileThrows(): void + { + $this->expectException(AstraException::class); + + MultipartEncoder::encode([ + 'doc' => ['path' => '/nonexistent/astra/' . bin2hex(random_bytes(6))], + ]); + } + + public function testQuotesAndNewlinesInFieldNameAreEscaped(): void + { + [$body] = MultipartEncoder::encode(['a"b' . "\r\n" . 'c' => 'v']); + + // Quote escaped, CR/LF stripped — prevents header injection. + self::assertStringContainsString('name="a\\"bc"', $body); + self::assertStringNotContainsString("name=\"a\"b\r\nc\"", $body); + } + + public function testArrayValueIsJsonEncoded(): void + { + [$body] = MultipartEncoder::encode(['meta' => ['k' => 'v']]); + + self::assertStringContainsString('name="meta"', $body); + self::assertStringContainsString('{"k":"v"}', $body); + } +} diff --git a/tests/PacketBufferTest.php b/tests/PacketBufferTest.php new file mode 100644 index 0000000..3dbfc4e --- /dev/null +++ b/tests/PacketBufferTest.php @@ -0,0 +1,71 @@ +readU8()); + self::assertSame(1, $buffer->offset); + } + + public function testReadU16BigEndian(): void + { + $buffer = new PacketBuffer("\x01\x02"); + self::assertSame(258, $buffer->readU16()); + } + + public function testReadU32BigEndian(): void + { + $buffer = new PacketBuffer("\x00\x00\x01\x00"); + self::assertSame(256, $buffer->readU32()); + } + + public function testReadStringUsesU16Length(): void + { + $buffer = new PacketBuffer("\x00\x03abc"); + self::assertSame('abc', $buffer->readString()); + self::assertSame(5, $buffer->offset); + } + + public function testReadStringZeroLengthReturnsEmpty(): void + { + $buffer = new PacketBuffer("\x00\x00"); + self::assertSame('', $buffer->readString()); + } + + public function testReadBytesUsesU32Length(): void + { + $buffer = new PacketBuffer("\x00\x00\x00\x02hi"); + self::assertSame('hi', $buffer->readBytes()); + self::assertSame(6, $buffer->offset); + } + + public function testSequentialReads(): void + { + $buffer = new PacketBuffer("\x07\x00\x02ok"); + self::assertSame(7, $buffer->readU8()); + self::assertSame('ok', $buffer->readString()); + } + + public function testUnderflowThrows(): void + { + $this->expectException(AstraException::class); + (new PacketBuffer(''))->readU8(); + } + + public function testStringUnderflowThrows(): void + { + $this->expectException(AstraException::class); + // Declares length 10 but provides 3 bytes. + (new PacketBuffer("\x00\x0Aabc"))->readString(); + } +} diff --git a/tests/RequestOptionsTest.php b/tests/RequestOptionsTest.php new file mode 100644 index 0000000..e2461ba --- /dev/null +++ b/tests/RequestOptionsTest.php @@ -0,0 +1,134 @@ + 'x', 'timeout' => 5]); + self::assertSame(5, $options->timeout); + self::assertFalse(property_exists($options, 'nonExistentOption')); + } + + public function testTransportArrayDropsNullsAndLocalOnlyFields(): void + { + $options = new RequestOptions([ + 'timeout' => 5, + 'onComplete' => fn () => null, + 'maxRetries' => 3, + 'retryDelayMs' => 500, + 'retryable' => true, + ]); + + $transport = $options->toTransportArray(); + + // Local-only keys must never cross the transport boundary. + self::assertArrayNotHasKey('onComplete', $transport); + self::assertArrayNotHasKey('maxRetries', $transport); + self::assertArrayNotHasKey('retryDelayMs', $transport); + self::assertArrayNotHasKey('retryable', $transport); + + // Null fields are filtered out. + self::assertArrayNotHasKey('ja3', $transport); + + self::assertSame(5, $transport['timeout']); + } + + public function testAssociativeCookiesAreNormalizedToNameValuePairs(): void + { + $options = new RequestOptions(['cookies' => ['session' => 'abc', 'lang' => 'en']]); + $transport = $options->toTransportArray(); + + self::assertSame( + [ + ['name' => 'session', 'value' => 'abc'], + ['name' => 'lang', 'value' => 'en'], + ], + $transport['cookies'] + ); + } + + public function testObjectCookiesAreNormalized(): void + { + $options = new RequestOptions(['cookies' => (object) ['session' => 'abc']]); + $transport = $options->toTransportArray(); + + self::assertSame([['name' => 'session', 'value' => 'abc']], $transport['cookies']); + } + + public function testArrayBodyIsJsonEncodedAndContentTypeAdded(): void + { + $options = new RequestOptions(['body' => ['name' => 'Ali', 'age' => 30]]); + $transport = $options->toTransportArray(); + + self::assertSame('{"name":"Ali","age":30}', $transport['body']); + self::assertSame('application/json; charset=utf-8', $transport['headers']['Content-Type']); + } + + public function testExistingContentTypeIsPreservedForArrayBody(): void + { + $options = new RequestOptions([ + 'headers' => ['Content-Type' => 'application/vnd.api+json'], + 'body' => ['a' => 1], + ]); + $transport = $options->toTransportArray(); + + self::assertSame('application/vnd.api+json', $transport['headers']['Content-Type']); + } + + public function testStringBodyIsPassedThroughUnchanged(): void + { + $options = new RequestOptions(['body' => 'raw-payload']); + $transport = $options->toTransportArray(); + + self::assertSame('raw-payload', $transport['body']); + self::assertArrayNotHasKey('headers', $transport); + } + + public function testStringableBodyIsCastToString(): void + { + $body = new class implements \Stringable { + public function __toString(): string + { + return 'from-object'; + } + }; + + $options = new RequestOptions(['body' => $body]); + $transport = $options->toTransportArray(); + + self::assertSame('from-object', $transport['body']); + } + + public function testMultipartBodyProducesMultipartContentType(): void + { + $options = new RequestOptions([ + 'body' => [ + '_multipart' => true, + 'name' => 'Ali', + ], + ]); + $transport = $options->toTransportArray(); + + self::assertStringStartsWith('multipart/form-data; boundary=', $transport['headers']['Content-Type']); + self::assertStringContainsString('name="name"', $transport['body']); + } + + public function testFileDescriptorBodyIsDetectedAsMultipart(): void + { + $options = new RequestOptions([ + 'body' => [ + 'avatar' => ['filename' => 'a.png', 'mime' => 'image/png', 'content' => 'x'], + ], + ]); + $transport = $options->toTransportArray(); + + self::assertStringStartsWith('multipart/form-data; boundary=', $transport['headers']['Content-Type']); + } +} From ad57066f8cca2a5ef68977858165f701450ac3f4 Mon Sep 17 00:00:00 2001 From: Ajmal Alkhaledi Date: Mon, 2 Nov 2026 17:27:34 +0000 Subject: [PATCH 2/2] fix(go): terminate SSE/WS read loops and avoid context leak (go vet) go vet (added in CI) surfaced real issues in the Go transport: - SSE and WebSocket read loops used `break` inside a `select`, which only breaks the select, not the enclosing `for {}`. The loops never terminated on EOF / normal close / cancellation: a spin after the stream ended and the trailing "end" frame was unreachable (never sent to PHP). Use labeled `break sseLoop` / `break wsLoop` so the loop exits and the end frame is sent. - processRequest created a cancellable context before the protocol dispatch, leaking it on the websocket/sse/http3 early-return paths (which manage their own). Create it only on the default HTTP path that uses it. Fixes: core.go unreachable-code (977, 1176) and lostcancel (132) vet findings. go build ./... passes. Co-Authored-By: Claude Opus 4.8 --- src-go/core.go | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src-go/core.go b/src-go/core.go index bcb0131..15fbb57 100644 --- a/src-go/core.go +++ b/src-go/core.go @@ -129,8 +129,6 @@ var debugLogger = log.New(os.Stdout, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfi // ready Request func processRequest(request cycleTLSRequest) (result fullRequest) { - ctx, cancel := context.WithCancel(context.Background()) - var browser = Browser{ // TLS fingerprinting options JA3: request.Options.Ja3, @@ -169,6 +167,11 @@ func processRequest(request cycleTLSRequest) (result fullRequest) { return dispatchHTTP3Request(request) } + // Only the default HTTP path below uses a cancellable context; the + // protocol-specific handlers above return early and manage their own. + // Creating it here avoids leaking a context on those early-return paths. + ctx, cancel := context.WithCancel(context.Background()) + // Default to true for connection reuse enableConnectionReuse := true if request.Options.EnableConnectionReuse == false { @@ -917,21 +920,22 @@ func dispatchSSEAsync(res fullRequest, chanWrite chan []byte) { } // Read SSE events +sseLoop: for { select { case <-res.req.Context().Done(): debugLogger.Printf("SSE request %s was canceled", res.options.RequestID) - break + break sseLoop default: event, err := sseResp.NextEvent() if err != nil { if err == io.EOF { // Normal end of stream - break + break sseLoop } debugLogger.Printf("SSE read error: %s", err.Error()) - break + break sseLoop } if event == nil { @@ -1121,6 +1125,7 @@ func dispatchWebSocketAsync(res fullRequest, chanWrite chan []byte) { } // Read WebSocket messages +wsLoop: for { select { case <-res.req.Context().Done(): @@ -1132,7 +1137,7 @@ func dispatchWebSocketAsync(res fullRequest, chanWrite chan []byte) { if err != nil { if websocket.IsCloseError(err, websocket.CloseNormalClosure) { // Normal close - break + break wsLoop } debugLogger.Printf("WebSocket read error: %s", err.Error()) return