diff --git a/CHANGELOG.md b/CHANGELOG.md index a6da949..68074fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ All notable changes to this bundle. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow [SemVer](https://semver.org/) and come from the Git tags. +## [0.3.0] - 2026-12-04 + +No action is needed on upgrade: the new client loads only when its library is installed and the adapter `gitlab` is enabled, and there is no migration. + +### Added + +- `Reply\Gitlab\GitlabReplyClient`, which posts answers to GitLab with the reply connection of an endpoint and does nothing else: `replyToDiscussion()` (a reply in an existing discussion of a merge request or an issue), `addNote()` (a new note on a merge request or an issue) and `currentUser()` (the user of the token), returning the value objects `GitlabNote` and `GitlabUser`; `GitlabNoteable` selects merge request or issue. The reply connection is an `ApiConfiguration` of the type `gitlab` with the config keys `base_url` (absolute http(s) root URL without a path) and `token` (encrypted, decrypted with `ConfigSecrets::decrypt()`), a contract with the application's GitLab connection schema; the bundle registers no connection type. Failures are exceptions under `Reply\Gitlab\Exception\` (`GitlabReplyException`: `ReplyConnectionException` before any request, `DiscussionNotFoundException` for 404 and `DiscussionNotRepliableException` for 400 on a reply, `GitlabRequestFailedException` otherwise). Redirects are never followed, the token appears in no exception message or log line, and the client checks no permission: the bot's GitLab role and token scope are the boundary. Built on `m4tthumphrey/php-gitlab-api` over `symfony/http-client`; the library client is not exposed. +- Conditional loading of components on suggested libraries: the client is registered (private, autowired, log channel `webhook`) only when `Gitlab\Client` exists and the adapter `gitlab` is enabled; otherwise nothing of it is in the container. The decision lives in `WebhookBundle::loadsOptionalComponent()`, the library check in `DependencyInjection\OptionalLibraries` (the bundle's new optional constructor argument; marker classes passed to it count as not installed). +- The service id `dmstr_webhook.reply_http_client` (`WebhookBundle::REPLY_HTTP_CLIENT`), the HTTP transport of the reply clients: an alias of FrameworkBundle's `http_client` unless the application defines it itself, e.g. as a `MockHttpClient` in its tests. Without a transport the client is removed and the container still builds (`DependencyInjection\Compiler\RemoveReplyClientsWithoutTransportPass`). +- Suggestions `m4tthumphrey/php-gitlab-api` (`^12.1.1`) and `symfony/http-client`; the library and `nyholm/psr7` are development requirements. `config.allow-plugins` denies `php-http/discovery`, so the library's discovery plugin never runs in this repository. +- Kernel variants of the container test: without the GitLab library, with the adapter `gitlab` disabled, with the host's own reply transport, and without `http_client`; tests of the client against a recording HTTP fake with fixtures in the shape of GitLab 15.11 responses. +- README section on the GitLab reply client. + ## [0.2.1] - 2026-12-03 No action is needed on upgrade: the new adapter is disabled by default, and there is no migration. @@ -129,3 +142,4 @@ Initial public release. + diff --git a/CLAUDE.md b/CLAUDE.md index 28e8621..13a7e1a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,8 +36,10 @@ Replay-window tests build their Standard Webhooks signatures with the time of a - The bundle checks only permissions with `is_granted()`: the constants of `Dmstr\Webhook\Security\WebhookPermissions`, tagged `za7_core.permission` in `config/services.yaml`. No `ROLE_*` name is checked in `src/` or `config/`; the host application maps permissions to roles through its own voter. The tag name `za7_core.permission` stays. A new permission gets a constant, a tag, a test and a README update in the same change. - The bundle never prepends `api_platform.mapping.paths`: API Platform adds the host application's default resource directories only while that list is empty, so a prepended path drops the host's own resources. The bundle's resources are discovered through the registered bundle (`src/Entity`); guarded by `tests/Unit/DependencyInjection/WebhookBundlePrependTest.php` and `tests/Integration/WebhookWiringTest.php`. - Hard requirements stay minimal: monolog, the lock component, the clock component, the security bundle and the audit-log bundle are optional (`suggest`), and the container must build without them; `clock` and `lock.factory` are optional references. +- Components that depend on a suggested package (today `Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient` on `m4tthumphrey/php-gitlab-api`) load only when the package is installed and the matching adapter is enabled: one decision, `WebhookBundle::loadsOptionalComponent()`, with the library check in `DependencyInjection\OptionalLibraries` (never a second `class_exists()` elsewhere). Such classes stay out of resource discovery (`src/Reply/` is excluded in `config/services.yaml`), so the container builds without the package; their HTTP transport is the service `dmstr_webhook.reply_http_client`, and without one they are removed. `tests/Integration/ContainerVariantsTest.php` proves it (package absent through `new OptionalLibraries([...])` in the test kernel, adapter off, adapter on, no `http_client`); a new optional component adds its variants there. - Secrets never appear in responses (only the mask `********`), exception messages, console output or logs; the payload of an event is in no serialization group. No text of a source object (e.g. a note body) enters the event context, route variables or log lines; it stays in the stored payload. + diff --git a/README.md b/README.md index a3ddd8c..e43c8d2 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Symfony bundle for incoming webhooks. Each source gets an endpoint under its own - [Routes](#routes) - [Delivery handlers](#delivery-handlers) - [Adapters](#adapters) +- [GitLab reply client](#gitlab-reply-client) - [Events](#events) - [Audit and logging](#audit-and-logging) - [Log redaction](#log-redaction) @@ -40,6 +41,7 @@ Symfony bundle for incoming webhooks. Each source gets an endpoint under its own - `gedmo/doctrine-extensions` (endpoints and routes are `Loggable`); changes are audited when the application registers a loggable listener, for example through `dmstr/doctrine-audit-log-bundle` - `symfony/security-bundle` for the firewall of the intake and the `is_granted()` checks of the admin API - a permission voter that decides the permission strings of the bundle (see [Permissions](#permissions)) +- optional, for the [GitLab reply client](#gitlab-reply-client) only: `m4tthumphrey/php-gitlab-api` (`^12.1.1`), `symfony/http-client` and a PSR-17 implementation such as `nyholm/psr7`; all three are suggestions, not requirements The bundle requires neither a process engine nor a specific platform bundle; a reference to a process engine is only a connection record, and a route names its process by a definition key. @@ -560,6 +562,58 @@ No text of a delivery (titles, content, `details`, names other than the actor's +## GitLab reply client + +`Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient` posts answers to GitLab with the reply connection of an endpoint (`replyConnection`), for example the answer of a process to the note that mentioned the bot. It does exactly three things and nothing else: + +| Method | GitLab API | Returns | +| --- | --- | --- | +| `replyToDiscussion(WebhookEndpoint $endpoint, GitlabNoteable $noteable, int\|string $projectId, int $iid, string $discussionId, string $body)` | `POST /projects/:id/merge_requests/:iid/discussions/:discussion_id/notes` or the same under `issues` | `GitlabNote` | +| `addNote(WebhookEndpoint $endpoint, GitlabNoteable $noteable, int\|string $projectId, int $iid, string $body)` | `POST /projects/:id/merge_requests/:iid/notes` or the same under `issues` | `GitlabNote` | +| `currentUser(WebhookEndpoint $endpoint)` | `GET /user` | `GitlabUser` (id, username, name, bot flag) | + +`GitlabNoteable` is `MergeRequest` or `Issue`; `$projectId` is the numeric id or the full path of the project. The [GitLab adapter](#gitlab) reports what a reply needs in its event context: the project, the target `iid` and the discussion. `GitlabNote` carries the note id, its type, the author's id and username, the noteable type and `iid` and the creation time, never the body. `currentUser()` tells which GitLab user the token belongs to, e.g. to compare it with the endpoint's `actorId`. + +**Packages.** The client is built on `m4tthumphrey/php-gitlab-api` (`^12.1.1`) over `symfony/http-client` (through its `Psr18Client`, which is also the PSR-17 factory the library is given); the library itself requires a PSR-17 implementation such as `nyholm/psr7`. All three are suggestions of the bundle, not requirements; install them in the application to use the client: + +```bash +composer require m4tthumphrey/php-gitlab-api:^12.1.1 symfony/http-client nyholm/psr7 +``` + +**Registration.** The service `Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient` (private, autowired, inject it by its class) exists only when both hold: the library is installed (the class `Gitlab\Client` exists) and the adapter `gitlab` is enabled (`dmstr_webhook.adapters.gitlab: true`). Otherwise nothing of it is registered and the container builds as without it. A service of the application that should work either way takes `?GitlabReplyClient $replyClient = null`. + +**HTTP transport.** The client sends its requests through the service `dmstr_webhook.reply_http_client` (`WebhookBundle::REPLY_HTTP_CLIENT`), which the bundle defines as an alias of FrameworkBundle's `http_client`. Without `http_client` (no `symfony/http-client`, or `framework.http_client.enabled: false`) and without an own definition of `dmstr_webhook.reply_http_client`, the client is removed from the container, which still builds. To replace the transport, for example in an end-to-end test of the application, define the service id yourself; the application's definition wins over the bundle's alias: + +```yaml +# config/services.yaml +when@test: + services: + dmstr_webhook.reply_http_client: + class: Symfony\Component\HttpClient\MockHttpClient + arguments: ['@App\Tests\GitlabResponses'] # a callable that answers each request +``` + +**Connection contract.** The endpoint's `replyConnection` is an `ApiConfiguration` of `dmstr/api-configuration-bundle` with the `type` `gitlab` and two config keys: `base_url`, the GitLab root URL as an absolute `http` or `https` URL without a path, query or credentials (`https://gitlab.example.com`, a trailing slash is fine; the library appends `/api/v4/…` to the host, so a path prefix would be dropped), and `token`, the access token of the bot user, stored encrypted and decrypted with `ConfigSecrets::decrypt()` only for the request. This is a contract with the GitLab connection schema of the application: the bundle registers no connection type and no schema of its own, so the application's schema for the type `gitlab` must provide these keys and mark `token` as `writeOnly`. + +**Errors.** Every failure is an exception under `Dmstr\Webhook\Reply\Gitlab\Exception\`, all extending `GitlabReplyException`: + +| Exception | When | +| --- | --- | +| `ReplyConnectionException` | the endpoint has no reply connection, it is not of the type `gitlab`, `base_url` is missing or not an absolute http(s) root URL, or `token` is missing or empty; no request is sent | +| `DiscussionNotFoundException` | `replyToDiscussion()`: GitLab answered 404 (no such project, target or discussion, or the token cannot see it) | +| `DiscussionNotRepliableException` | `replyToDiscussion()`: GitLab answered 400 (the discussion takes no replies) | +| `GitlabRequestFailedException` | every other failure: another HTTP status (`getStatusCode()`), a redirect, a transport error (status null) or a response of an unexpected shape | + +No exception of the library or the HTTP client is chained; a message names the operation, the status and at most GitLab's shortened error text, with the token masked if GitLab echoed it. + +**No redirects.** Neither the HTTP client (`max_redirects: 0`) nor the library (its redirect plugin is removed) follows a redirect, so a request and its token never go to another host; a 3xx answer fails with `GitlabRequestFailedException`. + +**No permission checks.** The client checks no permission and no role. What it may do is bounded by the bot's role in the GitLab project and the scope of its token (`api` for notes); give the bot user only the projects and the role it needs. The caller decides whether an answer is due. + +**Logging.** Each request writes one `info` line (success) or one `warning` line (failure) on the channel `webhook` with the operation, the endpoint id, the noteable type, the project, the `iid` and the HTTP status; never the token, the base URL or the note body. + +**Not a model tool.** The client is deterministic code for the application's process steps: the application decides what to post where. Do not offer it, or a wrapper that passes model output into its arguments, as a tool to a language model; a model that can choose the project, target and body could post anywhere the bot's token reaches. + ## Events `/api/admin/webhook_events` (GET collection, GET), permission `webhook:event:read`, read-only, newest first, filters `endpoint`, `status`, `type` and `dedupeKey`. @@ -896,7 +950,7 @@ Rules for an adapter: ## Not built yet - Starting the process of a `routed` event (the statuses `started` and `completed`, and the event fields `processInstanceId`, `replyReference` and `error`): the bundle stops at `routed`. -- A client that answers in the source (e.g. a GitLab note in the thread of a mention); the GitLab adapter only reports the references such a client needs (project, target `iid`, discussion). +- Answering in the source on its own: the bundle ships the [GitLab reply client](#gitlab-reply-client), but nothing in the bundle calls it; the application decides when to answer. - A detail view of an event with its payload. - A retention purge of old events. - Re-delivery of events that stayed `received` (a lost hand-over or a missing handler). @@ -906,7 +960,7 @@ Rules for an adapter: The PHPUnit suites live in this repository (configuration `./phpunit.dist.xml`, PHPUnit 12 or 13): - `unit` (`./tests/Unit`): no kernel, no database; the intake, the filters, the limiters, the router, the adapters, the console twins and the container wiring against stubs and in-memory doubles (`./tests/Support`). -- `integration` (`./tests/Integration`): boots the test kernel `./tests/Kernel/TestKernel.php`, a minimal host application with the dependency bundles, header-based test authentication (`X-Test-User`, `X-Test-Roles`) with neutral test roles (`./tests/Kernel/TestRoles.php`, `ROLE_WEBHOOK_ADMIN`) and a test permission voter that maps the bundle's permissions to them, a frozen `clock` (`MockClock`) for the Standard Webhooks replay window, test adapters with an event context, and the log channels `webhook` and `request` in a test log file. Kernel variants cover a host without the `clock` service, without a lock factory and without MonologBundle. Tests in the group `database` need PostgreSQL or MySQL 8 from `DATABASE_URL` (PostgreSQL by default in `phpunit.dist.xml`; the database name must end with `_test`, because one test drops every table); `./tests/Kernel/TestDatabase.php` creates the schema once per process by running all registered migrations, the bundle's own ones included, and one test runs them on an empty database to prove their order. The same tests run on both platforms; the few statements that cannot be portable branch on the DBAL platform. +- `integration` (`./tests/Integration`): boots the test kernel `./tests/Kernel/TestKernel.php`, a minimal host application with the dependency bundles, header-based test authentication (`X-Test-User`, `X-Test-Roles`) with neutral test roles (`./tests/Kernel/TestRoles.php`, `ROLE_WEBHOOK_ADMIN`) and a test permission voter that maps the bundle's permissions to them, a frozen `clock` (`MockClock`) for the Standard Webhooks replay window, test adapters with an event context, and the log channels `webhook` and `request` in a test log file. Kernel variants cover a host without the `clock` service, without a lock factory, MonologBundle and `http_client`, and the GitLab reply client without its library (simulated by building the bundle with `new OptionalLibraries([Gitlab\Client::class])`), with the adapter `gitlab` disabled, enabled, and with the host's own reply transport. Tests in the group `database` need PostgreSQL or MySQL 8 from `DATABASE_URL` (PostgreSQL by default in `phpunit.dist.xml`; the database name must end with `_test`, because one test drops every table); `./tests/Kernel/TestDatabase.php` creates the schema once per process by running all registered migrations, the bundle's own ones included, and one test runs them on an empty database to prove their order. The same tests run on both platforms; the few statements that cannot be portable branch on the DBAL platform. The intake is covered by a data-driven matrix: each row (`./tests/Support/IntakeCase.php`) is an endpoint configuration, one request and the expected status, reason, route and hand-over in each mode (`./tests/Support/IntakeExpectation.php`). `./tests/Support/IntakeHarness.php` runs a row without kernel and database (the real intake over an in-memory store), the group `database` runs the same rows against the database. The source-neutral rows (`./tests/Support/IntakeMatrix.php`) use the test adapters `./tests/Kernel/ContextTestAdapter.php` (context from the JSON body), `./tests/Kernel/ActorlessTestAdapter.php` (a source without actor and facts) and `./tests/Kernel/FilterAttributesTestAdapter.php` (one declared attribute of each kind). A source adapter with fixtures adds its rows in its own data provider with the same row shape. Its fixtures are YAML files under `./tests/Fixtures//`, one delivery per file with `origin`, `headers` and `body`, loaded through `./tests/Support/FixtureSet.php`; `origin` is `captured` (a recorded delivery with neutral values), `documented ()` (built from the source's documentation, every value invented, for a source without recorded deliveries) or `derived from ()` (single values of another fixture of the same source changed). `./tests/Support/FixtureMatrix.php` turns fixtures into rows with the source's default endpoint and, for a path secret source, the secret path segment of every request; the traits `./tests/Support/FixtureSequenceTests.php` and `./tests/Support/IntakeHarnessSequences.php` run a source's sequences (several deliveries to one endpoint, then the event rows in order) without database, and `./tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php` runs them against the database. Two sources have fixtures: GitLab (`./tests/Support/GitlabFixtures.php`, `./tests/Support/GitlabMatrix.php`), whose fixtures are captured GitLab 15.11 deliveries with neutral values or derived from them, and Basecamp 4 (`./tests/Support/Basecamp4Fixtures.php`, `./tests/Support/Basecamp4Matrix.php`), whose fixtures are all documented or derived, none captured. `./tests/Unit/Fixtures/FixtureAnonymisationTest.php` guards the anonymisation with one definition per source: structural rules on every fixture (only the source's `example.com` hosts, no redaction placeholders, no avatar service, ASCII only, a valid `origin`, the source's headers with fixture values only), and, when the source's environment variable points to a local directory of raw captures (never committed; `WEBHOOK_RAW_CAPTURES_DIR` for GitLab, `WEBHOOK_RAW_CAPTURES_DIR_BASECAMP4` for Basecamp 4), a check that no value of those captures occurs in any fixture of any source; without the variable that check is skipped. `./tests/Unit/Intake/Basecamp4LogTest.php` runs Basecamp 4 deliveries through the intake with a logger without the redaction processor and fails if a raw log record carries the secret path segment, the request path or any text of the payload; a deliberately leaking test adapter proves that the check detects a leak. @@ -934,3 +988,4 @@ MIT, see [LICENSE](LICENSE). + diff --git a/composer.json b/composer.json index 24d8d8a..21f6fc9 100644 --- a/composer.json +++ b/composer.json @@ -52,7 +52,9 @@ "ext-pdo_pgsql": "*", "dmstr/doctrine-audit-log-bundle": "^0.4", "dmstr/openapi-json-schema-bundle": "^0.5", + "m4tthumphrey/php-gitlab-api": "^12.1.1", "monolog/monolog": "^3.0", + "nyholm/psr7": "^1.8", "phpunit/phpunit": "^12.0 || ^13.0", "symfony/browser-kit": "^7.4", "symfony/clock": "^7.4", @@ -65,9 +67,11 @@ }, "suggest": { "dmstr/doctrine-audit-log-bundle": "Provides a Gedmo loggable listener and log entry entity, so every endpoint change (including each secret rotation as a timestamp) is recorded with its actor.", + "m4tthumphrey/php-gitlab-api": "Version 12.1.1 or later is needed by `Dmstr\\Webhook\\Reply\\Gitlab\\GitlabReplyClient`, which posts replies and notes on merge requests and issues through the GitLab reply connection of an endpoint; it also needs `symfony/http-client` and a PSR-17 implementation such as `nyholm/psr7`.", "monolog/monolog": "Version 3 is needed by `Dmstr\\Webhook\\Log\\WebhookSecretRedactionProcessor`, which masks webhook secrets in every log record where MonologBundle registers it.", "symfony/cache": "Provides the cache pool `cache.rate_limiter` of FrameworkBundle, which holds the sliding-window counters of the endpoint rate limit (FrameworkBundle installs it; use a shared adapter such as Redis when several PHP containers serve the intake).", "symfony/clock": "Registers the `clock` service of FrameworkBundle, which the Standard Webhooks adapter then uses for its replay window (system time without it); tests freeze it with `MockClock`.", + "symfony/http-client": "Provides the HTTP transport of the GitLab reply client (through its `Psr18Client`); tests replace it with `MockHttpClient`.", "symfony/lock": "Lets the endpoint rate limiter lock its sliding window, so concurrent deliveries of one endpoint do not overshoot the limit.", "symfony/monolog-bundle": "Registers the log channel `webhook` the bundle writes rejected deliveries and failed hand-offs to, and the secret redaction processor.", "symfony/security-bundle": "Provides the firewall the intake needs and the `is_granted()` checks of the admin API resources." @@ -83,6 +87,9 @@ } }, "config": { - "sort-packages": true + "sort-packages": true, + "allow-plugins": { + "php-http/discovery": false + } } } diff --git a/config/services.yaml b/config/services.yaml index 47cba2f..d4f153f 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -42,6 +42,9 @@ services: - '../src/Intake/AcceptedDelivery.php' - '../src/Intake/IntakeOutcome.php' - '../src/Intake/RejectionReason.php' + # Reply clients on optional libraries (e.g. m4tthumphrey/php-gitlab-api); + # registered by WebhookBundle only when their library is installed. + - '../src/Reply/' # Sliding-window counters of the endpoint rate limit, in the cache pool # `cache.rate_limiter` of FrameworkBundle (configure a shared adapter such @@ -81,3 +84,4 @@ services: # - revised 2026-12-03 (adapter contract: src/Model/ excluded from discovery) # - revised 2026-12-03 (route filters constraint excluded from discovery) # - revised 2026-12-03 (GitLab adapter: mention helper excluded from discovery) +# - revised 2026-12-04 (GitLab reply client: src/Reply/ excluded from discovery) diff --git a/src/DependencyInjection/Compiler/RemoveReplyClientsWithoutTransportPass.php b/src/DependencyInjection/Compiler/RemoveReplyClientsWithoutTransportPass.php new file mode 100644 index 0000000..1850e06 --- /dev/null +++ b/src/DependencyInjection/Compiler/RemoveReplyClientsWithoutTransportPass.php @@ -0,0 +1,61 @@ +has(WebhookBundle::REPLY_HTTP_CLIENT) || self::resolves($container, WebhookBundle::REPLY_HTTP_CLIENT)) { + return; + } + + $removed = [WebhookBundle::REPLY_HTTP_CLIENT => true]; + $container->removeAlias(WebhookBundle::REPLY_HTTP_CLIENT); + foreach (self::CLIENTS as $id) { + if ($container->hasDefinition($id)) { + $container->removeDefinition($id); + $removed[$id] = true; + } + } + + foreach ($container->getAliases() as $aliasId => $alias) { + if (isset($removed[(string) $alias])) { + $container->removeAlias($aliasId); + } + } + } + + private static function resolves(ContainerBuilder $container, string $id): bool + { + $seen = []; + while ($container->hasAlias($id) && !isset($seen[$id])) { + $seen[$id] = true; + $id = (string) $container->getAlias($id); + } + + return $container->hasDefinition($id); + } +} diff --git a/src/DependencyInjection/OptionalLibraries.php b/src/DependencyInjection/OptionalLibraries.php new file mode 100644 index 0000000..c36bc2c --- /dev/null +++ b/src/DependencyInjection/OptionalLibraries.php @@ -0,0 +1,36 @@ + $ignored marker classes to treat as not installed + */ + public function __construct( + private array $ignored = [], + ) { + } + + /** + * @param class-string $markerClass a class of the library + */ + public function installed(string $markerClass): bool + { + return !\in_array($markerClass, $this->ignored, true) && class_exists($markerClass); + } +} diff --git a/src/Reply/Gitlab/Exception/DiscussionNotFoundException.php b/src/Reply/Gitlab/Exception/DiscussionNotFoundException.php new file mode 100644 index 0000000..57bf4da --- /dev/null +++ b/src/Reply/Gitlab/Exception/DiscussionNotFoundException.php @@ -0,0 +1,15 @@ +toRfc4122())); + } + + public static function wrongType(Uuid $connectionId, string $type, string $expected): self + { + return new self(\sprintf('Reply connection %s has the type "%s", expected "%s".', $connectionId->toRfc4122(), $type, $expected)); + } + + public static function missingBaseUrl(Uuid $connectionId): self + { + return new self(\sprintf('Reply connection %s has no "base_url".', $connectionId->toRfc4122())); + } + + public static function invalidBaseUrl(Uuid $connectionId): self + { + return new self(\sprintf('The "base_url" of reply connection %s must be an absolute http or https URL of the GitLab root, without path, query, fragment or credentials.', $connectionId->toRfc4122())); + } + + public static function missingToken(Uuid $connectionId): self + { + return new self(\sprintf('Reply connection %s has no "token" or an empty one.', $connectionId->toRfc4122())); + } +} diff --git a/src/Reply/Gitlab/GitlabNote.php b/src/Reply/Gitlab/GitlabNote.php new file mode 100644 index 0000000..7b4b1b4 --- /dev/null +++ b/src/Reply/Gitlab/GitlabNote.php @@ -0,0 +1,30 @@ +/:iid/…`). + */ +enum GitlabNoteable: string +{ + case MergeRequest = 'merge_requests'; + case Issue = 'issues'; +} diff --git a/src/Reply/Gitlab/GitlabReplyClient.php b/src/Reply/Gitlab/GitlabReplyClient.php new file mode 100644 index 0000000..3cfd53e --- /dev/null +++ b/src/Reply/Gitlab/GitlabReplyClient.php @@ -0,0 +1,299 @@ +httpClient = $httpClient->withOptions(['max_redirects' => 0]); + } + + /** + * Replies in an existing discussion of a merge request or an issue + * (`POST /projects/:id//:iid/discussions/:discussion_id/notes`); + * a single note without a thread (`individual_note`) is turned into a + * thread by GitLab. + * + * @param int|string $projectId the numeric id or the full path of the project + * + * @throws ReplyConnectionException the reply connection is missing or unusable (no request sent) + * @throws DiscussionNotFoundException GitLab answered 404 + * @throws DiscussionNotRepliableException GitLab answered 400 + * @throws GitlabRequestFailedException any other failure + */ + public function replyToDiscussion(WebhookEndpoint $endpoint, GitlabNoteable $noteable, int|string $projectId, int $iid, string $discussionId, string $body): GitlabNote + { + return $this->postNote($endpoint, $noteable, $projectId, $iid, $discussionId, $body); + } + + /** + * Adds a new note to a merge request or an issue + * (`POST /projects/:id//:iid/notes`). + * + * @param int|string $projectId the numeric id or the full path of the project + * + * @throws ReplyConnectionException the reply connection is missing or unusable (no request sent) + * @throws GitlabRequestFailedException any failure of the request + */ + public function addNote(WebhookEndpoint $endpoint, GitlabNoteable $noteable, int|string $projectId, int $iid, string $body): GitlabNote + { + return $this->postNote($endpoint, $noteable, $projectId, $iid, null, $body); + } + + /** + * The user of the reply connection's token (`GET /user`). + * + * @throws ReplyConnectionException the reply connection is missing or unusable (no request sent) + * @throws GitlabRequestFailedException any failure of the request + */ + public function currentUser(WebhookEndpoint $endpoint): GitlabUser + { + $user = $this->send($endpoint, 'current_user', [], static fn (Client $client): mixed => $client->users()->me()); + + $id = $user['id'] ?? null; + $username = $user['username'] ?? null; + if (!\is_int($id) || !\is_string($username)) { + throw self::unexpectedResponse('current_user'); + } + + return new GitlabUser($id, $username, \is_string($user['name'] ?? null) ? $user['name'] : $username, true === ($user['bot'] ?? false)); + } + + /** + * The one path of a reply ($discussionId set) and a new note (null), for + * merge requests and issues alike. + */ + private function postNote(WebhookEndpoint $endpoint, GitlabNoteable $noteable, int|string $projectId, int $iid, ?string $discussionId, string $body): GitlabNote + { + $operation = null === $discussionId ? 'add_note' : 'reply_to_discussion'; + $context = ['noteable' => $noteable->value, 'project' => $projectId, 'iid' => $iid]; + $note = $this->send($endpoint, $operation, $context, static function (Client $client) use ($noteable, $projectId, $iid, $discussionId, $body): mixed { + $api = self::api($client, $noteable); + + return null === $discussionId + ? $api->addNote($projectId, $iid, $body) + : $api->addDiscussionNote($projectId, $iid, $discussionId, $body); + }); + + $id = $note['id'] ?? null; + $author = $note['author'] ?? null; + if (!\is_int($id) || !\is_array($author) || !\is_int($author['id'] ?? null) || !\is_string($author['username'] ?? null)) { + throw self::unexpectedResponse($operation); + } + + return new GitlabNote( + $id, + \is_string($note['type'] ?? null) ? $note['type'] : null, + $author['id'], + $author['username'], + \is_string($note['noteable_type'] ?? null) ? $note['noteable_type'] : '', + \is_int($note['noteable_iid'] ?? null) ? $note['noteable_iid'] : null, + \is_string($note['created_at'] ?? null) ? $note['created_at'] : null, + ); + } + + private static function api(Client $client, GitlabNoteable $noteable): MergeRequests|Issues + { + return match ($noteable) { + GitlabNoteable::MergeRequest => $client->mergeRequests(), + GitlabNoteable::Issue => $client->issues(), + }; + } + + /** + * Resolves the connection (before any request), sends one request through + * a fresh library client and turns every failure into an own exception. + * + * @param array $context log context of the operation + * @param \Closure(Client): mixed $request + * + * @return array the decoded JSON object of a 2xx response + */ + private function send(WebhookEndpoint $endpoint, string $operation, array $context, \Closure $request): array + { + [$baseUrl, $token] = $this->connection($endpoint); + $client = $this->client($baseUrl, $token); + $context = ['operation' => $operation, 'endpoint' => $endpoint->getId()->toRfc4122()] + $context; + + try { + $result = $request($client); + } catch (GitlabException $e) { + $status = $client->getLastResponse()?->getStatusCode() ?? (\is_int($e->getCode()) && $e->getCode() >= 100 ? $e->getCode() : null); + throw $this->failed($operation, $status, self::redact($e->getMessage(), $token), $context); + } catch (ClientExceptionInterface) { + throw $this->failed($operation, null, 'no response (transport error)', $context); + } + + $status = $client->getLastResponse()?->getStatusCode(); + if (null === $status || $status < 200 || $status >= 300) { + throw $this->failed($operation, $status, null !== $status && $status >= 300 && $status < 400 ? 'redirect not followed' : 'unexpected status', $context); + } + if (!\is_array($result)) { + throw $this->failed($operation, $status, 'the response is not a JSON object', $context); + } + + $this->webhookLogger?->info('GitLab reply client: {operation} answered with HTTP {status}.', $context + ['status' => $status]); + + return $result; + } + + /** + * The GitLab root URL and the plain token of the endpoint's reply + * connection. + * + * @return array{string, string} + */ + private function connection(WebhookEndpoint $endpoint): array + { + $connection = $endpoint->getReplyConnection() ?? throw ReplyConnectionException::missing($endpoint->getId()); + $config = $connection->getConfigJson(); + + $type = ConfigSecrets::typeOf($config); + if (self::CONNECTION_TYPE !== $type) { + throw ReplyConnectionException::wrongType($connection->getId(), $type, self::CONNECTION_TYPE); + } + + $baseUrl = $config[self::BASE_URL_KEY] ?? null; + if (!\is_string($baseUrl) || '' === trim($baseUrl)) { + throw ReplyConnectionException::missingBaseUrl($connection->getId()); + } + $baseUrl = self::rootUrl($baseUrl) ?? throw ReplyConnectionException::invalidBaseUrl($connection->getId()); + + if (!\is_string($config[self::TOKEN_KEY] ?? null) || '' === $config[self::TOKEN_KEY]) { + throw ReplyConnectionException::missingToken($connection->getId()); + } + $token = $this->configSecrets->decrypt([self::TOKEN_KEY => $config[self::TOKEN_KEY]])[self::TOKEN_KEY] ?? null; + if (!\is_string($token) || '' === trim($token)) { + throw ReplyConnectionException::missingToken($connection->getId()); + } + + return [$baseUrl, $token]; + } + + /** + * `scheme://host[:port]` of an absolute http(s) URL without path (a + * trailing slash is fine), query, fragment or credentials; null otherwise. + * The library puts `/api/v4/…` on the host only, so a path prefix would + * be dropped silently. + */ + private static function rootUrl(string $url): ?string + { + $parts = parse_url(trim($url)); + if (false === $parts || !isset($parts['scheme'], $parts['host']) || !\in_array(strtolower($parts['scheme']), ['http', 'https'], true)) { + return null; + } + if (isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment']) || !\in_array($parts['path'] ?? '', ['', '/'], true)) { + return null; + } + + return strtolower($parts['scheme']).'://'.$parts['host'].(isset($parts['port']) ? ':'.$parts['port'] : ''); + } + + private function client(string $baseUrl, #[\SensitiveParameter] string $token): Client + { + // The Psr18Client is also the PSR-17 request, stream and URI factory, + // so the library needs no discovery. + $psr18 = new Psr18Client($this->httpClient); + $builder = new Builder($psr18, $psr18, $psr18, $psr18); + $client = new Client($builder); + // The library follows redirects through this plugin; a redirect must + // not take the request (or its body) to another host. + $builder->removePlugin(RedirectPlugin::class); + $client->setUrl($baseUrl); + $client->authenticate($token, Client::AUTH_HTTP_TOKEN); + + return $client; + } + + /** + * @param array $context + */ + private function failed(string $operation, ?int $status, string $reason, array $context): GitlabRequestFailedException + { + $this->webhookLogger?->warning('GitLab reply client: {operation} failed with HTTP {status}.', $context + ['status' => $status ?? 'none']); + + $message = null === $status + ? \sprintf('GitLab request "%s" failed: %s.', $operation, $reason) + : \sprintf('GitLab request "%s" failed with HTTP %d: %s.', $operation, $status, $reason); + + return match (true) { + 'reply_to_discussion' === $operation && 404 === $status => new DiscussionNotFoundException($message, $status), + 'reply_to_discussion' === $operation && 400 === $status => new DiscussionNotRepliableException($message, $status), + default => new GitlabRequestFailedException($message, $status), + }; + } + + private static function unexpectedResponse(string $operation): GitlabRequestFailedException + { + return new GitlabRequestFailedException(\sprintf('GitLab request "%s" returned a response of an unexpected shape.', $operation)); + } + + /** GitLab's error message without the token, shortened. */ + private static function redact(string $message, #[\SensitiveParameter] string $token): string + { + $message = str_replace($token, self::MASK, rtrim(trim($message), '.')); + + return \strlen($message) > self::MAX_MESSAGE_LENGTH ? substr($message, 0, self::MAX_MESSAGE_LENGTH).'...' : $message; + } +} diff --git a/src/Reply/Gitlab/GitlabUser.php b/src/Reply/Gitlab/GitlabUser.php new file mode 100644 index 0000000..7d29e1e --- /dev/null +++ b/src/Reply/Gitlab/GitlabUser.php @@ -0,0 +1,22 @@ + enabled flag; `passthrough` is enabled @@ -69,9 +83,22 @@ final class WebhookBundle extends AbstractBundle /** Hard upper bound of every body cap: the request body limit of the reverse proxy. */ public const int MAX_BODY_CAP = 1048576; public const int DEFAULT_RATE_LIMIT = 60; + /** + * Service id of the HTTP transport of the reply clients: an alias of + * FrameworkBundle's `http_client` unless the host defines this id itself. + */ + public const string REPLY_HTTP_CLIENT = 'dmstr_webhook.reply_http_client'; protected string $extensionAlias = 'dmstr_webhook'; + /** + * @param OptionalLibraries $optionalLibraries decides which suggested libraries count as installed + */ + public function __construct( + private readonly OptionalLibraries $optionalLibraries = new OptionalLibraries(), + ) { + } + public function configure(DefinitionConfigurator $definition): void { $definition->rootNode() @@ -140,10 +167,11 @@ public function loadExtension(array $config, ContainerConfigurator $container, C { $adapters = $config['adapters'] + [self::DEFAULT_ADAPTER => true]; ksort($adapters); + $enabledAdapters = array_keys(array_filter($adapters)); $container->parameters() ->set('dmstr_webhook.adapters', $adapters) - ->set('dmstr_webhook.enabled_adapters', array_keys(array_filter($adapters))) + ->set('dmstr_webhook.enabled_adapters', $enabledAdapters) ->set('dmstr_webhook.body_cap', $config['body_cap']) ->set('dmstr_webhook.rate_limit', $config['rate_limit']); @@ -158,6 +186,30 @@ static function (ChildDefinition $definition, AsWebhookAdapter $attribute): void ->addTag(self::DELIVERY_HANDLER_TAG); $container->import(__DIR__.'/../config/services.yaml'); + + if ($this->loadsOptionalComponent(GitlabClient::class, GitlabParser::SOURCE, $enabledAdapters)) { + $services = $container->services(); + $services->alias(self::REPLY_HTTP_CLIENT, 'http_client'); + // Autowired: ConfigSecrets, and the channel `webhook` as + // `LoggerInterface $webhookLogger` like every bundle service. + $services->set(GitlabReplyClient::class) + ->autowire() + ->arg('$httpClient', service(self::REPLY_HTTP_CLIENT)); + } + } + + /** + * The one decision for components that depend on a suggested library + * (excluded from resource discovery in config/services.yaml): they load + * only when the library is installed and the adapter of their source is + * enabled, so a disabled adapter registers nothing. + * + * @param class-string $libraryMarkerClass a class of the suggested library + * @param list $enabledAdapters + */ + private function loadsOptionalComponent(string $libraryMarkerClass, string $adapter, array $enabledAdapters): bool + { + return \in_array($adapter, $enabledAdapters, true) && $this->optionalLibraries->installed($libraryMarkerClass); } public function build(ContainerBuilder $container): void @@ -167,6 +219,9 @@ public function build(ContainerBuilder $container): void // After the attribute autoconfiguration (priority 100), before the // tagged iterators and locators are resolved (optimization passes). $container->addCompilerPass(new RemoveDisabledAdaptersPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 0); + // After the extensions are loaded (FrameworkBundle's `http_client` + // included), before references are checked. + $container->addCompilerPass(new RemoveReplyClientsWithoutTransportPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 0); } } @@ -174,3 +229,4 @@ public function build(ContainerBuilder $container): void // - revised 2026-12-01 (no api_platform.mapping.paths prepend, host defaults stay) // - revised 2026-12-03 (GitLab adapter in the class doc) // - revised 2026-12-03 (Basecamp 4 adapter in the class doc) +// - revised 2026-12-04 (GitLab reply client: conditional registration, reply transport) diff --git a/tests/Fixtures/gitlab-reply/current-user.yaml b/tests/Fixtures/gitlab-reply/current-user.yaml new file mode 100644 index 0000000..509a0bb --- /dev/null +++ b/tests/Fixtures/gitlab-reply/current-user.yaml @@ -0,0 +1,46 @@ +# file generated with AI assistance: Claude Code - 2026-12-04 16:36:53 UTC +# GitLab 15.11 REST API response, documented: GET /user, 200 OK: the user of a project access token, a bot (lib/api/users.rb, lib/api/entities/user_public.rb) +origin: 'documented (GitLab v15.11.0 REST API documentation and source code, not captured)' +headers: + Content-Type: 'application/json' +body: | + { + "id": 900, + "username": "agent-example", + "name": "Agent Example", + "state": "active", + "avatar_url": "https://gitlab.example.com/uploads/-/system/user/avatar/900/avatar.png", + "web_url": "https://gitlab.example.com/agent-example", + "created_at": "2026-11-01T08:00:00.000Z", + "bio": "", + "location": "", + "public_email": null, + "skype": "", + "linkedin": "", + "twitter": "", + "website_url": "", + "organization": "", + "job_title": "", + "pronouns": null, + "bot": true, + "work_information": null, + "followers": 0, + "following": 0, + "is_followed": false, + "local_time": null, + "last_sign_in_at": null, + "confirmed_at": "2026-11-01T08:00:00.000Z", + "last_activity_on": "2026-12-04", + "email": "agent-example@example.com", + "theme_id": 1, + "color_scheme_id": 1, + "projects_limit": 0, + "current_sign_in_at": null, + "identities": [], + "can_create_group": false, + "can_create_project": false, + "two_factor_enabled": false, + "external": false, + "private_profile": false, + "commit_email": "agent-example@example.com" + } diff --git a/tests/Fixtures/gitlab-reply/discussion-not-found.yaml b/tests/Fixtures/gitlab-reply/discussion-not-found.yaml new file mode 100644 index 0000000..5047fb9 --- /dev/null +++ b/tests/Fixtures/gitlab-reply/discussion-not-found.yaml @@ -0,0 +1,9 @@ +# file generated with AI assistance: Claude Code - 2026-12-04 16:36:53 UTC +# GitLab 15.11 REST API response, documented: POST .../discussions/:discussion_id/notes, 404 Not Found: unknown discussion (lib/api/discussions.rb, not_found!("Discussion")) +origin: 'documented (GitLab v15.11.0 REST API documentation and source code, not captured)' +headers: + Content-Type: 'application/json' +body: | + { + "message": "404 Discussion Not Found" + } diff --git a/tests/Fixtures/gitlab-reply/discussion-not-repliable.yaml b/tests/Fixtures/gitlab-reply/discussion-not-repliable.yaml new file mode 100644 index 0000000..5605f1f --- /dev/null +++ b/tests/Fixtures/gitlab-reply/discussion-not-repliable.yaml @@ -0,0 +1,9 @@ +# file generated with AI assistance: Claude Code - 2026-12-04 16:36:53 UTC +# GitLab 15.11 REST API response, documented: POST .../discussions/:discussion_id/notes, 400 Bad Request: a note that cannot be replied to (lib/api/discussions.rb, bad_request!) +origin: 'documented (GitLab v15.11.0 REST API documentation and source code, not captured)' +headers: + Content-Type: 'application/json' +body: | + { + "message": "400 Bad request - Discussion can not be replied to." + } diff --git a/tests/Fixtures/gitlab-reply/discussion-reply-individual-note.yaml b/tests/Fixtures/gitlab-reply/discussion-reply-individual-note.yaml new file mode 100644 index 0000000..fd909a7 --- /dev/null +++ b/tests/Fixtures/gitlab-reply/discussion-reply-individual-note.yaml @@ -0,0 +1,33 @@ +# file generated with AI assistance: Claude Code - 2026-12-04 16:36:53 UTC +# GitLab 15.11 REST API response, documented: POST /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id/notes, 201 Created: a reply to a single note without a thread (individual_note), which GitLab turns into a thread (lib/api/discussions.rb, can_convert_to_discussion?) +origin: 'documented (GitLab v15.11.0 REST API documentation and source code, not captured)' +headers: + Content-Type: 'application/json' +body: | + { + "id": 70005, + "type": "DiscussionNote", + "body": "Sample reply of the agent.", + "attachment": null, + "author": { + "id": 900, + "username": "agent-example", + "name": "Agent Example", + "state": "active", + "avatar_url": "https://gitlab.example.com/uploads/-/system/user/avatar/900/avatar.png", + "web_url": "https://gitlab.example.com/agent-example" + }, + "created_at": "2026-12-04T10:19:00.000Z", + "updated_at": "2026-12-04T10:19:00.000Z", + "system": false, + "noteable_id": 5001, + "noteable_type": "MergeRequest", + "resolvable": true, + "resolved": false, + "resolved_by": null, + "resolved_at": null, + "confidential": false, + "internal": false, + "noteable_iid": 12, + "commands_changes": {} + } diff --git a/tests/Fixtures/gitlab-reply/discussion-reply-issue.yaml b/tests/Fixtures/gitlab-reply/discussion-reply-issue.yaml new file mode 100644 index 0000000..1dac45b --- /dev/null +++ b/tests/Fixtures/gitlab-reply/discussion-reply-issue.yaml @@ -0,0 +1,30 @@ +# file generated with AI assistance: Claude Code - 2026-12-04 16:36:53 UTC +# GitLab 15.11 REST API response, documented: POST /projects/:id/issues/:issue_iid/discussions/:discussion_id/notes, 201 Created: a reply in a thread of an issue (lib/api/discussions.rb, lib/api/entities/note.rb) +origin: 'documented (GitLab v15.11.0 REST API documentation and source code, not captured)' +headers: + Content-Type: 'application/json' +body: | + { + "id": 70004, + "type": "DiscussionNote", + "body": "Sample reply of the agent.", + "attachment": null, + "author": { + "id": 900, + "username": "agent-example", + "name": "Agent Example", + "state": "active", + "avatar_url": "https://gitlab.example.com/uploads/-/system/user/avatar/900/avatar.png", + "web_url": "https://gitlab.example.com/agent-example" + }, + "created_at": "2026-12-04T10:18:00.000Z", + "updated_at": "2026-12-04T10:18:00.000Z", + "system": false, + "noteable_id": 4001, + "noteable_type": "Issue", + "resolvable": false, + "confidential": false, + "internal": false, + "noteable_iid": 3, + "commands_changes": {} + } diff --git a/tests/Fixtures/gitlab-reply/discussion-reply-merge-request.yaml b/tests/Fixtures/gitlab-reply/discussion-reply-merge-request.yaml new file mode 100644 index 0000000..3c63cd5 --- /dev/null +++ b/tests/Fixtures/gitlab-reply/discussion-reply-merge-request.yaml @@ -0,0 +1,33 @@ +# file generated with AI assistance: Claude Code - 2026-12-04 16:36:53 UTC +# GitLab 15.11 REST API response, documented: POST /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id/notes, 201 Created: a reply in a thread of a merge request (lib/api/discussions.rb, lib/api/entities/note.rb) +origin: 'documented (GitLab v15.11.0 REST API documentation and source code, not captured)' +headers: + Content-Type: 'application/json' +body: | + { + "id": 70003, + "type": "DiscussionNote", + "body": "Sample reply of the agent.", + "attachment": null, + "author": { + "id": 900, + "username": "agent-example", + "name": "Agent Example", + "state": "active", + "avatar_url": "https://gitlab.example.com/uploads/-/system/user/avatar/900/avatar.png", + "web_url": "https://gitlab.example.com/agent-example" + }, + "created_at": "2026-12-04T10:17:00.000Z", + "updated_at": "2026-12-04T10:17:00.000Z", + "system": false, + "noteable_id": 5001, + "noteable_type": "MergeRequest", + "resolvable": true, + "resolved": false, + "resolved_by": null, + "resolved_at": null, + "confidential": false, + "internal": false, + "noteable_iid": 12, + "commands_changes": {} + } diff --git a/tests/Fixtures/gitlab-reply/note-issue.yaml b/tests/Fixtures/gitlab-reply/note-issue.yaml new file mode 100644 index 0000000..740df05 --- /dev/null +++ b/tests/Fixtures/gitlab-reply/note-issue.yaml @@ -0,0 +1,30 @@ +# file generated with AI assistance: Claude Code - 2026-12-04 16:36:53 UTC +# GitLab 15.11 REST API response, documented: POST /projects/:id/issues/:issue_iid/notes, 201 Created: a new note on an issue (lib/api/notes.rb, lib/api/entities/note.rb) +origin: 'documented (GitLab v15.11.0 REST API documentation and source code, not captured)' +headers: + Content-Type: 'application/json' +body: | + { + "id": 70002, + "type": null, + "body": "Sample answer of the agent.", + "attachment": null, + "author": { + "id": 900, + "username": "agent-example", + "name": "Agent Example", + "state": "active", + "avatar_url": "https://gitlab.example.com/uploads/-/system/user/avatar/900/avatar.png", + "web_url": "https://gitlab.example.com/agent-example" + }, + "created_at": "2026-12-04T10:16:00.000Z", + "updated_at": "2026-12-04T10:16:00.000Z", + "system": false, + "noteable_id": 4001, + "noteable_type": "Issue", + "resolvable": false, + "confidential": false, + "internal": false, + "noteable_iid": 3, + "commands_changes": {} + } diff --git a/tests/Fixtures/gitlab-reply/note-merge-request.yaml b/tests/Fixtures/gitlab-reply/note-merge-request.yaml new file mode 100644 index 0000000..4177db0 --- /dev/null +++ b/tests/Fixtures/gitlab-reply/note-merge-request.yaml @@ -0,0 +1,30 @@ +# file generated with AI assistance: Claude Code - 2026-12-04 16:36:53 UTC +# GitLab 15.11 REST API response, documented: POST /projects/:id/merge_requests/:merge_request_iid/notes, 201 Created: a new note on a merge request (lib/api/notes.rb, lib/api/entities/note.rb) +origin: 'documented (GitLab v15.11.0 REST API documentation and source code, not captured)' +headers: + Content-Type: 'application/json' +body: | + { + "id": 70001, + "type": null, + "body": "Sample answer of the agent.", + "attachment": null, + "author": { + "id": 900, + "username": "agent-example", + "name": "Agent Example", + "state": "active", + "avatar_url": "https://gitlab.example.com/uploads/-/system/user/avatar/900/avatar.png", + "web_url": "https://gitlab.example.com/agent-example" + }, + "created_at": "2026-12-04T10:15:00.000Z", + "updated_at": "2026-12-04T10:15:00.000Z", + "system": false, + "noteable_id": 5001, + "noteable_type": "MergeRequest", + "resolvable": false, + "confidential": false, + "internal": false, + "noteable_iid": 12, + "commands_changes": {} + } diff --git a/tests/Integration/ContainerVariantsTest.php b/tests/Integration/ContainerVariantsTest.php index 4b9d6df..3cca1e0 100644 --- a/tests/Integration/ContainerVariantsTest.php +++ b/tests/Integration/ContainerVariantsTest.php @@ -14,13 +14,17 @@ use Dmstr\Webhook\Intake\SlidingWindowLimiter; use Dmstr\Webhook\Intake\WebhookIntake; use Dmstr\Webhook\Log\WebhookSecretRedactionProcessor; +use Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient; use Dmstr\Webhook\Tests\Kernel\TestKernel; use Dmstr\Webhook\WebhookBundle; +use Monolog\Logger; use Psr\Clock\ClockInterface; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Symfony\Component\Clock\MockClock; +use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Webhook\Exception\RejectWebhookException; +use Symfony\Contracts\HttpClient\HttpClientInterface; /** * The container of a host application with and without the optional @@ -30,9 +34,13 @@ * its replay window (the test kernel's clock is frozen); * - without a `clock` service (a host without symfony/clock) the container * builds and the adapter falls back to the system time; - * - without a lock factory and without MonologBundle (both suggested only) - * the container builds and the intake services are complete, the GitLab - * and Basecamp 4 adapters included. + * - without a lock factory, without MonologBundle and without `http_client` + * (all suggested only) the container builds and the intake services are + * complete, the GitLab and Basecamp 4 adapters included; the GitLab reply + * client, which has no transport then, is not registered; + * - the GitLab reply client is registered only with + * m4tthumphrey/php-gitlab-api installed and the adapter `gitlab` enabled, + * over the application's `http_client` or the host's own reply transport. */ final class ContainerVariantsTest extends KernelTestCase { @@ -88,6 +96,65 @@ public function testTheContainerBuildsWithoutLockFactoryAndMonologBundle(): void // Without MonologBundle nothing uses the redaction processor, so the // container drops the unused private service. self::assertFalse($container->has(WebhookSecretRedactionProcessor::class)); + // Library and adapter are there, the transport is not. + self::assertFalse($container->has('http_client')); + self::assertFalse($container->has(GitlabReplyClient::class)); + } + + public function testTheGitlabReplyClientIsUnknownWithoutTheLibrary(): void + { + self::bootKernel(['environment' => TestKernel::ENV_NO_GITLAB_LIBRARY]); + $container = self::getContainer(); + + self::assertContains(GitlabParser::SOURCE, $container->getParameter('dmstr_webhook.enabled_adapters')); + self::assertTrue($container->has('http_client')); + self::assertFalse($container->has(GitlabReplyClient::class)); + // The adapter itself needs no library. + self::assertInstanceOf(GitlabParser::class, $container->get(WebhookAdapterRegistry::class)->get(GitlabParser::SOURCE)); + } + + public function testTheGitlabReplyClientIsUnknownWithTheAdapterOff(): void + { + self::bootKernel(['environment' => TestKernel::ENV_GITLAB_OFF]); + $container = self::getContainer(); + + self::assertNotContains(GitlabParser::SOURCE, $container->getParameter('dmstr_webhook.enabled_adapters')); + self::assertTrue(class_exists(\Gitlab\Client::class)); + self::assertFalse($container->has(GitlabReplyClient::class)); + self::assertFalse($container->get(WebhookAdapterRegistry::class)->has(GitlabParser::SOURCE)); + } + + public function testTheGitlabReplyClientUsesTheApplicationsHttpClient(): void + { + self::bootKernel(); + $container = self::getContainer(); + + self::assertTrue($container->has(GitlabReplyClient::class)); + $transport = self::transportOf($container->get(GitlabReplyClient::class)); + self::assertNotInstanceOf(MockHttpClient::class, $transport); + // The log channel `webhook`, like every service of the bundle. + $logger = new \ReflectionProperty(GitlabReplyClient::class, 'webhookLogger')->getValue($container->get(GitlabReplyClient::class)); + self::assertInstanceOf(Logger::class, $logger); + self::assertSame(WebhookBundle::LOG_CHANNEL, $logger->getName()); + } + + public function testTheHostReplacesTheReplyTransport(): void + { + self::bootKernel(['environment' => TestKernel::ENV_REPLY_TRANSPORT]); + $container = self::getContainer(); + + self::assertSame('dmstr_webhook.reply_http_client', WebhookBundle::REPLY_HTTP_CLIENT); + // The client keeps a copy of the transport without redirects. + self::assertInstanceOf(MockHttpClient::class, self::transportOf($container->get(GitlabReplyClient::class))); + } + + private static function transportOf(mixed $client): HttpClientInterface + { + self::assertInstanceOf(GitlabReplyClient::class, $client); + $transport = new \ReflectionProperty(GitlabReplyClient::class, 'httpClient')->getValue($client); + self::assertInstanceOf(HttpClientInterface::class, $transport); + + return $transport; } private static function standardWebhooks(): StandardWebhooksParser @@ -119,3 +186,4 @@ private static function signed(string $id, int $timestamp): Request // - revised 2026-12-03 (GitLab adapter in the minimal variant) // - revised 2026-12-03 (Basecamp 4 adapter in the minimal variant) +// - revised 2026-12-04 (GitLab reply client: library absent, adapter off, default and host transport, minimal without http_client) diff --git a/tests/Kernel/TestKernel.php b/tests/Kernel/TestKernel.php index 176b053..ab77ee5 100644 --- a/tests/Kernel/TestKernel.php +++ b/tests/Kernel/TestKernel.php @@ -14,12 +14,16 @@ use Dmstr\DoctrineAuditLog\Entity\LogEntry; use Dmstr\OpenApiJsonSchema\OpenApiJsonSchemaBundle; use Dmstr\OpenApiJsonSchema\Service\OperationInputSchemaResolver; +use Dmstr\Webhook\Adapter\GitlabParser; +use Dmstr\Webhook\DependencyInjection\OptionalLibraries; +use Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient; use Dmstr\Webhook\Tests\Support\RecordingDeliveryHandler; use Dmstr\Webhook\WebhookBundle; use Doctrine\Bundle\DoctrineBundle\DoctrineBundle; use Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle; use Doctrine\DBAL\Platforms\PostgreSQLPlatform; use Gedmo\Loggable\Entity\MappedSuperclass\AbstractLogEntry; +use Gitlab\Client as GitlabClient; use Psr\Clock\ClockInterface as PsrClockInterface; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; @@ -31,6 +35,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; @@ -112,8 +117,21 @@ * check of the bundle is denied; * - {@see self::ENV_NO_CLOCK}: the `clock` service and its aliases are * removed, as in a host without symfony/clock; - * - {@see self::ENV_MINIMAL}: no MonologBundle and no lock factory (both - * only suggested by the bundle). + * - {@see self::ENV_MINIMAL}: no MonologBundle, no lock factory and no + * `http_client` (all only suggested by the bundle), so the GitLab reply + * client has no transport and is removed; + * - {@see self::ENV_NO_GITLAB_LIBRARY}: m4tthumphrey/php-gitlab-api counts as + * not installed (the bundle is built with + * `new OptionalLibraries([Gitlab\Client::class])`), so the GitLab reply + * client is not registered although the adapter `gitlab` is enabled; + * - {@see self::ENV_GITLAB_OFF}: the adapter `gitlab` is disabled, so the + * GitLab reply client is not registered; + * - {@see self::ENV_REPLY_TRANSPORT}: the host defines the reply transport + * `dmstr_webhook.reply_http_client` itself, as a `MockHttpClient`. + * + * Where the GitLab reply client is registered, {@see self::process()} makes + * it public, as a consumer of the host would keep it, so the tests can fetch + * it. * * Cache and logs live under the system temp directory, one directory per * variant, so a test run leaves no files in the repository. @@ -126,6 +144,9 @@ final class TestKernel extends Kernel implements CompilerPassInterface public const string ENV_NO_VOTER = 'test_no_voter'; public const string ENV_NO_CLOCK = 'test_no_clock'; public const string ENV_MINIMAL = 'test_minimal'; + public const string ENV_NO_GITLAB_LIBRARY = 'test_no_gitlab_library'; + public const string ENV_GITLAB_OFF = 'test_gitlab_off'; + public const string ENV_REPLY_TRANSPORT = 'test_reply_transport'; public const string API_PREFIX = '/api'; @@ -170,7 +191,7 @@ public function registerBundles(): iterable if ($this->hasMonolog()) { yield new MonologBundle(); } - yield new WebhookBundle(); + yield new WebhookBundle(new OptionalLibraries(self::ENV_NO_GITLAB_LIBRARY === $this->environment ? [GitlabClient::class] : [])); } /** @@ -241,6 +262,12 @@ public function process(ContainerBuilder $container): void ->addMethodCall('setActorProvider', [new Reference(TestActorProvider::class)]); } + // Nothing of the host uses the reply client; public, so the tests can + // fetch it instead of the container dropping the unused service. + if ($container->hasDefinition(GitlabReplyClient::class)) { + $container->getDefinition(GitlabReplyClient::class)->setPublic(true); + } + // As in a host without symfony/clock: FrameworkBundle registers no // `clock` service then. Runs after the bundle's own passes and // before the optional references are resolved. @@ -293,6 +320,7 @@ private function configureContainer(ContainerConfigurator $container): void 'webhook' => ['enabled' => false], 'remote_event' => ['enabled' => false], 'lock' => self::ENV_MINIMAL === $this->environment ? false : 'flock', + 'http_client' => ['enabled' => self::ENV_MINIMAL !== $this->environment], 'cache' => [ 'app' => 'cache.adapter.array', 'pools' => [ @@ -386,7 +414,9 @@ private function configureContainer(ContainerConfigurator $container): void ]); $container->extension('dmstr_webhook', [ - 'adapters' => self::ADAPTERS, + 'adapters' => self::ENV_GITLAB_OFF === $this->environment + ? array_replace(self::ADAPTERS, [GitlabParser::SOURCE => false]) + : self::ADAPTERS, ]); if ($this->hasMonolog()) { @@ -431,6 +461,11 @@ private function configureContainer(ContainerConfigurator $container): void // `dmstr_webhook.delivery_handler` through autoconfiguration. $services->set(RecordingDeliveryHandler::class); + if (self::ENV_REPLY_TRANSPORT === $this->environment) { + // The host's own reply transport, as its end-to-end tests set it. + $services->set(WebhookBundle::REPLY_HTTP_CLIENT, MockHttpClient::class); + } + if ($this->hasPermissionVoter()) { // Autoconfiguration adds the `security.voter` tag; public so that // tests can tell the variants apart. @@ -474,3 +509,4 @@ private static function attributeMapping(string $class, string $prefix): array // - revised 2026-12-03 (test-only adapters test_context and test_actorless for the intake modes) // - revised 2026-12-03 (GitLab adapter enabled) // - revised 2026-12-03 (Basecamp 4 adapter enabled) +// - revised 2026-12-04 (GitLab reply client: variants without library, with the adapter off, with the host's transport, minimal without http_client) diff --git a/tests/Support/GitlabReplyFixtures.php b/tests/Support/GitlabReplyFixtures.php new file mode 100644 index 0000000..9d37920 --- /dev/null +++ b/tests/Support/GitlabReplyFixtures.php @@ -0,0 +1,97 @@ + + * origin: documented (GitLab v15.11.0 REST API documentation and source code, not captured) + * headers: {Content-Type: application/json} + * body: | + * { pretty-printed JSON in the shape of the API entity } + * + * None is captured: the shapes follow the documentation and the source code + * (`lib/api/notes.rb`, `lib/api/discussions.rb`, `lib/api/entities/note.rb`, + * `lib/api/entities/user_public.rb`) of GitLab tag `v15.11.0`, every value is + * invented. The HTTP status of each response is {@see self::STATUS}; the + * identities below are the ones the files and the reply tests use. + */ +final class GitlabReplyFixtures +{ + public const string DIR = __DIR__.'/../Fixtures/gitlab-reply'; + + /** The `base_url` of the reply connection. */ + public const string BASE_URL = 'https://gitlab.example.com'; + + /** The plain token of the reply connection; distinctive, so a leak is found by substring. */ + public const string TOKEN = 'fixture-token-gitlab-reply-Zq8Wv3Kd7Tn2Lr5Xm9Ph4'; + + /** The token's user: the endpoint's bot. */ + public const int BOT_ID = 900; + public const string BOT_HANDLE = 'agent-example'; + + public const int PROJECT_ID = 101; + public const string PROJECT_PATH = 'example-group/sample-project'; + public const int MERGE_REQUEST_IID = 12; + public const int ISSUE_IID = 3; + + /** A thread (several notes). */ + public const string DISCUSSION_ID = '3c8e1f4a9b2d7e6f0a5c1b8d4e7f2a9c6b3d0e1f'; + /** A single note without a thread (`individual_note: true`). */ + public const string INDIVIDUAL_NOTE_DISCUSSION_ID = '7f2a9c6b3d0e1f3c8e1f4a9b2d7e6f0a5c1b8d4e'; + + /** The HTTP status of each fixture. */ + public const array STATUS = [ + 'current-user' => 200, + 'discussion-not-found' => 404, + 'discussion-not-repliable' => 400, + 'discussion-reply-individual-note' => 201, + 'discussion-reply-issue' => 201, + 'discussion-reply-merge-request' => 201, + 'note-issue' => 201, + 'note-merge-request' => 201, + ]; + + private static ?FixtureSet $set = null; + + /** The fixture files of {@see self::DIR}. */ + public static function set(): FixtureSet + { + return self::$set ??= new FixtureSet(self::DIR, 'GitLab reply'); + } + + /** + * The decoded body. + * + * @return array + */ + public static function payload(string $name): array + { + return self::set()->payload($name); + } + + /** The fixture as a response of the HTTP fake, with its status and headers. */ + public static function response(string $name): MockResponse + { + $headers = []; + foreach (self::set()->headers($name) as $header => $value) { + $headers[] = $header.': '.$value; + } + + return new MockResponse(self::set()->body($name), [ + 'http_code' => self::STATUS[$name] ?? throw new \OutOfBoundsException(\sprintf('No status for the GitLab reply fixture "%s".', $name)), + 'response_headers' => $headers, + ]); + } +} diff --git a/tests/Support/RecordingGitlabHttpClient.php b/tests/Support/RecordingGitlabHttpClient.php new file mode 100644 index 0000000..c2e6983 --- /dev/null +++ b/tests/Support/RecordingGitlabHttpClient.php @@ -0,0 +1,154 @@ + ['POST', '~^/api/v4/projects/[^/]+/(merge_requests|issues)/[0-9]+/discussions/[^/]+/notes$~'], + 'add_note' => ['POST', '~^/api/v4/projects/[^/]+/(merge_requests|issues)/[0-9]+/notes$~'], + 'current_user' => ['GET', '~^/api/v4/user$~'], + ]; + + /** @var list>, body: array|null}> */ + public array $requests = []; + + /** @var list */ + private array $queue; + + private readonly MockHttpClient $client; + + /** + * @param string $baseUrl the `base_url` of the reply connection + * @param list $responses the answers, in order + */ + public function __construct(private readonly string $baseUrl = GitlabReplyFixtures::BASE_URL, array $responses = []) + { + $this->queue = $responses; + $this->client = new MockHttpClient($this->respond(...), null); + } + + public function client(): MockHttpClient + { + return $this->client; + } + + public function queue(MockResponse ...$responses): self + { + array_push($this->queue, ...$responses); + + return $this; + } + + /** + * The one recorded request; fails unless there is exactly one. + * + * @return array{operation: string, method: string, url: string, path: string, headers: array>, body: array|null} + */ + public function single(): array + { + Assert::assertCount(1, $this->requests, 'requests sent to GitLab'); + + return $this->requests[0]; + } + + /** + * The response factory of the {@see MockHttpClient}: checks and records + * one request (headers by lower-case name, the authentication header + * included), then answers with the next queued response. + * + * @param array $options + */ + private function respond(string $method, string $url, array $options): MockResponse + { + $parts = parse_url($url); + $expected = parse_url($this->baseUrl); + if (false === $parts || false === $expected) { + Assert::fail(\sprintf('Unparsable request URL to GitLab: %s %s', $method, $url)); + } + foreach (['scheme', 'host', 'port'] as $key) { + if (($parts[$key] ?? null) !== ($expected[$key] ?? null)) { + Assert::fail(\sprintf('Request to another %s than the base_url %s: %s %s', $key, $this->baseUrl, $method, $url)); + } + } + if (isset($parts['query']) || isset($parts['fragment'])) { + Assert::fail(\sprintf('Request to GitLab with a query or fragment: %s %s', $method, $url)); + } + + $path = $parts['path'] ?? ''; + $operation = null; + foreach (self::OPERATIONS as $name => [$allowedMethod, $pattern]) { + if ($allowedMethod === $method && 1 === preg_match($pattern, $path)) { + $operation = $name; + break; + } + } + if (null === $operation) { + Assert::fail(\sprintf('Request outside the operations of the reply client: %s %s', $method, $path)); + } + + $body = self::body($options['body'] ?? ''); + if ('GET' === $method && '' !== $body) { + Assert::fail(\sprintf('GET request to GitLab with a body: %s', $path)); + } + $decoded = null; + if ('POST' === $method) { + $decoded = json_decode($body, true); + if (!\is_array($decoded) || ['body'] !== array_keys($decoded) || !\is_string($decoded['body'])) { + Assert::fail(\sprintf('POST request to GitLab with a body other than {"body": ""}: %s', $path)); + } + } + + $headers = []; + foreach ($options['normalized_headers'] ?? [] as $name => $lines) { + $headers[(string) $name] = array_map(static fn (string $line): string => trim(explode(':', $line, 2)[1] ?? ''), $lines); + } + + $this->requests[] = ['operation' => $operation, 'method' => $method, 'url' => $url, 'path' => $path, 'headers' => $headers, 'body' => $decoded]; + + $response = array_shift($this->queue); + if (null === $response) { + Assert::fail(\sprintf('No response queued for %s %s', $method, $path)); + } + + return $response; + } + + private static function body(mixed $body): string + { + if (\is_string($body)) { + return $body; + } + if ($body instanceof \Closure) { + $content = ''; + while ('' !== $chunk = (string) $body(16384)) { + $content .= $chunk; + } + + return $content; + } + + return ''; + } +} diff --git a/tests/Unit/DependencyInjection/OptionalLibrariesTest.php b/tests/Unit/DependencyInjection/OptionalLibrariesTest.php new file mode 100644 index 0000000..e0fa551 --- /dev/null +++ b/tests/Unit/DependencyInjection/OptionalLibrariesTest.php @@ -0,0 +1,39 @@ +installed(GitlabClient::class)); + } + + public function testAMissingMarkerClassIsNotInstalled(): void + { + /** @var class-string $missing */ + $missing = 'Dmstr\\Webhook\\Tests\\Unit\\DependencyInjection\\NoSuchLibraryClient'; + + self::assertFalse(new OptionalLibraries()->installed($missing)); + } + + public function testAnIgnoredMarkerClassIsNotInstalled(): void + { + $libraries = new OptionalLibraries([GitlabClient::class]); + + self::assertFalse($libraries->installed(GitlabClient::class)); + self::assertTrue($libraries->installed(TestCase::class)); + } +} diff --git a/tests/Unit/DependencyInjection/RemoveReplyClientsWithoutTransportPassTest.php b/tests/Unit/DependencyInjection/RemoveReplyClientsWithoutTransportPassTest.php new file mode 100644 index 0000000..bbc5e17 --- /dev/null +++ b/tests/Unit/DependencyInjection/RemoveReplyClientsWithoutTransportPassTest.php @@ -0,0 +1,79 @@ +setAlias('reply_client_alias', GitlabReplyClient::class); + $container->register('unrelated', \stdClass::class); + + new RemoveReplyClientsWithoutTransportPass()->process($container); + + self::assertFalse($container->has(GitlabReplyClient::class)); + self::assertFalse($container->has(WebhookBundle::REPLY_HTTP_CLIENT)); + self::assertFalse($container->hasAlias('reply_client_alias')); + self::assertTrue($container->hasDefinition('unrelated')); + } + + public function testTheApplicationsHttpClientKeepsTheClients(): void + { + $container = self::withClient(); + $container->register('http_client', MockHttpClient::class); + + new RemoveReplyClientsWithoutTransportPass()->process($container); + + self::assertTrue($container->hasDefinition(GitlabReplyClient::class)); + self::assertTrue($container->hasAlias(WebhookBundle::REPLY_HTTP_CLIENT)); + } + + public function testTheHostsOwnTransportKeepsTheClients(): void + { + $container = self::withClient(); + $container->removeAlias(WebhookBundle::REPLY_HTTP_CLIENT); + $container->register(WebhookBundle::REPLY_HTTP_CLIENT, MockHttpClient::class); + + new RemoveReplyClientsWithoutTransportPass()->process($container); + + self::assertTrue($container->hasDefinition(GitlabReplyClient::class)); + self::assertTrue($container->hasDefinition(WebhookBundle::REPLY_HTTP_CLIENT)); + } + + public function testWithoutAReplyTransportNothingChanges(): void + { + $container = new ContainerBuilder(); + $container->register('unrelated', \stdClass::class); + + new RemoveReplyClientsWithoutTransportPass()->process($container); + + self::assertTrue($container->hasDefinition('unrelated')); + } + + /** The registration of the bundle: the client and the transport alias of `http_client`. */ + private static function withClient(): ContainerBuilder + { + $container = new ContainerBuilder(); + $container->register(GitlabReplyClient::class, GitlabReplyClient::class); + $container->setAlias(WebhookBundle::REPLY_HTTP_CLIENT, 'http_client'); + + return $container; + } +} diff --git a/tests/Unit/Fixtures/FixtureAnonymisationTest.php b/tests/Unit/Fixtures/FixtureAnonymisationTest.php index cf69787..3c0c5b5 100644 --- a/tests/Unit/Fixtures/FixtureAnonymisationTest.php +++ b/tests/Unit/Fixtures/FixtureAnonymisationTest.php @@ -9,6 +9,7 @@ use Dmstr\Webhook\Tests\Support\Basecamp4Fixtures; use Dmstr\Webhook\Tests\Support\FixtureSet; use Dmstr\Webhook\Tests\Support\GitlabFixtures; +use Dmstr\Webhook\Tests\Support\GitlabReplyFixtures; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Symfony\Component\Yaml\Yaml; @@ -93,6 +94,27 @@ private static function sources(): array 'avatar', 'merge_requests', 'issues', 'commit', ], ], + // REST API responses of the reply client, built from the GitLab + // v15.11.0 documentation and source code: every fixture is + // documented, every value invented; layer 2 runs only once + // captures exist. + 'gitlab-reply' => [ + 'fixtures' => GitlabReplyFixtures::set(), + 'minFixtures' => 8, + 'allowedHosts' => ['example.com', 'gitlab.example.com'], + 'headers' => [ + 'Content-Type' => 'application/json', + ], + 'headerPatterns' => [], + 'cleanSample' => '"web_url": "https://gitlab.example.com/agent-example", "email": "agent-example@example.com", "body": "Sample reply of the agent."', + 'capturesEnv' => 'WEBHOOK_RAW_CAPTURES_DIR_GITLAB_REPLY', + 'structural' => [ + 'application/json', 'MergeRequest', 'Issue', 'DiscussionNote', 'active', + '404 Discussion Not Found', '400 Bad request - Discussion can not be replied to.', + // URL path keywords of the source. + 'avatar', 'uploads', 'system', 'user', 'merge_requests', 'issues', 'discussions', 'notes', + ], + ], // No recorded deliveries: every fixture is documented or derived, // every value invented; layer 2 runs only once captures exist. 'basecamp4' => [ @@ -398,3 +420,4 @@ private static function captureValues(string $capture, array $structural): array // - revised 2026-12-03 (sources as entries of one definition per source) // - revised 2026-12-03 (Basecamp 4 source: documented fixtures, its headers, hosts and broken samples) +// - revised 2026-12-04 (GitLab reply source: documented REST API responses of the reply client) diff --git a/tests/Unit/Reply/GitlabReplyClientTest.php b/tests/Unit/Reply/GitlabReplyClientTest.php new file mode 100644 index 0000000..14e7565 --- /dev/null +++ b/tests/Unit/Reply/GitlabReplyClientTest.php @@ -0,0 +1,366 @@ + ` in `$records`. */ + private AbstractLogger $logger; + + protected function setUp(): void + { + $this->encryption = new CredentialEncryption(random_bytes(\SODIUM_CRYPTO_SECRETBOX_KEYBYTES)); + $this->http = new RecordingGitlabHttpClient(); + $this->logger = new class extends AbstractLogger { + /** @var list */ + public array $records = []; + + public function log($level, string|\Stringable $message, array $context = []): void + { + $this->records[] = $level.' '.$message.' '.json_encode($context, \JSON_THROW_ON_ERROR); + } + }; + } + + /** + * @return iterable + */ + public static function noteCases(): iterable + { + $mr = GitlabReplyFixtures::MERGE_REQUEST_IID; + $issue = GitlabReplyFixtures::ISSUE_IID; + $project = GitlabReplyFixtures::PROJECT_ID; + $thread = GitlabReplyFixtures::DISCUSSION_ID; + + yield 'new note on a merge request' => [GitlabNoteable::MergeRequest, $project, $mr, null, 'note-merge-request', "/api/v4/projects/101/merge_requests/$mr/notes", null]; + yield 'new note on an issue' => [GitlabNoteable::Issue, $project, $issue, null, 'note-issue', "/api/v4/projects/101/issues/$issue/notes", null]; + yield 'reply in a thread of a merge request' => [GitlabNoteable::MergeRequest, $project, $mr, $thread, 'discussion-reply-merge-request', "/api/v4/projects/101/merge_requests/$mr/discussions/$thread/notes", 'DiscussionNote']; + yield 'reply in a thread of an issue' => [GitlabNoteable::Issue, $project, $issue, $thread, 'discussion-reply-issue', "/api/v4/projects/101/issues/$issue/discussions/$thread/notes", 'DiscussionNote']; + yield 'new note, project by path' => [GitlabNoteable::MergeRequest, GitlabReplyFixtures::PROJECT_PATH, $mr, null, 'note-merge-request', "/api/v4/projects/example-group%2Fsample-project/merge_requests/$mr/notes", null]; + } + + #[DataProvider('noteCases')] + public function testPostsANoteOrAReply(GitlabNoteable $noteable, int|string $project, int $iid, ?string $discussionId, string $fixture, string $path, ?string $type): void + { + $this->http->queue(GitlabReplyFixtures::response($fixture)); + $endpoint = $this->endpoint(); + + $note = null === $discussionId + ? $this->client()->addNote($endpoint, $noteable, $project, $iid, self::TEXT) + : $this->client()->replyToDiscussion($endpoint, $noteable, $project, $iid, $discussionId, self::TEXT); + + $request = $this->http->single(); + self::assertSame('POST', $request['method']); + self::assertSame($path, $request['path']); + self::assertSame(GitlabReplyFixtures::BASE_URL.$path, $request['url']); + self::assertSame(['body' => self::TEXT], $request['body']); + self::assertSame([GitlabReplyFixtures::TOKEN], $request['headers']['private-token'] ?? null); + + $payload = GitlabReplyFixtures::payload($fixture); + self::assertEquals(new GitlabNote( + $payload['id'], + $type, + GitlabReplyFixtures::BOT_ID, + GitlabReplyFixtures::BOT_HANDLE, + GitlabNoteable::MergeRequest === $noteable ? 'MergeRequest' : 'Issue', + $iid, + $payload['created_at'], + ), $note); + $this->assertNoTokenInLogs(); + } + + public function testRepliesToASingleNoteWithoutAThread(): void + { + $this->http->queue(GitlabReplyFixtures::response('discussion-reply-individual-note')); + $discussion = GitlabReplyFixtures::INDIVIDUAL_NOTE_DISCUSSION_ID; + + $note = $this->client()->replyToDiscussion($this->endpoint(), GitlabNoteable::MergeRequest, GitlabReplyFixtures::PROJECT_ID, GitlabReplyFixtures::MERGE_REQUEST_IID, $discussion, self::TEXT); + + $request = $this->http->single(); + self::assertSame('reply_to_discussion', $request['operation']); + self::assertSame('/api/v4/projects/101/merge_requests/12/discussions/'.$discussion.'/notes', $request['path']); + self::assertSame(['body' => self::TEXT], $request['body']); + self::assertSame('DiscussionNote', $note->type); + self::assertSame(GitlabReplyFixtures::payload('discussion-reply-individual-note')['id'], $note->id); + } + + public function testReadsTheOwnIdentity(): void + { + $this->http->queue(GitlabReplyFixtures::response('current-user')); + + $user = $this->client()->currentUser($this->endpoint()); + + $request = $this->http->single(); + self::assertSame('GET', $request['method']); + self::assertSame(GitlabReplyFixtures::BASE_URL.'/api/v4/user', $request['url']); + self::assertNull($request['body']); + self::assertSame([GitlabReplyFixtures::TOKEN], $request['headers']['private-token'] ?? null); + self::assertSame(GitlabReplyFixtures::BOT_ID, $user->id); + self::assertSame(GitlabReplyFixtures::BOT_HANDLE, $user->username); + self::assertSame('Agent Example', $user->name); + self::assertTrue($user->bot); + } + + public function testATrailingSlashOfTheBaseUrlIsAccepted(): void + { + $this->http->queue(GitlabReplyFixtures::response('current-user')); + + $this->client()->currentUser($this->endpoint(['base_url' => GitlabReplyFixtures::BASE_URL.'/'])); + + self::assertSame(GitlabReplyFixtures::BASE_URL.'/api/v4/user', $this->http->single()['url']); + } + + /** + * @return iterable, int}> + */ + public static function replyFailures(): iterable + { + yield 'unknown discussion of a merge request' => [GitlabNoteable::MergeRequest, 'discussion-not-found', DiscussionNotFoundException::class, 404]; + yield 'unknown discussion of an issue' => [GitlabNoteable::Issue, 'discussion-not-found', DiscussionNotFoundException::class, 404]; + yield 'discussion of a merge request that cannot be replied to' => [GitlabNoteable::MergeRequest, 'discussion-not-repliable', DiscussionNotRepliableException::class, 400]; + yield 'discussion of an issue that cannot be replied to' => [GitlabNoteable::Issue, 'discussion-not-repliable', DiscussionNotRepliableException::class, 400]; + } + + /** + * @param class-string $expected + */ + #[DataProvider('replyFailures')] + public function testAFailedReplyThrowsItsOwnException(GitlabNoteable $noteable, string $fixture, string $expected, int $status): void + { + $this->http->queue(GitlabReplyFixtures::response($fixture)); + + $e = $this->catch(fn () => $this->client()->replyToDiscussion($this->endpoint(), $noteable, GitlabReplyFixtures::PROJECT_ID, 7, GitlabReplyFixtures::DISCUSSION_ID, self::TEXT)); + + self::assertInstanceOf($expected, $e); + self::assertSame($status, $e->statusCode); + self::assertStringContainsString((string) GitlabReplyFixtures::payload($fixture)['message'], $e->getMessage()); + $this->assertNoToken($e); + $this->assertNoTokenInLogs(); + self::assertCount(1, $this->http->requests); + } + + public function testA404OnANewNoteIsNoUnknownDiscussion(): void + { + $this->http->queue(new MockResponse('{"message":"404 Merge Request Not Found"}', ['http_code' => 404, 'response_headers' => ['Content-Type: application/json']])); + + $e = $this->catch(fn () => $this->client()->addNote($this->endpoint(), GitlabNoteable::MergeRequest, GitlabReplyFixtures::PROJECT_ID, 99, self::TEXT)); + + self::assertInstanceOf(GitlabRequestFailedException::class, $e); + self::assertNotInstanceOf(DiscussionNotFoundException::class, $e); + self::assertSame(404, $e->statusCode); + } + + /** + * @return iterable|null, string}> + */ + public static function unusableConnections(): iterable + { + yield 'no reply connection' => [null, 'has no reply connection']; + yield 'connection of another type' => [['type' => 'github'], 'has the type "github", expected "gitlab"']; + yield 'connection without a type' => [['type' => null], 'has the type "", expected "gitlab"']; + yield 'no base_url' => [['base_url' => null], 'has no "base_url"']; + yield 'empty base_url' => [['base_url' => ' '], 'has no "base_url"']; + yield 'base_url with a path' => [['base_url' => 'https://gitlab.example.com/gitlab'], 'must be an absolute http or https URL']; + yield 'base_url without a scheme' => [['base_url' => 'gitlab.example.com'], 'must be an absolute http or https URL']; + yield 'base_url with credentials' => [['base_url' => 'https://user:pass@gitlab.example.com'], 'must be an absolute http or https URL']; + yield 'no token' => [['token' => null], 'has no "token" or an empty one']; + yield 'empty token' => [['token' => ''], 'has no "token" or an empty one']; + yield 'encrypted empty token' => [['token' => 'encrypted-empty'], 'has no "token" or an empty one']; + } + + /** + * @param array|null $override config overrides (null removes a key); null: no reply connection + */ + #[DataProvider('unusableConnections')] + public function testAnUnusableConnectionFailsBeforeAnyRequest(?array $override, string $message): void + { + if (null !== $override && 'encrypted-empty' === ($override['token'] ?? null)) { + $override['token'] = $this->encrypted(''); + } + $endpoint = null === $override ? new WebhookEndpoint() : $this->endpoint($override); + + foreach ([ + fn () => $this->client()->addNote($endpoint, GitlabNoteable::Issue, 1, 1, self::TEXT), + fn () => $this->client()->replyToDiscussion($endpoint, GitlabNoteable::MergeRequest, 1, 1, GitlabReplyFixtures::DISCUSSION_ID, self::TEXT), + fn () => $this->client()->currentUser($endpoint), + ] as $call) { + $e = $this->catch($call); + self::assertInstanceOf(ReplyConnectionException::class, $e); + self::assertStringContainsString($message, $e->getMessage()); + $this->assertNoToken($e); + } + self::assertSame([], $this->http->requests); + } + + public function testNoRedirectIsFollowedToAnotherHost(): void + { + $this->http->queue(new MockResponse('', ['http_code' => 302, 'response_headers' => ['Location: https://gitlab.other-host.test/api/v4/projects/101/merge_requests/12/notes']])); + + $e = $this->catch(fn () => $this->client()->addNote($this->endpoint(), GitlabNoteable::MergeRequest, GitlabReplyFixtures::PROJECT_ID, GitlabReplyFixtures::MERGE_REQUEST_IID, self::TEXT)); + + self::assertInstanceOf(GitlabRequestFailedException::class, $e); + self::assertSame(302, $e->statusCode); + self::assertStringContainsString('redirect not followed', $e->getMessage()); + self::assertCount(1, $this->http->requests); + $this->assertNoToken($e); + } + + /** + * @return iterable + */ + public static function leakingFailures(): iterable + { + $json = ['response_headers' => ['Content-Type: application/json']]; + yield 'error message echoing the token' => [new MockResponse('{"message":"401 Unauthorized: '.GitlabReplyFixtures::TOKEN.'"}', ['http_code' => 401] + $json)]; + yield 'server error echoing the token' => [new MockResponse('{"error":"'.GitlabReplyFixtures::TOKEN.'"}', ['http_code' => 500] + $json)]; + yield 'transport error naming the token' => [new MockResponse('', ['error' => 'connection reset, token '.GitlabReplyFixtures::TOKEN])]; + yield 'invalid JSON echoing the token' => [new MockResponse('{'.GitlabReplyFixtures::TOKEN, ['http_code' => 201] + $json)]; + yield 'JSON that is no note' => [new MockResponse('["'.GitlabReplyFixtures::TOKEN.'"]', ['http_code' => 201] + $json)]; + } + + #[DataProvider('leakingFailures')] + public function testTheTokenAppearsInNoExceptionMessageAndNoLogRecord(MockResponse $response): void + { + $this->http->queue($response); + + $e = $this->catch(fn () => $this->client()->addNote($this->endpoint(), GitlabNoteable::Issue, GitlabReplyFixtures::PROJECT_ID, GitlabReplyFixtures::ISSUE_IID, self::TEXT)); + + self::assertInstanceOf(GitlabRequestFailedException::class, $e); + $this->assertNoToken($e); + $this->assertNoTokenInLogs(); + self::assertNotSame([], $this->logger->records); + } + + public function testThePublicApiExposesNoGitlabLibraryType(): void + { + $classes = [GitlabReplyClient::class, GitlabNote::class, GitlabNoteable::class, \Dmstr\Webhook\Reply\Gitlab\GitlabUser::class, ReplyConnectionException::class, GitlabRequestFailedException::class, DiscussionNotFoundException::class, DiscussionNotRepliableException::class, GitlabReplyException::class]; + foreach ($classes as $class) { + $reflection = new \ReflectionClass($class); + foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + $types = [(string) $method->getReturnType()]; + foreach ($method->getParameters() as $parameter) { + $types[] = (string) $parameter->getType(); + } + foreach ($types as $type) { + self::assertStringNotContainsString('Gitlab\\', str_replace('Dmstr\\Webhook\\Reply\\Gitlab\\', '', $type), $class.'::'.$method->getName()); + } + } + foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { + self::assertStringNotContainsString('Gitlab\\', str_replace('Dmstr\\Webhook\\Reply\\Gitlab\\', '', (string) $property->getType()), $class.'::$'.$property->getName()); + } + } + + $client = new \ReflectionClass(GitlabReplyClient::class); + self::assertSame([], $client->getProperties(\ReflectionProperty::IS_PUBLIC)); + self::assertSame(['__construct', 'replyToDiscussion', 'addNote', 'currentUser'], array_map(static fn (\ReflectionMethod $m): string => $m->getName(), $client->getMethods(\ReflectionMethod::IS_PUBLIC))); + } + + private function client(): GitlabReplyClient + { + return new GitlabReplyClient($this->configSecrets(), $this->http->client(), $this->logger); + } + + private function configSecrets(): ConfigSecrets + { + $encryption = $this->encryption; + + return new ConfigSecrets( + new SecretSchemaResolver(new SchemaRegistry(new ArrayAdapter(), new NullLogger()), new ApiExtensionRegistry()), + static fn (): CredentialEncryption => $encryption, + ); + } + + /** A token as ConfigSecrets stores it. */ + private function encrypted(string $token): string + { + return ConfigSecrets::PREFIX.$this->encryption->encrypt(['v' => $token]); + } + + /** + * An endpoint with a GitLab reply connection; an override with the value + * null removes the key. + * + * @param array $override + */ + private function endpoint(array $override = []): WebhookEndpoint + { + $config = array_merge([ + 'type' => GitlabReplyClient::CONNECTION_TYPE, + 'endpoint_type' => 'rest', + 'base_url' => GitlabReplyFixtures::BASE_URL, + 'token' => $this->encrypted(GitlabReplyFixtures::TOKEN), + ], $override); + $connection = new ApiConfiguration(); + $connection->setName('GitLab reply'); + $connection->setConfigJson(array_filter($config, static fn (mixed $value): bool => null !== $value)); + + return new WebhookEndpoint()->setReplyConnection($connection); + } + + private function catch(\Closure $call): GitlabReplyException + { + try { + $call(); + } catch (GitlabReplyException $e) { + return $e; + } + + self::fail('No GitlabReplyException thrown.'); + } + + private function assertNoToken(\Throwable $e): void + { + for ($current = $e; null !== $current; $current = $current->getPrevious()) { + self::assertStringNotContainsString(GitlabReplyFixtures::TOKEN, $current->getMessage(), $current::class); + self::assertStringNotContainsString(GitlabReplyFixtures::TOKEN, (string) $current, $current::class.' as string'); + } + } + + private function assertNoTokenInLogs(): void + { + foreach ($this->logger->records as $record) { + self::assertStringNotContainsString(GitlabReplyFixtures::TOKEN, $record); + } + } +}