From 0a741923117f9efafd748bd57393f984f4af4f98 Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 3 Dec 2026 22:58:24 +0000 Subject: [PATCH 1/5] refactor(adapter): shared path secret check, source-neutral fixture set and matrix, anonymisation test per source [*] No behaviour change, preparation for a second source adapter: the path secret check of PassthroughPathParser and the sample test adapter moves into AbstractWebhookParser::verifyPathSecret(); the fixture loader and the matrix building block of the GitLab tests become FixtureSet and FixtureMatrix; FixtureAnonymisationTest takes one definition per source. Co-Authored-By: Claude Fable 5.2 --- src/Adapter/AbstractWebhookParser.php | 22 +- src/Adapter/PassthroughPathParser.php | 9 +- tests/Kernel/ActorlessTestAdapter.php | 9 +- tests/Support/FixtureMatrix.php | 72 ++++++ tests/Support/FixtureSet.php | 166 +++++++++++++ tests/Support/GitlabFixtures.php | 63 ++--- tests/Support/GitlabMatrix.php | 35 ++- .../Fixtures/FixtureAnonymisationTest.php | 233 ++++++++++++------ 8 files changed, 468 insertions(+), 141 deletions(-) create mode 100644 tests/Support/FixtureMatrix.php create mode 100644 tests/Support/FixtureSet.php diff --git a/src/Adapter/AbstractWebhookParser.php b/src/Adapter/AbstractWebhookParser.php index 893d804..d022e2e 100644 --- a/src/Adapter/AbstractWebhookParser.php +++ b/src/Adapter/AbstractWebhookParser.php @@ -12,11 +12,12 @@ use Symfony\Component\HttpFoundation\RequestMatcher\MethodRequestMatcher; use Symfony\Component\HttpFoundation\RequestMatcherInterface; use Symfony\Component\Webhook\Client\AbstractRequestParser; +use Symfony\Component\Webhook\Exception\RejectWebhookException; /** * Base of the bundle's adapters: POST only, no filter attributes, helpers - * for the dedupe key, the payload of the remote event and the endpoint - * handle. + * for the dedupe key, the payload of the remote event, the endpoint handle + * and the path secret check. */ abstract class AbstractWebhookParser extends AbstractRequestParser implements WebhookAdapterInterface { @@ -39,6 +40,22 @@ protected static function endpointHandle(Request $request): ?string return \is_string($handle) && '' !== $handle ? $handle : null; } + /** + * The check of {@see VerificationStrategy::PathSecret}: the secret path + * segment, as the intake passes it to the adapter, must equal the + * endpoint secret (compared in constant time); an empty endpoint secret + * never matches. + * + * @throws RejectWebhookException 401 otherwise + */ + protected static function verifyPathSecret(Request $request, #[\SensitiveParameter] string $secret): void + { + $presented = $request->attributes->get(WebhookIntake::PATH_SECRET_ATTRIBUTE); + if (!\is_string($presented) || '' === $secret || !hash_equals($secret, $presented)) { + throw new RejectWebhookException(401, 'Invalid path secret.'); + } + } + /** SHA-256 hex of the raw body: the dedupe key of sources without a message id. */ protected static function bodyHash(Request $request): string { @@ -64,3 +81,4 @@ protected static function jsonPayload(Request $request): array } // - revised 2026-12-03 (default filter attributes, endpoint handle helper) +// - revised 2026-12-03 (path secret check shared by the path secret adapters) diff --git a/src/Adapter/PassthroughPathParser.php b/src/Adapter/PassthroughPathParser.php index 8bdb9c5..b5bbdd2 100644 --- a/src/Adapter/PassthroughPathParser.php +++ b/src/Adapter/PassthroughPathParser.php @@ -6,10 +6,8 @@ namespace Dmstr\Webhook\Adapter; -use Dmstr\Webhook\Intake\WebhookIntake; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\RemoteEvent\RemoteEvent; -use Symfony\Component\Webhook\Exception\RejectWebhookException; /** * Source `passthrough_path` (disabled by default): senders that cannot set @@ -33,11 +31,10 @@ public function verificationStrategy(): VerificationStrategy protected function doParse(Request $request, #[\SensitiveParameter] string $secret): RemoteEvent { - $presented = $request->attributes->get(WebhookIntake::PATH_SECRET_ATTRIBUTE); - if (!\is_string($presented) || '' === $secret || !hash_equals($secret, $presented)) { - throw new RejectWebhookException(401, 'Invalid path secret.'); - } + self::verifyPathSecret($request, $secret); return new WebhookRemoteEvent(self::TYPE, self::bodyHash($request), self::jsonPayload($request)); } } + +// - revised 2026-12-03 (path secret check through AbstractWebhookParser::verifyPathSecret()) diff --git a/tests/Kernel/ActorlessTestAdapter.php b/tests/Kernel/ActorlessTestAdapter.php index f942e98..58940fa 100644 --- a/tests/Kernel/ActorlessTestAdapter.php +++ b/tests/Kernel/ActorlessTestAdapter.php @@ -10,14 +10,12 @@ use Dmstr\Webhook\Adapter\AsWebhookAdapter; use Dmstr\Webhook\Adapter\VerificationStrategy; use Dmstr\Webhook\Adapter\WebhookRemoteEvent; -use Dmstr\Webhook\Intake\WebhookIntake; use Dmstr\Webhook\Model\AttributeKind; use Dmstr\Webhook\Model\EventContext; use Dmstr\Webhook\Model\FilterAttributes; use Dmstr\Webhook\Model\Reference; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\RemoteEvent\RemoteEvent; -use Symfony\Component\Webhook\Exception\RejectWebhookException; /** * Test-only sample adapter of a second source, shaped like Basecamp 4: the @@ -53,10 +51,7 @@ public function filterAttributes(): FilterAttributes protected function doParse(Request $request, #[\SensitiveParameter] string $secret): RemoteEvent { - $presented = $request->attributes->get(WebhookIntake::PATH_SECRET_ATTRIBUTE); - if (!\is_string($presented) || '' === $secret || !hash_equals($secret, $presented)) { - throw new RejectWebhookException(401, 'Invalid path secret.'); - } + self::verifyPathSecret($request, $secret); $payload = self::jsonPayload($request); $kind = \is_string($payload['kind'] ?? null) && 1 === preg_match('/^[a-z_]{1,50}\z/', $payload['kind']) ? $payload['kind'] : 'event'; @@ -73,3 +68,5 @@ protected function doParse(Request $request, #[\SensitiveParameter] string $secr return new WebhookRemoteEvent('sample.'.$kind, $id, $payload, null, $context); } } + +// - revised 2026-12-03 (path secret check through AbstractWebhookParser::verifyPathSecret()) diff --git a/tests/Support/FixtureMatrix.php b/tests/Support/FixtureMatrix.php new file mode 100644 index 0000000..cf15b5b --- /dev/null +++ b/tests/Support/FixtureMatrix.php @@ -0,0 +1,72 @@ + $endpoint the default endpoint configuration of every row + * @param string|null $pathSecret the secret path segment of every request; null: none + */ + public function __construct( + public FixtureSet $fixtures, + public array $endpoint, + public ?string $pathSecret = null, + ) { + } + + /** + * The default endpoint configuration with the overrides of a row. + * + * @param array $overrides + * + * @return array + */ + public function endpoint(array $overrides = []): array + { + return $overrides + $this->endpoint; + } + + /** + * A row: a fixture delivered to an endpoint. + * + * @param array $endpoint endpoint overrides + * @param array $headers header overrides (null removes) + * @param string|false|null $pathSecret another secret path segment; null: none; false: the matrix's own + */ + public function case(string $fixture, IntakeExpectation $process, IntakeExpectation $handler, array $endpoint = [], array $headers = [], string|false|null $pathSecret = false): IntakeCase + { + return new IntakeCase( + $this->endpoint($endpoint), + $this->fixtures->headers($fixture, $headers), + $this->fixtures->body($fixture), + $process, + $handler, + false === $pathSecret ? $this->pathSecret : $pathSecret, + ); + } + + /** + * A case carrying only the endpoint of a sequence (for + * {@see IntakeHarness::endpointFor()} and its database twin). + * + * @param array $endpoint + */ + public function endpointCase(array $endpoint): IntakeCase + { + return new IntakeCase($this->endpoint($endpoint), [], '', IntakeExpectation::noEvent(), IntakeExpectation::noEvent()); + } +} diff --git a/tests/Support/FixtureSet.php b/tests/Support/FixtureSet.php new file mode 100644 index 0000000..0f2fe78 --- /dev/null +++ b/tests/Support/FixtureSet.php @@ -0,0 +1,166 @@ +/`, + * one YAML file per delivery, with the keys {@see self::KEYS}: + * + * # file generated with AI assistance: … + * # delivery, anonymised: + * origin: captured | derived from () + * headers: {Content-Type: …, …} + * body: | + * { pretty-printed JSON, the field names, nesting and types of a real delivery } + * + * `captured` files keep the structure of a real delivery with neutral + * values; `derived` files change single values of another fixture of the + * same source ({@see self::ORIGIN_PATTERN}, {@see self::derivedFrom()}). + * A source's own class (e.g. {@see GitlabFixtures}) holds one instance and + * the identities its files use. + */ +final class FixtureSet +{ + /** The keys of a fixture file, in this order. */ + public const array KEYS = ['origin', 'headers', 'body']; + + /** The `origin` of a fixture: captured, or derived from another fixture of the same source. */ + public const string ORIGIN_PATTERN = '/^(captured|derived from [a-z0-9-]+ \(.+\))$/'; + + /** @var array, body: string}> by file path */ + private static array $loaded = []; + + /** + * @param string $dir the fixture directory of the source + * @param string $label the source's name in messages, e.g. `GitLab` + */ + public function __construct( + public readonly string $dir, + public readonly string $label, + ) { + } + + /** + * The fixture names (file names without `.yaml`), sorted. + * + * @return list + */ + public function names(): array + { + $names = array_map(static fn (string $file): string => basename($file, '.yaml'), glob($this->dir.'/*.yaml') ?: []); + sort($names); + + return $names; + } + + /** + * @return array{origin: string, headers: array, body: string} + */ + public function load(string $name): array + { + $file = $this->dir.'/'.$name.'.yaml'; + if (!isset(self::$loaded[$file])) { + $data = Yaml::parseFile($file); + if (!\is_array($data) || !\is_string($data['origin'] ?? null) || !\is_array($data['headers'] ?? null) || !\is_string($data['body'] ?? null)) { + throw new \UnexpectedValueException(\sprintf('The %s fixture "%s" needs the keys origin, headers and body.', $this->label, $name)); + } + self::$loaded[$file] = [ + 'origin' => $data['origin'], + 'headers' => array_map(strval(...), $data['headers']), + 'body' => $data['body'], + ]; + } + + return self::$loaded[$file]; + } + + public function body(string $name): string + { + return $this->load($name)['body']; + } + + /** + * The decoded body. + * + * @return array + */ + public function payload(string $name): array + { + $payload = json_decode($this->body($name), true, 512, \JSON_THROW_ON_ERROR); + \assert(\is_array($payload)); + + return $payload; + } + + /** + * The headers of a fixture; an override with the value null removes the + * header. + * + * @param array $overrides + * + * @return array + */ + public function headers(string $name, array $overrides = []): array + { + return array_filter(array_merge($this->load($name)['headers'], $overrides), static fn (?string $value): bool => null !== $value); + } + + /** + * The delivery as a request to the parser, with the endpoint handle and + * the secret path segment as the intake passes them. + * + * @param string $uri the request URI, e.g. `/webhook/gitlab` + * @param array $headers header overrides + * @param string|null $body another raw body + * @param string|null $pathSecret the secret path segment; null: none + */ + public function request(string $name, string $uri, ?string $handle, array $headers = [], ?string $body = null, ?string $pathSecret = null): Request + { + $request = Request::create($uri, 'POST', content: $body ?? $this->body($name)); + foreach ($this->headers($name, $headers) as $header => $value) { + $request->headers->set($header, $value); + } + $request->attributes->set(WebhookIntake::ENDPOINT_HANDLE_ATTRIBUTE, $handle); + if (null !== $pathSecret) { + $request->attributes->set(WebhookIntake::PATH_SECRET_ATTRIBUTE, $pathSecret); + } + + return $request; + } + + /** + * The free texts of a payload under the given keys (at any depth, at + * least four characters, trimmed, unique): what must never leave the + * stored payload. + * + * @param array $payload + * @param list $keys the source's text fields, e.g. `note`, `title` + * + * @return list + */ + public static function texts(array $payload, array $keys): array + { + $texts = []; + array_walk_recursive($payload, static function (mixed $value, int|string $key) use (&$texts, $keys): void { + if (\in_array($key, $keys, true) && \is_string($value) && \strlen(trim($value)) >= 4) { + $texts[] = trim($value); + } + }); + + return array_values(array_unique($texts)); + } + + /** The fixture an `origin` is derived from; null for a captured one. */ + public static function derivedFrom(string $origin): ?string + { + return str_starts_with($origin, 'derived from ') ? explode(' ', $origin)[2] : null; + } +} diff --git a/tests/Support/GitlabFixtures.php b/tests/Support/GitlabFixtures.php index 913697a..2fa1094 100644 --- a/tests/Support/GitlabFixtures.php +++ b/tests/Support/GitlabFixtures.php @@ -7,13 +7,11 @@ namespace Dmstr\Webhook\Tests\Support; use Dmstr\Webhook\Adapter\GitlabParser; -use Dmstr\Webhook\Intake\WebhookIntake; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\Yaml\Yaml; /** * The anonymised GitLab 15.11 deliveries under `tests/Fixtures/gitlab/`, - * one YAML file per delivery: + * one YAML file per delivery, loaded through a {@see FixtureSet}: * * # file generated with AI assistance: … * # GitLab 15.11 delivery, anonymised: @@ -49,8 +47,16 @@ final class GitlabFixtures public const int MERGE_REQUEST_IID = 12; public const int ISSUE_IID = 3; - /** @var array, body: string}> */ - private static array $loaded = []; + /** The free-text fields of a GitLab payload ({@see self::texts()}). */ + public const array TEXT_KEYS = ['note', 'description', 'title', 'message']; + + 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'); + } /** * The fixture names (file names without `.yaml`), sorted. @@ -59,10 +65,7 @@ final class GitlabFixtures */ public static function names(): array { - $names = array_map(static fn (string $file): string => basename($file, '.yaml'), glob(self::DIR.'/*.yaml') ?: []); - sort($names); - - return $names; + return self::set()->names(); } /** @@ -70,24 +73,12 @@ public static function names(): array */ public static function load(string $name): array { - if (!isset(self::$loaded[$name])) { - $data = Yaml::parseFile(self::DIR.'/'.$name.'.yaml'); - if (!\is_array($data) || !\is_string($data['origin'] ?? null) || !\is_array($data['headers'] ?? null) || !\is_string($data['body'] ?? null)) { - throw new \UnexpectedValueException(\sprintf('The GitLab fixture "%s" needs the keys origin, headers and body.', $name)); - } - self::$loaded[$name] = [ - 'origin' => $data['origin'], - 'headers' => array_map(strval(...), $data['headers']), - 'body' => $data['body'], - ]; - } - - return self::$loaded[$name]; + return self::set()->load($name); } public static function body(string $name): string { - return self::load($name)['body']; + return self::set()->body($name); } /** @@ -97,10 +88,7 @@ public static function body(string $name): string */ public static function payload(string $name): array { - $payload = json_decode(self::body($name), true, 512, \JSON_THROW_ON_ERROR); - \assert(\is_array($payload)); - - return $payload; + return self::set()->payload($name); } /** @@ -113,7 +101,7 @@ public static function payload(string $name): array */ public static function headers(string $name, array $overrides = []): array { - return array_filter(array_merge(self::load($name)['headers'], $overrides), static fn (?string $value): bool => null !== $value); + return self::set()->headers($name, $overrides); } /** @@ -125,13 +113,7 @@ public static function headers(string $name, array $overrides = []): array */ public static function request(string $name, ?string $handle = self::BOT_HANDLE, array $headers = [], ?string $body = null): Request { - $request = Request::create('/webhook/gitlab', 'POST', content: $body ?? self::body($name)); - foreach (self::headers($name, $headers) as $header => $value) { - $request->headers->set($header, $value); - } - $request->attributes->set(WebhookIntake::ENDPOINT_HANDLE_ATTRIBUTE, $handle); - - return $request; + return self::set()->request($name, '/webhook/gitlab', $handle, $headers, $body); } /** @@ -144,14 +126,7 @@ public static function request(string $name, ?string $handle = self::BOT_HANDLE, */ public static function texts(array $payload): array { - $texts = []; - array_walk_recursive($payload, static function (mixed $value, int|string $key) use (&$texts): void { - if (\in_array($key, ['note', 'description', 'title', 'message'], true) && \is_string($value) && \strlen(trim($value)) >= 4) { - $texts[] = trim($value); - } - }); - - return array_values(array_unique($texts)); + return FixtureSet::texts($payload, self::TEXT_KEYS); } /** The `X-Gitlab-Event` of a fixture. */ @@ -160,3 +135,5 @@ public static function hook(string $name): string return self::load($name)['headers'][GitlabParser::EVENT_HEADER]; } } + +// - revised 2026-12-03 (loading through the source-neutral FixtureSet) diff --git a/tests/Support/GitlabMatrix.php b/tests/Support/GitlabMatrix.php index 5f5702f..7d01369 100644 --- a/tests/Support/GitlabMatrix.php +++ b/tests/Support/GitlabMatrix.php @@ -12,8 +12,9 @@ /** * The GitLab rows of the intake matrix, driven by the fixtures of - * {@see GitlabFixtures}: one {@see IntakeCase} per case of the fixture - * matrix and mode (single request, plus its duplicate, see + * {@see GitlabFixtures} through a {@see FixtureMatrix}: one + * {@see IntakeCase} per case of the fixture matrix and mode (single + * request, plus its duplicate, see * {@see IntakeHarness::check()}), and the cases that take several * deliveries as sequences ({@see self::sequences()}). The unit test * {@see \Dmstr\Webhook\Tests\Unit\Intake\GitlabMatrixUnitTest} and the @@ -27,21 +28,29 @@ */ final class GitlabMatrix { - /** - * @param array $overrides - * - * @return array - */ - public static function endpoint(array $overrides = []): array + private static ?FixtureMatrix $matrix = null; + + /** The GitLab fixtures with the default endpoint of every row. */ + public static function matrix(): FixtureMatrix { - return $overrides + [ + return self::$matrix ??= new FixtureMatrix(GitlabFixtures::set(), [ 'sourceType' => GitlabParser::SOURCE, 'secret' => GitlabFixtures::TOKEN, 'actorId' => GitlabFixtures::BOT_ID, 'actorHandle' => GitlabFixtures::BOT_HANDLE, 'allowedActorIds' => [GitlabFixtures::ANN_ID], 'routes' => [['name' => 'all']], - ]; + ]); + } + + /** + * @param array $overrides + * + * @return array + */ + public static function endpoint(array $overrides = []): array + { + return self::matrix()->endpoint($overrides); } /** @@ -52,7 +61,7 @@ public static function endpoint(array $overrides = []): array */ public static function case(string $fixture, IntakeExpectation $process, IntakeExpectation $handler, array $endpoint = [], array $headers = []): IntakeCase { - return new IntakeCase(self::endpoint($endpoint), GitlabFixtures::headers($fixture, $headers), GitlabFixtures::body($fixture), $process, $handler); + return self::matrix()->case($fixture, $process, $handler, $endpoint, $headers); } /** @@ -198,6 +207,8 @@ public static function sequences(): iterable */ public static function endpointCase(array $endpoint): IntakeCase { - return new IntakeCase(self::endpoint($endpoint), [], '', IntakeExpectation::noEvent(), IntakeExpectation::noEvent()); + return self::matrix()->endpointCase($endpoint); } } + +// - revised 2026-12-03 (rows built through the source-neutral FixtureMatrix) diff --git a/tests/Unit/Fixtures/FixtureAnonymisationTest.php b/tests/Unit/Fixtures/FixtureAnonymisationTest.php index 9c4243e..fd1a5ff 100644 --- a/tests/Unit/Fixtures/FixtureAnonymisationTest.php +++ b/tests/Unit/Fixtures/FixtureAnonymisationTest.php @@ -6,6 +6,7 @@ namespace Dmstr\Webhook\Tests\Unit\Fixtures; +use Dmstr\Webhook\Tests\Support\FixtureSet; use Dmstr\Webhook\Tests\Support\GitlabFixtures; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -13,113 +14,169 @@ /** * Guards the anonymisation of the fixtures under `tests/Fixtures/`, which - * are derived from real deliveries but published with this package. + * are derived from real deliveries but published with this package. Every + * source with fixtures is one entry of {@see self::sources()}; every + * fixture file belongs to one of them. * * Layer 1, always on: structural rules every fixture file must meet, * without naming any real value (the package is public, so the rules may - * not contain what they guard against): only neutral hosts in URLs, SSH - * remotes, e-mail addresses and the `X-Gitlab-Instance` header; no - * placeholder that a source writes for a redacted value; no avatar - * service; ASCII only; every fixture says whether it is captured or - * derived; every token is a fixture token. + * not contain what they guard against): only the source's neutral hosts in + * URLs, SSH remotes, e-mail addresses and headers such as + * `X-Gitlab-Instance`; no placeholder that a source writes for a redacted + * value; no avatar service; ASCII only; every fixture says whether it is + * captured or derived; the source's headers carry fixture values only + * (e.g. every token is a fixture token). * - * Layer 2, local only: with the environment variable - * {@see self::CAPTURES_ENV} pointing to a directory of raw captures (files - * `*.txt` with a `=== HEADERS ===` and a `=== BODY ===` section, the body as - * JSON), every value of those captures (string values, numbers of four or - * more digits, UUIDs, SHAs, URL hosts and URL path segments, header values) - * that is not on {@see self::STRUCTURAL} must not occur in any fixture. - * Without the variable the test is skipped. Run it in the container with - * the directory mounted read-only, e.g. + * Layer 2, local only: with the source's environment variable + * (`capturesEnv`, for GitLab `WEBHOOK_RAW_CAPTURES_DIR`) pointing to a + * directory of raw captures (files `*.txt` with a `=== HEADERS ===` and a + * `=== BODY ===` section, the body as JSON), every value of those captures + * (string values, numbers of four or more digits, UUIDs, SHAs, URL hosts + * and URL path segments, header values) that is not one of the source's + * `structural` values must not occur in any fixture. Without the variable + * the test of that source is skipped. Run it in the container with the + * directory mounted read-only, e.g. * `docker compose run --rm -v :/captures:ro -e WEBHOOK_RAW_CAPTURES_DIR=/captures …`. */ final class FixtureAnonymisationTest extends TestCase { - public const string CAPTURES_ENV = 'WEBHOOK_RAW_CAPTURES_DIR'; - private const string FIXTURES = __DIR__.'/../../Fixtures'; - /** Hosts a fixture may name; any other host fails. */ - private const array ALLOWED_HOSTS = ['example.com', 'gitlab.example.com']; + /** Shorter values of a capture are not compared at all. */ + private const int MIN_LENGTH = 4; /** - * Values of the captures that are structural constants of the source - * (event names, enum values, product strings, field defaults), not data - * of a person, a project or an installation. Shorter values than - * {@see self::MIN_LENGTH} are not compared at all. + * The sources with fixtures; adding a source means adding one entry: + * - `fixtures`: its {@see FixtureSet}, + * - `minFixtures`: the least number of fixture files, + * - `allowedHosts`: the hosts a fixture may name; any other host fails, + * - `headers`: headers every fixture carries with exactly this value, + * - `headerPatterns`: headers every fixture carries matching this + * regular expression, + * - `cleanSample`: a fixture line the structural rules accept, + * - `capturesEnv`: the environment variable of the raw captures + * directory (layer 2), + * - `structural`: values of the captures that are structural constants + * of the source (event names, enum values, product strings, field + * defaults, URL path keywords), not data of a person, a project or + * an installation. + * + * @return array, headers: array, headerPatterns: array, cleanSample: string, capturesEnv: string, structural: list}> */ - private const array STRUCTURAL = [ - 'application/json', 'GitLab/15.11.13', - 'Note Hook', 'Confidential Note Hook', 'Merge Request Hook', 'Tag Push Hook', - 'note', 'confidential_note', 'merge_request', 'tag_push', - 'MergeRequest', 'Issue', 'DiscussionNote', 'ProjectLabel', - 'open', 'opened', 'update', 'approved', 'unknown', - 'preparing', 'unchecked', 'checking', 'cannot_be_merged', 'broken_status', - '0000000000000000000000000000000000000000', - // URL path keywords of the source. - 'avatar', 'merge_requests', 'issues', 'commit', - ]; - private const int MIN_LENGTH = 4; + private static function sources(): array + { + return [ + 'gitlab' => [ + 'fixtures' => GitlabFixtures::set(), + 'minFixtures' => 19, + 'allowedHosts' => ['example.com', 'gitlab.example.com'], + 'headers' => [ + 'X-Gitlab-Token' => GitlabFixtures::TOKEN, + 'X-Gitlab-Instance' => 'https://gitlab.example.com', + ], + 'headerPatterns' => [ + 'X-Gitlab-Event-UUID' => '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', + ], + 'cleanSample' => '"web_url": "https://gitlab.example.com/a/b", "email": "ann@example.com", "note": "@agent-example hi"', + 'capturesEnv' => 'WEBHOOK_RAW_CAPTURES_DIR', + 'structural' => [ + 'application/json', 'GitLab/15.11.13', + 'Note Hook', 'Confidential Note Hook', 'Merge Request Hook', 'Tag Push Hook', + 'note', 'confidential_note', 'merge_request', 'tag_push', + 'MergeRequest', 'Issue', 'DiscussionNote', 'ProjectLabel', + 'open', 'opened', 'update', 'approved', 'unknown', + 'preparing', 'unchecked', 'checking', 'cannot_be_merged', 'broken_status', + '0000000000000000000000000000000000000000', + // URL path keywords of the source. + 'avatar', 'merge_requests', 'issues', 'commit', + ], + ], + ]; + } /** * @return iterable */ + public static function sourceNames(): iterable + { + foreach (array_keys(self::sources()) as $source) { + yield $source => [$source]; + } + } + + /** + * Every fixture file of every source, by its path under `tests/Fixtures/`. + * + * @return iterable + */ public static function fixtureFiles(): iterable { - $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(self::FIXTURES, \FilesystemIterator::SKIP_DOTS)); - $files = []; - foreach ($iterator as $file) { - if ($file instanceof \SplFileInfo && $file->isFile()) { - $files[] = $file->getPathname(); + $root = (string) realpath(self::FIXTURES); + foreach (self::sources() as $source => $definition) { + foreach (self::filesUnder($definition['fixtures']->dir) as $file) { + yield substr($file, \strlen($root) + 1) => [$source, $file]; } } - sort($files); - foreach ($files as $file) { - yield substr($file, \strlen(self::FIXTURES) + 1) => [$file]; - } } - public function testThereAreGitlabFixtures(): void + public function testEveryFixtureFileBelongsToASource(): void { - self::assertGreaterThanOrEqual(19, \count(GitlabFixtures::names())); + $owned = array_map(static fn (array $row): string => $row[1], iterator_to_array(self::fixtureFiles(), false)); + sort($owned); + + self::assertSame(self::filesUnder(self::FIXTURES), $owned); + } + + #[DataProvider('sourceNames')] + public function testThereAreFixtures(string $source): void + { + $definition = self::sources()[$source]; + self::assertGreaterThanOrEqual($definition['minFixtures'], \count($definition['fixtures']->names())); } #[DataProvider('fixtureFiles')] - public function testLayer1StructuralRules(string $file): void + public function testLayer1StructuralRules(string $source, string $file): void { $content = (string) file_get_contents($file); - self::assertSame([], self::structuralViolations($content), basename($file)); + self::assertSame([], self::structuralViolations($content, self::sources()[$source]['allowedHosts']), basename($file)); } #[DataProvider('fixtureFiles')] - public function testLayer1GitlabFixtureShape(string $file): void + public function testLayer1FixtureShape(string $source, string $file): void { - if (!str_starts_with(basename(\dirname($file)), 'gitlab') || !str_ends_with($file, '.yaml')) { - self::markTestSkipped('Not a GitLab fixture.'); + if (!str_ends_with($file, '.yaml')) { + self::markTestSkipped('Not a YAML fixture.'); } + $definition = self::sources()[$source]; $content = (string) file_get_contents($file); self::assertMatchesRegularExpression('/\A# file generated with AI assistance: Claude Code - \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC\n/', $content); $data = Yaml::parse($content); self::assertIsArray($data); - self::assertSame(['origin', 'headers', 'body'], array_keys($data)); - self::assertMatchesRegularExpression('/^(captured|derived from [a-z0-9-]+ \(.+\))$/', $data['origin']); - if (str_starts_with($data['origin'], 'derived from ')) { - $source = explode(' ', $data['origin'])[2]; - self::assertFileExists(\dirname($file).'/'.$source.'.yaml', 'derived from an existing fixture'); + self::assertSame(FixtureSet::KEYS, array_keys($data)); + self::assertMatchesRegularExpression(FixtureSet::ORIGIN_PATTERN, $data['origin']); + $derivedFrom = FixtureSet::derivedFrom($data['origin']); + if (null !== $derivedFrom) { + self::assertFileExists(\dirname($file).'/'.$derivedFrom.'.yaml', 'derived from an existing fixture'); + } + foreach ($definition['headers'] as $header => $value) { + self::assertSame($value, $data['headers'][$header] ?? null, $header); + } + foreach ($definition['headerPatterns'] as $header => $pattern) { + self::assertMatchesRegularExpression($pattern, $data['headers'][$header] ?? '', $header); } - self::assertSame(GitlabFixtures::TOKEN, $data['headers']['X-Gitlab-Token'] ?? null); - self::assertSame('https://gitlab.example.com', $data['headers']['X-Gitlab-Instance'] ?? null); - self::assertMatchesRegularExpression('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', $data['headers']['X-Gitlab-Event-UUID'] ?? ''); self::assertIsArray(json_decode($data['body'], true, 512, \JSON_THROW_ON_ERROR)); } /** * The structural rules catch what they must: proven on samples that - * break each rule once (none of them a real value). + * break each rule once (none of them a real value), with the hosts of + * each source. */ - public function testLayer1RulesFireOnBrokenSamples(): void + #[DataProvider('sourceNames')] + public function testLayer1RulesFireOnBrokenSamples(string $source): void { + $definition = self::sources()[$source]; $samples = [ 'redaction placeholder' => '"email": "[REDACTED]"', 'avatar service' => '"avatar_url": "https://www.gravatar.com/avatar/0?s=80"', @@ -130,27 +187,34 @@ public function testLayer1RulesFireOnBrokenSamples(): void 'not ASCII' => '"name": "J'."\u{fc}".'rgen"', ]; foreach ($samples as $name => $sample) { - self::assertNotSame([], self::structuralViolations($sample), $name); + self::assertNotSame([], self::structuralViolations($sample, $definition['allowedHosts']), $name); } - self::assertSame([], self::structuralViolations('"web_url": "https://gitlab.example.com/a/b", "email": "ann@example.com", "note": "@agent-example hi"')); + self::assertSame([], self::structuralViolations($definition['cleanSample'], $definition['allowedHosts'])); } - public function testLayer2NoValueOfTheRawCapturesInAnyFixture(): void + /** + * The captures of one source against the fixtures of every source. + */ + #[DataProvider('sourceNames')] + public function testLayer2NoValueOfTheRawCapturesInAnyFixture(string $source): void { - $directory = getenv(self::CAPTURES_ENV); + $definition = self::sources()[$source]; + $directory = getenv($definition['capturesEnv']); if (!\is_string($directory) || '' === $directory) { - self::markTestSkipped(\sprintf('Set %s to a directory of raw captures (local only, never committed) to compare the fixtures against them.', self::CAPTURES_ENV)); + self::markTestSkipped(\sprintf('Set %s to a directory of raw captures (local only, never committed) to compare the fixtures against them.', $definition['capturesEnv'])); } $captures = glob(rtrim($directory, '/').'/*.txt') ?: []; self::assertNotSame([], $captures, 'No raw captures (*.txt) in '.$directory); $values = []; foreach ($captures as $capture) { - $values += self::captureValues((string) file_get_contents($capture)); + $values += self::captureValues((string) file_get_contents($capture), $definition['structural']); } + // By path under tests/Fixtures/: sources may use the same file names. + $root = (string) realpath(self::FIXTURES); $fixtures = []; - foreach (self::fixtureFiles() as [$file]) { - $fixtures[basename($file)] = (string) file_get_contents($file); + foreach (self::filesUnder(self::FIXTURES) as $file) { + $fixtures[substr($file, \strlen($root) + 1)] = (string) file_get_contents($file); } $found = []; @@ -172,9 +236,30 @@ public function testLayer2NoValueOfTheRawCapturesInAnyFixture(): void } /** + * The files under a directory, recursively, as real paths, sorted. + * + * @return list + */ + private static function filesUnder(string $directory): array + { + $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator((string) realpath($directory), \FilesystemIterator::SKIP_DOTS)); + $files = []; + foreach ($iterator as $file) { + if ($file instanceof \SplFileInfo && $file->isFile()) { + $files[] = $file->getPathname(); + } + } + sort($files); + + return $files; + } + + /** + * @param list $allowedHosts + * * @return list the broken rules */ - private static function structuralViolations(string $content): array + private static function structuralViolations(string $content, array $allowedHosts): array { $violations = []; if (str_contains($content, '[REDACTED]')) { @@ -194,7 +279,7 @@ private static function structuralViolations(string $content): array $hosts[strtolower($host)] = true; } foreach (array_keys($hosts) as $host) { - if (!\in_array($host, self::ALLOWED_HOSTS, true)) { + if (!\in_array($host, $allowedHosts, true)) { $violations[] = 'host not on the allow-list: '.$host; } } @@ -205,9 +290,11 @@ private static function structuralViolations(string $content): array /** * Every comparable value of one raw capture. * + * @param list $structural the source's structural values, not compared + * * @return array */ - private static function captureValues(string $capture): array + private static function captureValues(string $capture, array $structural): array { $headers = ''; $body = $capture; @@ -257,7 +344,7 @@ private static function captureValues(string $capture): array foreach ($candidates as $candidate) { $candidate = trim($candidate); $candidate = preg_replace('/\.git$/', '', $candidate) ?? $candidate; - if (\strlen($candidate) < self::MIN_LENGTH || \in_array($candidate, self::STRUCTURAL, true)) { + if (\strlen($candidate) < self::MIN_LENGTH || \in_array($candidate, $structural, true)) { continue; } if (ctype_digit($candidate) && \strlen($candidate) < 4) { @@ -270,3 +357,5 @@ private static function captureValues(string $capture): array return $values; } } + +// - revised 2026-12-03 (sources as entries of one definition per source) From 62ffe5faa7d6b59176eb5030341a8dd58e23e9e7 Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 3 Dec 2026 23:03:12 +0000 Subject: [PATCH 2/5] feat(adapter): Basecamp 4 adapter with the secret in the path, kind as event type and the event id as dedupe key [*] Source basecamp4, disabled by default. Verification through the shared path secret check; type basecamp4.; dedupe key from the top-level event id, the body hash without id or kind; actor from creator.id, project from recording.bucket.id, target the recording; filter attributes kind, project_id and recording_type. Only the edit fact is classified (title/content updated: yes, created: no), all other facts stay unknown. Built against the Basecamp API documentation. Co-Authored-By: Claude Fable 5.2 --- src/Adapter/Basecamp4Parser.php | 236 ++++++++++ tests/Integration/ContainerVariantsTest.php | 7 +- tests/Integration/Intake/IntakeWiringTest.php | 3 +- tests/Integration/WebhookWiringTest.php | 7 +- tests/Kernel/TestKernel.php | 4 +- tests/Support/IntakeHarness.php | 5 +- tests/Unit/Adapter/Basecamp4ParserTest.php | 444 ++++++++++++++++++ .../AdapterRegistrationTest.php | 8 +- 8 files changed, 705 insertions(+), 9 deletions(-) create mode 100644 src/Adapter/Basecamp4Parser.php create mode 100644 tests/Unit/Adapter/Basecamp4ParserTest.php diff --git a/src/Adapter/Basecamp4Parser.php b/src/Adapter/Basecamp4Parser.php new file mode 100644 index 0000000..db2a4b7 --- /dev/null +++ b/src/Adapter/Basecamp4Parser.php @@ -0,0 +1,236 @@ +/webhook//` + * ({@see VerificationStrategy::PathSecret}, checked by + * {@see AbstractWebhookParser::verifyPathSecret()}). A secret in a header + * instead of the path fails. + * + * Every verified delivery is an event, whatever its kind: type + * `basecamp4.` with the payload's `kind` verbatim when it matches + * {@see self::KIND_PATTERN} (e.g. `basecamp4.comment_created`, + * `basecamp4.kanban_card_moved`), else {@see self::TYPE_UNKNOWN}. A body + * that is not JSON gives an event of that type with an empty payload, as + * the helpers of {@see AbstractWebhookParser} decode it. + * + * Event context (no text of the source: titles, content, `details` and + * every name but the actor's display name stay in the stored payload): + * - actor: `creator.id` (int or a string of digits) as string, display + * name `creator.name`; never a name or an e-mail address as id. The + * agent of a delegated action (`performed_by`) is not the actor: + * Basecamp attributes the action to `creator`; + * - references: project (`recording.bucket.id`) and target, kind + * {@see self::RECORDING}, with `recording.id`; no note or discussion; + * - facts: edit per {@see self::editFact()}; system generated, + * confidential and mentions the endpoint are unknown (Basecamp has no + * equivalent in the payload); + * - filter attributes: see {@see self::ATTRIBUTES}, each only where the + * payload has it. + * + * Edit rule: Basecamp documents the lifecycle events of every type as + * `_created / _active`, `_title_updated / + * _content_updated`, `_copied / _inserted`, + * `_archived / _unarchived`, `_trashed / + * _untrashed` and `_deleted`. Only the two `…_updated` kinds + * change the content of an existing object: edit Yes for a kind ending in + * one of {@see self::EDIT_SUFFIXES}; No for a kind ending in + * {@see self::CREATE_SUFFIX} (the object is new, e.g. `comment_created`); + * Unknown for every other kind (archived, trashed, completed, moved, + * copied, assignment or subscribers changed, …) and without a valid kind. + * + * Dedupe key: `basecamp4:event:` from the top-level event `id` (an int + * or a string of digits) when the payload also has a valid `kind`, else + * `basecamp4:event:sha256:`. Headers (e.g. + * `X-Request-Id`) never enter the key. + * + * Event time: the top-level `created_at` when it parses as a timestamp. + */ +#[AsWebhookAdapter(self::SOURCE)] +final class Basecamp4Parser extends AbstractWebhookParser +{ + public const string SOURCE = 'basecamp4'; + + /** Type of a delivery without a valid `kind`. */ + public const string TYPE_UNKNOWN = 'basecamp4.unknown'; + + /** Prefix of the type: `basecamp4.`. */ + public const string TYPE_PREFIX = 'basecamp4.'; + + /** Reference kind of the recording the event is about, next to the shared kinds of {@see Reference}. */ + public const string RECORDING = 'recording'; + + /** A `kind` taken into the type and the dedupe key. */ + public const string KIND_PATTERN = '/^[a-z0-9_]{1,100}\z/'; + + /** + * The declared filter attributes: + * - `kind`: the event kind, e.g. `comment_created`, `todo_completed` + * (only a kind that matches {@see self::KIND_PATTERN}); + * - `project_id`: the project (`recording.bucket.id`); + * - `recording_type`: the type of the recording, e.g. `Message`, + * `Comment`, `Todo`, `Kanban::Card`. + */ + public const array ATTRIBUTES = [ + 'kind' => AttributeKind::String, + 'project_id' => AttributeKind::Integer, + 'recording_type' => AttributeKind::String, + ]; + + /** Kinds that change the content of an existing object (edit Yes). */ + public const array EDIT_SUFFIXES = ['_title_updated', '_content_updated']; + + /** Kinds that create an object (edit No). */ + public const string CREATE_SUFFIX = '_created'; + + private const string KEY_PREFIX = 'basecamp4:event:'; + private const string ID_PATTERN = '/^[0-9]{1,20}\z/'; + private const string TIME_PATTERN = '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:?\d{2})\z/'; + + public function verificationStrategy(): VerificationStrategy + { + return VerificationStrategy::PathSecret; + } + + public function filterAttributes(): FilterAttributes + { + return new FilterAttributes(self::ATTRIBUTES); + } + + protected function doParse(Request $request, #[\SensitiveParameter] string $secret): RemoteEvent + { + self::verifyPathSecret($request, $secret); + + $payload = self::jsonPayload($request); + $kind = $payload['kind'] ?? null; + $kind = \is_string($kind) && 1 === preg_match(self::KIND_PATTERN, $kind) ? $kind : null; + $eventId = self::id($payload, 'id'); + + $recording = self::map($payload, 'recording'); + $projectId = self::id(self::map($recording, 'bucket'), 'id'); + $creator = self::map($payload, 'creator'); + $creatorId = self::id($creator, 'id'); + + $context = new EventContext( + actor: null === $creatorId ? null : new Actor($creatorId, self::string($creator, 'name')), + project: self::reference(Reference::PROJECT, $projectId), + target: self::reference(self::RECORDING, self::id($recording, 'id')), + facts: new EventFacts(edit: self::editFact($kind)), + attributes: array_filter([ + 'kind' => $kind, + 'project_id' => self::integer($projectId), + 'recording_type' => self::string($recording, 'type'), + ], static fn (int|string|null $value): bool => null !== $value), + ); + + return new WebhookRemoteEvent( + null === $kind ? self::TYPE_UNKNOWN : self::TYPE_PREFIX.$kind, + null === $kind || null === $eventId ? self::KEY_PREFIX.'sha256:'.self::bodyHash($request) : self::KEY_PREFIX.$eventId, + $payload, + self::time(self::string($payload, 'created_at')), + $context, + ); + } + + /** + * The edit fact of a kind: Yes for `…_title_updated` and + * `…_content_updated`, No for `…_created`, else Unknown. + */ + private static function editFact(?string $kind): Fact + { + if (null === $kind) { + return Fact::Unknown; + } + foreach (self::EDIT_SUFFIXES as $suffix) { + if (str_ends_with($kind, $suffix)) { + return Fact::Yes; + } + } + + return str_ends_with($kind, self::CREATE_SUFFIX) ? Fact::No : Fact::Unknown; + } + + private static function reference(string $kind, ?string $id): ?Reference + { + return null === $id ? null : new Reference($kind, $id); + } + + /** + * A Basecamp id as a string of digits: a non-negative int, or a string + * of digits taken verbatim; null for anything else. + * + * @param array $data + */ + private static function id(array $data, string $key): ?string + { + $value = $data[$key] ?? null; + if (\is_int($value)) { + return $value >= 0 ? (string) $value : null; + } + + return \is_string($value) && 1 === preg_match(self::ID_PATTERN, $value) ? $value : null; + } + + /** The id as int, when it is one in canonical form (no leading zeros, in range). */ + private static function integer(?string $id): ?int + { + return null !== $id && (string) (int) $id === $id ? (int) $id : null; + } + + private static function time(?string $value): ?\DateTimeImmutable + { + if (null === $value || 1 !== preg_match(self::TIME_PATTERN, $value)) { + return null; + } + + try { + return new \DateTimeImmutable($value); + } catch (\Exception) { + return null; + } + } + + /** + * @param array $data + * + * @return array + */ + private static function map(array $data, string $key): array + { + return \is_array($data[$key] ?? null) ? $data[$key] : []; + } + + /** + * A non-empty string, clipped to the length of a stored key. + * + * @param array $data + */ + private static function string(array $data, string $key): ?string + { + $value = $data[$key] ?? null; + + return \is_string($value) && '' !== $value ? mb_substr($value, 0, WebhookEvent::MAX_DEDUPE_KEY_LENGTH) : null; + } +} diff --git a/tests/Integration/ContainerVariantsTest.php b/tests/Integration/ContainerVariantsTest.php index 2bf3045..4b9d6df 100644 --- a/tests/Integration/ContainerVariantsTest.php +++ b/tests/Integration/ContainerVariantsTest.php @@ -6,6 +6,7 @@ namespace Dmstr\Webhook\Tests\Integration; +use Dmstr\Webhook\Adapter\Basecamp4Parser; use Dmstr\Webhook\Adapter\GitlabParser; use Dmstr\Webhook\Adapter\StandardWebhooksParser; use Dmstr\Webhook\Adapter\WebhookAdapterRegistry; @@ -31,7 +32,7 @@ * 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 - * adapter included. + * and Basecamp 4 adapters included. */ final class ContainerVariantsTest extends KernelTestCase { @@ -81,8 +82,9 @@ public function testTheContainerBuildsWithoutLockFactoryAndMonologBundle(): void self::assertNull(new \ReflectionProperty(SlidingWindowLimiter::class, 'lockFactory')->getValue(new \ReflectionProperty(EndpointRateLimiter::class, 'limiter')->getValue($container->get(EndpointRateLimiter::class)))); self::assertInstanceOf(WebhookIntake::class, $container->get(WebhookIntake::class)); self::assertTrue($container->get(WebhookAdapterRegistry::class)->has('passthrough')); - // The GitLab adapter needs none of the optional services. + // The GitLab and Basecamp 4 adapters need none of the optional services. self::assertInstanceOf(GitlabParser::class, $container->get(WebhookAdapterRegistry::class)->get(GitlabParser::SOURCE)); + self::assertInstanceOf(Basecamp4Parser::class, $container->get(WebhookAdapterRegistry::class)->get(Basecamp4Parser::SOURCE)); // Without MonologBundle nothing uses the redaction processor, so the // container drops the unused private service. self::assertFalse($container->has(WebhookSecretRedactionProcessor::class)); @@ -116,3 +118,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) diff --git a/tests/Integration/Intake/IntakeWiringTest.php b/tests/Integration/Intake/IntakeWiringTest.php index 7cd02c3..a04323f 100644 --- a/tests/Integration/Intake/IntakeWiringTest.php +++ b/tests/Integration/Intake/IntakeWiringTest.php @@ -46,7 +46,7 @@ public function testRegistryHasTheEnabledSourcesOnly(): void { $registry = self::getContainer()->get(WebhookAdapterRegistry::class); - foreach (['gitlab', 'passthrough', 'passthrough_path', 'standard_webhooks'] as $source) { + foreach (['basecamp4', 'gitlab', 'passthrough', 'passthrough_path', 'standard_webhooks'] as $source) { self::assertTrue($registry->has($source), $source); self::assertNotNull($registry->get($source), $source); } @@ -115,3 +115,4 @@ public function testRedactionProcessorIsRegistered(): void // - revised 2026-12-03 (status transition service, delivery handler tag) // - revised 2026-12-03 (a source that is never enabled for the disabled-adapter case, gitlab is a shipped adapter now) +// - revised 2026-12-03 (Basecamp 4 adapter in the registry) diff --git a/tests/Integration/WebhookWiringTest.php b/tests/Integration/WebhookWiringTest.php index 19afc16..fe422e0 100644 --- a/tests/Integration/WebhookWiringTest.php +++ b/tests/Integration/WebhookWiringTest.php @@ -49,7 +49,7 @@ public function testConfigurationParameters(): void { $container = self::getContainer(); - // The test kernel also enables the GitLab, path and Standard + // The test kernel also enables the Basecamp 4, GitLab, path and Standard // Webhooks adapters (TestKernel::ADAPTERS), so the intake tests can // prove every verification strategy and run the GitLab fixtures, // and the test-only adapter with @@ -57,8 +57,8 @@ public function testConfigurationParameters(): void // adapters of the intake mode tests; the bundle default // (passthrough only) is WebhookBundleConfigurationTest. self::assertSame(TestKernel::ADAPTERS, $container->getParameter('dmstr_webhook.adapters')); - self::assertSame(['gitlab' => true, 'passthrough' => true, 'passthrough_path' => true, 'standard_webhooks' => true, 'test_actorless' => true, 'test_context' => true, 'test_filters' => true], $container->getParameter('dmstr_webhook.adapters')); - self::assertSame(['gitlab', 'passthrough', 'passthrough_path', 'standard_webhooks', 'test_actorless', 'test_context', 'test_filters'], $container->getParameter('dmstr_webhook.enabled_adapters')); + self::assertSame(['basecamp4' => true, 'gitlab' => true, 'passthrough' => true, 'passthrough_path' => true, 'standard_webhooks' => true, 'test_actorless' => true, 'test_context' => true, 'test_filters' => true], $container->getParameter('dmstr_webhook.adapters')); + self::assertSame(['basecamp4', 'gitlab', 'passthrough', 'passthrough_path', 'standard_webhooks', 'test_actorless', 'test_context', 'test_filters'], $container->getParameter('dmstr_webhook.enabled_adapters')); self::assertSame(WebhookBundle::MAX_BODY_CAP, $container->getParameter('dmstr_webhook.body_cap')); self::assertSame(60, $container->getParameter('dmstr_webhook.rate_limit')); } @@ -362,3 +362,4 @@ private static function codes(ConstraintViolationListInterface $violations): arr // - revised 2026-12-03 (test-only adapters test_context and test_actorless) // - revised 2026-12-03 (GitLab adapter enabled in the test kernel) // - revised 2026-12-03 (a source that is never enabled for the disabled-adapter case, gitlab is a shipped adapter now) +// - revised 2026-12-03 (Basecamp 4 adapter enabled in the test kernel) diff --git a/tests/Kernel/TestKernel.php b/tests/Kernel/TestKernel.php index 76b6d20..176b053 100644 --- a/tests/Kernel/TestKernel.php +++ b/tests/Kernel/TestKernel.php @@ -79,7 +79,7 @@ * {@see self::FROZEN_NOW}; the Standard Webhooks adapter takes it for its * replay window, so signatures built with {@see self::frozenNow()} are * independent of the run time. - * - `dmstr_webhook`: all four adapters enabled ({@see self::ADAPTERS}), so + * - `dmstr_webhook`: all five adapters enabled ({@see self::ADAPTERS}), so * the tests reach every verification strategy and the GitLab fixtures * (`tests/Fixtures/gitlab/`) run against the database; the bundle default * (`passthrough` only) is covered without kernel. Also enabled: the @@ -141,6 +141,7 @@ final class TestKernel extends Kernel implements CompilerPassInterface /** `dmstr_webhook.adapters` of the test kernel */ public const array ADAPTERS = [ + 'basecamp4' => true, 'gitlab' => true, 'passthrough' => true, 'passthrough_path' => true, @@ -472,3 +473,4 @@ private static function attributeMapping(string $class, string $prefix): array // - revised 2026-12-03 (test-only adapter with filter attributes for the route rules) // - 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) diff --git a/tests/Support/IntakeHarness.php b/tests/Support/IntakeHarness.php index 95acb56..d61c982 100644 --- a/tests/Support/IntakeHarness.php +++ b/tests/Support/IntakeHarness.php @@ -6,6 +6,7 @@ namespace Dmstr\Webhook\Tests\Support; +use Dmstr\Webhook\Adapter\Basecamp4Parser; use Dmstr\Webhook\Adapter\GitlabParser; use Dmstr\Webhook\Adapter\PassthroughParser; use Dmstr\Webhook\Adapter\PassthroughPathParser; @@ -109,7 +110,7 @@ public function __construct(TestCase $test, array $handlers = [], array $adapter } /** - * The adapters of the harness by source: the bundle's four (`gitlab` + * The adapters of the harness by source: the bundle's five (`gitlab` * with the fixtures of {@see GitlabFixtures}) and the test adapters * `test_context` and `test_actorless`. * @@ -118,6 +119,7 @@ public function __construct(TestCase $test, array $handlers = [], array $adapter public static function adapters(MockClock $clock): array { return [ + Basecamp4Parser::SOURCE => static fn (): Basecamp4Parser => new Basecamp4Parser(), GitlabParser::SOURCE => static fn (): GitlabParser => new GitlabParser(), PassthroughParser::SOURCE => static fn (): PassthroughParser => new PassthroughParser(), PassthroughPathParser::SOURCE => static fn (): PassthroughPathParser => new PassthroughPathParser(), @@ -274,3 +276,4 @@ public static function decoded(string $body): array } // - revised 2026-12-03 (GitLab adapter registered) +// - revised 2026-12-03 (Basecamp 4 adapter registered) diff --git a/tests/Unit/Adapter/Basecamp4ParserTest.php b/tests/Unit/Adapter/Basecamp4ParserTest.php new file mode 100644 index 0000000..1a721dd --- /dev/null +++ b/tests/Unit/Adapter/Basecamp4ParserTest.php @@ -0,0 +1,444 @@ +Invented content of the recording'; + private const string DETAIL = 'invented-detail-text'; + private const string RECORDING_CREATOR = 'Robin Recorder'; + private const string BUCKET_NAME = 'Invented Project Name'; + + public function testStrategyAndDeclaredAttributes(): void + { + $parser = new Basecamp4Parser(); + + self::assertSame('basecamp4', Basecamp4Parser::SOURCE); + self::assertSame(VerificationStrategy::PathSecret, $parser->verificationStrategy()); + self::assertSame(['kind', 'project_id', 'recording_type'], $parser->filterAttributes()->names()); + self::assertSame(Basecamp4Parser::ATTRIBUTES, $parser->filterAttributes()->all()); + } + + /** + * @return iterable}> + */ + public static function rejectedSecrets(): iterable + { + yield 'wrong secret' => ['another-path-secret-0123456789abcdefghij', self::SECRET, []]; + yield 'missing segment' => [null, self::SECRET, []]; + yield 'empty segment' => ['', self::SECRET, []]; + yield 'empty endpoint secret' => ['', '', []]; + yield 'any segment, empty endpoint secret' => [self::SECRET, '', []]; + yield 'prefix of the secret' => [substr(self::SECRET, 0, -1), self::SECRET, []]; + yield 'secret with a suffix' => [self::SECRET.'x', self::SECRET, []]; + yield 'secret with a prefix' => ['x'.self::SECRET, self::SECRET, []]; + yield 'secret in a header instead of the path' => [null, self::SECRET, ['X-Webhook-Token' => self::SECRET]]; + yield 'secret as bearer instead of the path' => [null, self::SECRET, ['Authorization' => 'Bearer '.self::SECRET]]; + } + + /** + * @param array $headers + */ + #[DataProvider('rejectedSecrets')] + public function testRejectsAWrongMissingOrEmptyPathSecret(?string $presented, string $secret, array $headers): void + { + $this->expectException(RejectWebhookException::class); + + new Basecamp4Parser()->parse(self::request(self::payload(), $presented, $headers), $secret); + } + + /** + * @return iterable + */ + public static function kinds(): iterable + { + foreach (['message_created', 'comment_created', 'todo_completed', 'kanban_card_moved', 'message_content_updated', 'todo_assignment_changed', 'question_answer_created', 'some_future_kind_2'] as $kind) { + yield $kind => [$kind]; + } + } + + #[DataProvider('kinds')] + public function testTypeAndKeyPerKind(string $kind): void + { + $event = self::parse(self::payload(['kind' => $kind])); + + self::assertSame('basecamp4.'.$kind, $event->getName()); + self::assertSame('basecamp4:event:9100000001', $event->getId()); + self::assertSame($kind, $event->getContext()->attribute('kind')); + } + + public function testTheEventIdAsIntOrDigitStringGivesTheSameKey(): void + { + self::assertSame('basecamp4:event:9100000001', self::parse(self::payload(['id' => 9100000001]))->getId()); + self::assertSame('basecamp4:event:9100000001', self::parse(self::payload(['id' => '9100000001']))->getId()); + } + + /** + * @return iterable): array, bool}> + */ + public static function bodyHashKeys(): iterable + { + yield 'no id' => [static fn (array $p): array => self::without($p, 'id'), true]; + yield 'id null' => [static fn (array $p): array => ['id' => null] + $p, true]; + yield 'negative id' => [static fn (array $p): array => ['id' => -5] + $p, true]; + yield 'id with letters' => [static fn (array $p): array => ['id' => '91abc'] + $p, true]; + yield 'id as float' => [static fn (array $p): array => ['id' => 1.5] + $p, true]; + yield 'no kind' => [static fn (array $p): array => self::without($p, 'kind'), false]; + yield 'kind with capitals' => [static fn (array $p): array => ['kind' => 'Message_Created'] + $p, false]; + yield 'kind with a dot' => [static fn (array $p): array => ['kind' => 'message.created'] + $p, false]; + yield 'empty kind' => [static fn (array $p): array => ['kind' => ''] + $p, false]; + yield 'kind too long' => [static fn (array $p): array => ['kind' => str_repeat('a', 101)] + $p, false]; + yield 'kind not a string' => [static fn (array $p): array => ['kind' => 42] + $p, false]; + } + + /** + * @param \Closure(array): array $change + */ + #[DataProvider('bodyHashKeys')] + public function testWithoutUsableIdOrKindTheKeyIsTheBodyHash(\Closure $change, bool $kindValid): void + { + $body = self::json($change(self::payload())); + $event = self::parseBody($body); + + self::assertSame('basecamp4:event:sha256:'.hash('sha256', $body), $event->getId()); + self::assertSame(self::parseBody($body)->getId(), $event->getId()); + self::assertSame($kindValid ? 'basecamp4.message_created' : Basecamp4Parser::TYPE_UNKNOWN, $event->getName()); + if (!$kindValid) { + self::assertNull($event->getContext()->attribute('kind')); + self::assertSame(Fact::Unknown, $event->getContext()->facts->edit); + } + } + + public function testDifferentBodiesWithoutIdGetDifferentKeys(): void + { + $a = self::parse(self::without(self::payload(), 'id')); + $b = self::parse(self::without(self::payload(['kind' => 'comment_created']), 'id')); + + self::assertNotSame($a->getId(), $b->getId()); + } + + public function testHeadersNeverEnterTheKey(): void + { + $body = self::json(self::payload()); + $a = self::parseBody($body, ['X-Request-Id' => '00000000-0000-4000-8000-000000000001']); + $b = self::parseBody($body, ['X-Request-Id' => '00000000-0000-4000-8000-000000000002']); + + self::assertSame($a->getId(), $b->getId()); + + $body = self::json(self::without(self::payload(), 'id')); + self::assertSame(self::parseBody($body, ['X-Request-Id' => 'a'])->getId(), self::parseBody($body, ['X-Request-Id' => 'b'])->getId()); + } + + public function testANonJsonBodyIsAnUnknownEventWithAnEmptyPayload(): void + { + $event = self::parseBody('not json'); + + self::assertSame(Basecamp4Parser::TYPE_UNKNOWN, $event->getName()); + self::assertSame('basecamp4:event:sha256:'.hash('sha256', 'not json'), $event->getId()); + self::assertSame([], $event->getPayload()); + self::assertEquals(EventContext::none(), $event->getContext()); + self::assertNull($event->getTime()); + } + + public function testContext(): void + { + $context = self::parse(self::payload())->getContext(); + + self::assertEquals(new Actor('9200000001', 'Alex Example'), $context->actor); + self::assertEquals(new Reference(Reference::PROJECT, '9300000001'), $context->project); + self::assertEquals(new Reference(Basecamp4Parser::RECORDING, '9400000001'), $context->target); + self::assertSame('recording', Basecamp4Parser::RECORDING); + self::assertNull($context->note); + self::assertNull($context->discussion); + self::assertSame(['kind' => 'message_created', 'project_id' => 9300000001, 'recording_type' => 'Message'], $context->attributes); + } + + /** + * @return iterable + */ + public static function creatorIds(): iterable + { + yield 'int' => [9200000001, '9200000001']; + yield 'digit string' => ['9200000001', '9200000001']; + yield 'name instead of id' => ['Alex Example', null]; + yield 'e-mail instead of id' => ['alex@example.com', null]; + yield 'negative' => [-1, null]; + yield 'null' => [null, null]; + yield 'bool' => [true, null]; + } + + #[DataProvider('creatorIds')] + public function testActorId(mixed $id, ?string $expected): void + { + $payload = self::payload(); + $payload['creator']['id'] = $id; + + self::assertSame($expected, self::parse($payload)->getContext()->actorId()); + } + + public function testWithoutCreatorThereIsNoActor(): void + { + self::assertNull(self::parse(self::without(self::payload(), 'creator'))->getContext()->actor); + + $payload = self::payload(); + unset($payload['creator']['name']); + self::assertEquals(new Actor('9200000001'), self::parse($payload)->getContext()->actor); + } + + public function testTheRecordingCreatorIsNotTheActor(): void + { + // The actor is the top-level creator (who caused the event), not + // the creator of the recording. + self::assertSame('9200000001', self::parse(self::payload())->getContext()->actorId()); + self::assertNull(self::parse(self::without(self::payload(), 'creator'))->getContext()->actorId()); + } + + public function testTheProjectComesFromTheRecordingBucketOnly(): void + { + $payload = self::payload(); + $payload['bucket'] = ['id' => 9399999999, 'name' => self::BUCKET_NAME, 'type' => 'Project']; + $context = self::parse($payload)->getContext(); + self::assertSame('9300000001', $context->project?->id); + self::assertSame(9300000001, $context->attribute('project_id')); + + unset($payload['recording']['bucket']); + $context = self::parse($payload)->getContext(); + self::assertNull($context->project); + self::assertNull($context->attribute('project_id')); + } + + public function testDigitStringIdsOfProjectAndRecording(): void + { + $payload = self::payload(); + $payload['recording']['id'] = '9400000001'; + $payload['recording']['bucket']['id'] = '9300000001'; + $context = self::parse($payload)->getContext(); + + self::assertEquals(new Reference(Reference::PROJECT, '9300000001'), $context->project); + self::assertEquals(new Reference(Basecamp4Parser::RECORDING, '9400000001'), $context->target); + self::assertSame(9300000001, $context->attribute('project_id')); + } + + public function testWithoutRecordingThereIsNoProjectTargetOrType(): void + { + $context = self::parse(self::without(self::payload(), 'recording'))->getContext(); + + self::assertNull($context->project); + self::assertNull($context->target); + self::assertSame(['kind' => 'message_created'], $context->attributes); + } + + /** + * @return iterable + */ + public static function editFacts(): iterable + { + yield 'message_title_updated' => ['message_title_updated', Fact::Yes]; + yield 'message_content_updated' => ['message_content_updated', Fact::Yes]; + yield 'todo_content_updated' => ['todo_content_updated', Fact::Yes]; + yield 'kanban_card_title_updated' => ['kanban_card_title_updated', Fact::Yes]; + yield 'message_created' => ['message_created', Fact::No]; + yield 'comment_created' => ['comment_created', Fact::No]; + yield 'question_answer_created' => ['question_answer_created', Fact::No]; + yield 'message_active' => ['message_active', Fact::Unknown]; + yield 'message_copied' => ['message_copied', Fact::Unknown]; + yield 'message_archived' => ['message_archived', Fact::Unknown]; + yield 'message_trashed' => ['message_trashed', Fact::Unknown]; + yield 'message_deleted' => ['message_deleted', Fact::Unknown]; + yield 'todo_completed' => ['todo_completed', Fact::Unknown]; + yield 'kanban_card_moved' => ['kanban_card_moved', Fact::Unknown]; + yield 'todo_assignment_changed' => ['todo_assignment_changed', Fact::Unknown]; + yield 'message_subscribers_changed' => ['message_subscribers_changed', Fact::Unknown]; + yield 'unknown future kind' => ['something_new', Fact::Unknown]; + } + + #[DataProvider('editFacts')] + public function testEditRuleAndOtherFactsUnknown(string $kind, Fact $edit): void + { + $facts = self::parse(self::payload(['kind' => $kind]))->getContext()->facts; + + self::assertSame($edit, $facts->edit); + self::assertSame(Fact::Unknown, $facts->systemGenerated); + self::assertSame(Fact::Unknown, $facts->confidential); + self::assertSame(Fact::Unknown, $facts->mentionsEndpoint); + } + + public function testTheEndpointHandleChangesNoFact(): void + { + $request = self::request(self::payload(['kind' => 'comment_created']), self::SECRET); + $request->attributes->set(WebhookIntake::ENDPOINT_HANDLE_ATTRIBUTE, 'robin'); + $event = new Basecamp4Parser()->parse($request, self::SECRET); + + self::assertInstanceOf(WebhookRemoteEvent::class, $event); + self::assertSame(Fact::Unknown, $event->getContext()->facts->mentionsEndpoint); + } + + public function testAttributesAreDeclaredAndOfTheirKind(): void + { + $parser = new Basecamp4Parser(); + foreach (self::parse(self::payload(['kind' => 'kanban_card_moved'], ['type' => 'Kanban::Card']))->getContext()->attributes as $name => $value) { + self::assertTrue($parser->filterAttributes()->accepts($name, $value), $name); + } + self::assertSame('Kanban::Card', self::parse(self::payload([], ['type' => 'Kanban::Card']))->getContext()->attribute('recording_type')); + } + + public function testEventTime(): void + { + self::assertEquals(new \DateTimeImmutable('2026-11-20T10:15:30.123Z'), self::parse(self::payload())->getTime()); + self::assertEquals(new \DateTimeImmutable('2026-11-20T11:15:30.123+01:00'), self::parse(self::payload(['created_at' => '2026-11-20T11:15:30.123+01:00']))->getTime()); + self::assertNull(self::parse(self::payload(['created_at' => 'yesterday']))->getTime()); + self::assertNull(self::parse(self::payload(['created_at' => 1795773600]))->getTime()); + self::assertNull(self::parse(self::without(self::payload(), 'created_at'))->getTime()); + } + + public function testThePayloadIsTheDecodedBody(): void + { + $payload = self::payload(); + + self::assertSame($payload, self::parse($payload)->getPayload()); + } + + public function testNoTextOfTheDeliveryLeavesThePayload(): void + { + $event = self::parse(self::payload()); + $context = $event->getContext(); + $exposed = json_encode([ + $event->getName(), + $event->getId(), + $context->project, + $context->target, + $context->actor?->id, + $context->attributes, + ], \JSON_THROW_ON_ERROR); + + foreach ([self::TITLE, self::CONTENT, self::DETAIL, self::RECORDING_CREATOR, self::BUCKET_NAME, 'Invented Board', 'alex@example.com'] as $text) { + self::assertStringNotContainsString($text, $exposed); + self::assertStringContainsString($text, json_encode($event->getPayload(), \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES)); + } + // The only name in the context is the actor's display name. + self::assertSame('Alex Example', $context->actor?->displayName); + } + + /** + * A delivery in the documented shape, with invented values. + * + * @param array $top top-level fields to replace + * @param array $recording recording fields to replace + * + * @return array + */ + private static function payload(array $top = [], array $recording = []): array + { + return array_replace([ + 'id' => 9100000001, + 'kind' => 'message_created', + 'details' => ['notified_recipient_ids' => [9200000002], 'note' => self::DETAIL], + 'created_at' => '2026-11-20T10:15:30.123Z', + 'recording' => array_replace([ + 'id' => 9400000001, + 'status' => 'active', + 'created_at' => '2026-11-20T10:15:29.000Z', + 'updated_at' => '2026-11-20T10:15:30.000Z', + 'title' => self::TITLE, + 'inherits_status' => true, + 'type' => 'Message', + 'url' => 'https://basecamp.example.com/1000001/buckets/9300000001/messages/9400000001.json', + 'app_url' => 'https://basecamp.example.com/1000001/buckets/9300000001/messages/9400000001', + 'parent' => ['id' => 9400000000, 'title' => 'Invented Board', 'type' => 'Message::Board'], + 'bucket' => ['id' => 9300000001, 'name' => self::BUCKET_NAME, 'type' => 'Project'], + 'creator' => ['id' => 9200000003, 'name' => self::RECORDING_CREATOR, 'email_address' => 'robin@example.com'], + 'content' => self::CONTENT, + ], $recording), + 'creator' => [ + 'id' => 9200000001, + 'name' => 'Alex Example', + 'email_address' => 'alex@example.com', + 'personable_type' => 'User', + ], + ], $top); + } + + /** + * @param array $payload + * + * @return array + */ + private static function without(array $payload, string $key): array + { + unset($payload[$key]); + + return $payload; + } + + /** + * @param array $payload + */ + private static function json(array $payload): string + { + return json_encode($payload, \JSON_THROW_ON_ERROR); + } + + /** + * @param array $payload + */ + private static function parse(array $payload): WebhookRemoteEvent + { + return self::parseBody(self::json($payload)); + } + + /** + * @param array $headers + */ + private static function parseBody(string $body, array $headers = []): WebhookRemoteEvent + { + $event = new Basecamp4Parser()->parse(self::request($body, self::SECRET, $headers), self::SECRET); + self::assertInstanceOf(WebhookRemoteEvent::class, $event); + + return $event; + } + + /** + * @param array|string $body + * @param array $headers + */ + private static function request(array|string $body, ?string $pathSecret, array $headers = []): Request + { + $request = Request::create('/webhook/basecamp', 'POST', content: \is_string($body) ? $body : self::json($body)); + $request->headers->set('Content-Type', 'application/json'); + foreach ($headers as $name => $value) { + $request->headers->set($name, $value); + } + if (null !== $pathSecret) { + $request->attributes->set(WebhookIntake::PATH_SECRET_ATTRIBUTE, $pathSecret); + } + + return $request; + } +} diff --git a/tests/Unit/DependencyInjection/AdapterRegistrationTest.php b/tests/Unit/DependencyInjection/AdapterRegistrationTest.php index a512e70..334871f 100644 --- a/tests/Unit/DependencyInjection/AdapterRegistrationTest.php +++ b/tests/Unit/DependencyInjection/AdapterRegistrationTest.php @@ -6,6 +6,7 @@ namespace Dmstr\Webhook\Tests\Unit\DependencyInjection; +use Dmstr\Webhook\Adapter\Basecamp4Parser; use Dmstr\Webhook\Adapter\GitlabParser; use Dmstr\Webhook\Adapter\PassthroughParser; use Dmstr\Webhook\Adapter\PassthroughPathParser; @@ -29,6 +30,7 @@ final class AdapterRegistrationTest extends TestCase { private const array ADAPTERS = [ + 'basecamp4' => Basecamp4Parser::class, 'gitlab' => GitlabParser::class, 'passthrough' => PassthroughParser::class, 'passthrough_path' => PassthroughPathParser::class, @@ -41,7 +43,10 @@ final class AdapterRegistrationTest extends TestCase public static function configurations(): iterable { yield 'defaults' => [[], ['passthrough']]; - yield 'all enabled' => [['gitlab' => true, 'passthrough_path' => true, 'standard_webhooks' => true], ['gitlab', 'passthrough', 'passthrough_path', 'standard_webhooks']]; + yield 'all enabled' => [['basecamp4' => true, 'gitlab' => true, 'passthrough_path' => true, 'standard_webhooks' => true], ['basecamp4', 'gitlab', 'passthrough', 'passthrough_path', 'standard_webhooks']]; + yield 'basecamp4 enabled' => [['basecamp4' => true], ['basecamp4', 'passthrough']]; + yield 'basecamp4 switched off' => [['basecamp4' => false, 'gitlab' => true], ['gitlab', 'passthrough']]; + yield 'only basecamp4' => [['basecamp4' => true, 'passthrough' => false], ['basecamp4']]; yield 'gitlab enabled' => [['gitlab' => true], ['gitlab', 'passthrough']]; yield 'gitlab switched off' => [['gitlab' => false, 'standard_webhooks' => true], ['passthrough', 'standard_webhooks']]; yield 'only gitlab' => [['gitlab' => true, 'passthrough' => false], ['gitlab']]; @@ -94,3 +99,4 @@ private static function build(array $adapters): ContainerBuilder } // - revised 2026-12-03 (GitLab adapter: registered only when enabled) +// - revised 2026-12-03 (Basecamp 4 adapter: registered only when enabled) From 13e715809fbb5a9bf253e925847a3c8721615d35 Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 3 Dec 2026 23:08:07 +0000 Subject: [PATCH 3/5] test(intake): raw log records of a Basecamp 4 delivery carry neither the path secret nor payload text [*] The intake runs with the real Basecamp4Parser and a recording logger without any processor, so the proof does not rest on the redaction processor; a deliberately leaking test adapter proves that the detector bites. Co-Authored-By: Claude Fable 5.2 --- tests/Unit/Intake/Basecamp4LogTest.php | 636 +++++++++++++++++++++++++ 1 file changed, 636 insertions(+) create mode 100644 tests/Unit/Intake/Basecamp4LogTest.php diff --git a/tests/Unit/Intake/Basecamp4LogTest.php b/tests/Unit/Intake/Basecamp4LogTest.php new file mode 100644 index 0000000..97c181b --- /dev/null +++ b/tests/Unit/Intake/Basecamp4LogTest.php @@ -0,0 +1,636 @@ + 'TitleMarkerQx71 quarterly kickoff', + 'content' => 'ContentMarkerQx72 agenda for the kickoff', + 'details' => 'DetailsMarkerQx73 moved from draft', + 'bucket name' => 'BucketNameMarkerQx74 Example Project', + 'creator name' => 'CreatorNameMarkerQx75 Jane Example', + 'creator e-mail' => 'creator.marker.qx76@example.com', + 'recording creator name' => 'RecordingCreatorMarkerQx77 John Example', + ]; + + private InMemoryWebhookStore $store; + private TestHandler $log; + private Logger $logger; + private WebhookIntake $intake; + private DeliveryHandOff $handOff; + private string $secret; + private string $wrongSecret; + + /** @var list handlers after the recording one */ + private array $extraHandlers = []; + + protected function setUp(): void + { + // Path-safe, random-looking and distinctive. + $this->secret = 'bc4Sec_'.bin2hex(random_bytes(10)).'-Zq.9~'; + $this->wrongSecret = 'bc4Bad_'.bin2hex(random_bytes(10)).'-Wx.7~'; + $this->build(); + } + + /** @return iterable */ + public static function modes(): iterable + { + yield 'process' => [EndpointMode::Process]; + yield 'handler' => [EndpointMode::Handler]; + } + + #[DataProvider('modes')] + public function testAcceptedDelivery(EndpointMode $mode): void + { + $slug = $this->endpointWithRoute($mode); + + $outcome = $this->deliver($slug, self::body(), $this->secret); + + self::assertSame(202, $outcome->statusCode()); + $row = $this->onlyRow($slug); + self::assertSame(self::body(), $row['payload'], 'the payload passed the intake'); + self::assertSame('basecamp4.message_created', $row['type']); + if (EndpointMode::Process === $mode) { + self::assertSame(WebhookEvent::STATUS_ROUTED, $row['status']); + self::assertNull($row['reason']); + self::assertSame([], RecordingDeliveryHandler::deliveriesOf($slug)); + $this->assertRecords([['INFO', WebhookIntake::DECISION_MESSAGE, 'routed', null]]); + } else { + self::assertSame(WebhookEvent::STATUS_RECEIVED, $row['status']); + self::assertCount(1, RecordingDeliveryHandler::deliveriesOf($slug)); + // The mode handler writes no line for an accepted delivery. + $this->assertRecords([]); + } + $this->assertNoLeak(); + } + + #[DataProvider('modes')] + public function testDuplicateDelivery(EndpointMode $mode): void + { + $slug = $this->endpointWithRoute($mode); + + $this->deliver($slug, self::body(), $this->secret); + $records = \count($this->log->getRecords()); + $again = $this->deliver($slug, self::body(), $this->secret); + + self::assertSame(202, $again->statusCode()); + self::assertTrue($again->events[0]->isDuplicate()); + self::assertCount(1, $this->rows($slug)); + self::assertCount(EndpointMode::Handler === $mode ? 1 : 0, RecordingDeliveryHandler::deliveriesOf($slug)); + self::assertCount($records, $this->log->getRecords(), 'a duplicate writes no line'); + $this->assertNoLeak(); + } + + #[DataProvider('modes')] + public function testWrongSecretIsRejected(EndpointMode $mode): void + { + $slug = $this->endpointWithRoute($mode); + + $outcome = $this->deliver($slug, self::body(), $this->wrongSecret); + + self::assertSame(401, $outcome->statusCode()); + self::assertSame([], $this->rows($slug)); + $this->assertRecords([['WARNING', WebhookIntake::REJECTION_MESSAGE, null, 'verification_failed']]); + $this->assertNoLeak(); + } + + #[DataProvider('modes')] + public function testMissingSecretSegmentIsRejected(EndpointMode $mode): void + { + $slug = $this->endpointWithRoute($mode); + + $outcome = $this->deliver($slug, self::body(), null); + + self::assertSame(401, $outcome->statusCode()); + self::assertSame([], $this->rows($slug)); + $this->assertRecords([['WARNING', WebhookIntake::REJECTION_MESSAGE, null, 'verification_failed']]); + $this->assertNoLeak(); + } + + public function testUnknownSlugWithSecretInThePath(): void + { + $outcome = $this->deliver(self::SLUG_PREFIX.'no-such-hook', self::body(), $this->secret); + + self::assertSame(404, $outcome->statusCode()); + self::assertSame([], $this->store->rows); + $this->assertRecords([['WARNING', WebhookIntake::REJECTION_MESSAGE, null, 'unknown_endpoint']]); + $this->assertNoLeak(); + } + + #[DataProvider('modes')] + public function testDeliveryOfTheEndpointsOwnIdentity(EndpointMode $mode): void + { + $slug = $this->endpointWithRoute($mode, ['actorId' => (string) self::CREATOR_ID]); + + $outcome = $this->deliver($slug, self::body(), $this->secret); + + self::assertSame(202, $outcome->statusCode()); + $row = $this->onlyRow($slug); + self::assertSame(WebhookEvent::STATUS_IGNORED, $row['status']); + self::assertSame('own_actor', $row['reason']); + self::assertSame([], RecordingDeliveryHandler::deliveriesOf($slug)); + $this->assertRecords([['INFO', WebhookIntake::DECISION_MESSAGE, 'ignored', 'own_actor']]); + $this->assertNoLeak(); + } + + #[DataProvider('modes')] + public function testActorNotAllowed(EndpointMode $mode): void + { + $slug = $this->endpointWithRoute($mode, ['allowedActorIds' => ['42']]); + + $outcome = $this->deliver($slug, self::body(), $this->secret); + + self::assertSame(202, $outcome->statusCode()); + $this->assertDecision($slug, $mode, 'actor_not_allowed'); + $this->assertNoLeak(); + } + + #[DataProvider('modes')] + public function testBodyWithoutIdAndKind(EndpointMode $mode): void + { + $slug = $this->endpointWithRoute($mode); + $payload = self::payload(); + unset($payload['id'], $payload['kind']); + $body = json_encode($payload, \JSON_THROW_ON_ERROR); + + $outcome = $this->deliver($slug, $body, $this->secret); + + self::assertSame(202, $outcome->statusCode()); + $row = $this->assertDecision($slug, $mode, 'no_route'); + self::assertSame(Basecamp4Parser::TYPE_UNKNOWN, $row['type']); + self::assertSame($body, $row['payload']); + $this->assertNoLeak(); + } + + #[DataProvider('modes')] + public function testBodyThatIsNotJson(EndpointMode $mode): void + { + $slug = $this->endpointWithRoute($mode); + $body = 'kind=message_created&title='.self::PAYLOAD_MARKERS['title'].'&content='.self::PAYLOAD_MARKERS['content'].'&creator='.self::PAYLOAD_MARKERS['creator e-mail']; + + $outcome = $this->deliver($slug, $body, $this->secret); + + self::assertSame(202, $outcome->statusCode()); + // No creator: no actor, which the mode process does not allow. + $row = $this->assertDecision($slug, $mode, 'actor_not_allowed'); + self::assertSame(Basecamp4Parser::TYPE_UNKNOWN, $row['type']); + self::assertSame($body, $row['payload']); + $this->assertNoLeak(); + } + + public function testThrowingDeliveryHandlerLogsNeitherSecretNorPayload(): void + { + $this->extraHandlers = [new class($this->secret) implements DeliveryHandlerInterface { + public function __construct(private readonly string $secret) + { + } + + public function handle(AcceptedDelivery $delivery): void + { + $payload = $delivery->event->getPayload(); + throw new \RuntimeException('handler failed for /webhook/'.$delivery->endpoint->getSlug().'/'.$this->secret.': '.json_encode($payload)); + } + }]; + $this->build(); + $slug = $this->endpointWithRoute(EndpointMode::Handler); + + $outcome = $this->deliver($slug, self::body(), $this->secret); + + self::assertSame(202, $outcome->statusCode()); + $row = $this->onlyRow($slug); + self::assertSame(WebhookEvent::STATUS_FAILED, $row['status']); + self::assertSame(DeliveryHandOff::FAILED_REASON_PREFIX.'RuntimeException', $row['reason']); + $records = $this->log->getRecords(); + self::assertCount(1, $records); + self::assertSame(Level::Error, $records[0]->level); + self::assertSame(['event_id', 'exception_class', 'handler', 'slug'], self::keys($records[0]->context)); + $this->assertNoLeak(); + } + + /** + * The self-check: a path secret adapter that logs the secret, the + * request path, the request object and an exception with payload text + * through the same recording logger. The detector must flag each of + * its records, so a green run of the cases above means something. + */ + public function testDetectorFlagsALeakingAdapter(): void + { + $slug = self::SLUG_PREFIX.'leaky'; + $this->endpoint($slug, EndpointMode::Handler, [], self::LEAKY_SOURCE); + + $outcome = $this->deliver($slug, self::body(), $this->secret); + + self::assertSame(202, $outcome->statusCode(), 'the leaking adapter verified the path secret'); + $records = $this->log->getRecords(); + self::assertCount(5, $records); + $expected = [ + ['secret'], + ['secret', 'secret (URL-encoded)'], + ['secret', 'secret (URL-encoded)', 'title', 'content', 'creator e-mail'], + ['title'], + ['details'], + ]; + foreach ($records as $i => $record) { + $found = $this->leaks($record); + foreach ($expected[$i] as $label) { + self::assertContains($label, $found, 'record '.$i.' ('.$record->message.') not flagged for '.$label); + } + } + + // A wrong secret presented to the leaking adapter is flagged as well. + $this->log->reset(); + $this->deliver($slug, self::body(), $this->wrongSecret); + $flagged = array_merge(...array_map($this->leaks(...), $this->log->getRecords())); + self::assertContains('wrong secret', $flagged); + + // And a value in `extra`, which no processor of this logger fills. + $record = new LogRecord(new \DateTimeImmutable(), 'webhook', Level::Info, 'Clean message.', [], ['nested' => ['uri' => '/webhook/x/'.rawurlencode($this->secret)]]); + self::assertContains('secret (URL-encoded)', $this->leaks($record)); + + // A clean record is not flagged. + self::assertSame([], $this->leaks(new LogRecord(new \DateTimeImmutable(), 'webhook', Level::Info, 'Webhook event {status}.', ['slug' => $slug, 'type' => 'basecamp4.message_created']))); + } + + private function build(): void + { + RecordingDeliveryHandler::reset(); + $this->store = new InMemoryWebhookStore(); + $entityManager = $this->store->entityManager($this); + $this->log = new TestHandler(); + // Deliberately no processor: the records are checked as written. + $this->logger = new Logger('webhook', [$this->log]); + self::assertSame([], $this->logger->getProcessors()); + + $logger = $this->logger; + $events = new EventStore($entityManager); + $transition = new EventStatusTransition($events); + $this->intake = new WebhookIntake( + $entityManager, + new WebhookAdapterRegistry(new ServiceLocator([ + Basecamp4Parser::SOURCE => static fn (): Basecamp4Parser => new Basecamp4Parser(), + self::LEAKY_SOURCE => static fn (): WebhookAdapterInterface => self::leakingAdapter($logger), + ])), + $this->store->secrets, + new IpAllowlistMatcher(), + new EndpointRateLimiter(new SlidingWindowLimiter(new InMemoryStorage())), + $events, + new EventFilter(), + new ActorRateLimiter(new SlidingWindowLimiter(new InMemoryStorage())), + new EventRouter($entityManager, new RouteMatcher()), + $this->logger, + 1048576, + 60, + ); + $this->handOff = new DeliveryHandOff([new RecordingDeliveryHandler($transition), ...$this->extraHandlers], $transition, $this->logger); + } + + /** + * A path secret adapter that leaks on purpose, built on the same base + * and check as {@see Basecamp4Parser}. + */ + private static function leakingAdapter(LoggerInterface $logger): WebhookAdapterInterface + { + return new class($logger) extends AbstractWebhookParser { + public function __construct(private readonly LoggerInterface $logger) + { + } + + public function verificationStrategy(): VerificationStrategy + { + return VerificationStrategy::PathSecret; + } + + protected function doParse(Request $request, #[\SensitiveParameter] string $secret): RemoteEvent + { + $presented = $request->attributes->get(WebhookIntake::PATH_SECRET_ATTRIBUTE); + $this->logger->debug('Presented path secret {presented}.', ['presented' => $presented]); + $this->logger->info('Delivery to {uri}.', ['uri' => $request->getUri()]); + $this->logger->notice('Delivery received.', ['request' => $request]); + $payload = self::jsonPayload($request); + $title = \is_array($payload['recording'] ?? null) ? (string) ($payload['recording']['title'] ?? '') : ''; + $this->logger->warning('Parse problem.', ['exception' => new \RuntimeException('outer', 0, new \LogicException('bad title '.$title))]); + $this->logger->error('Details: '.json_encode($payload['details'] ?? null)); + + self::verifyPathSecret($request, $secret); + + return new WebhookRemoteEvent('leaky.event', 'leaky:'.self::bodyHash($request), $payload); + } + }; + } + + /** + * An endpoint of the source `basecamp4` (or another) with a route for + * `basecamp4.message_created` and the creator on the allowlist, unless + * `$config` says otherwise. + * + * @param array $config + */ + private function endpointWithRoute(EndpointMode $mode, array $config = []): string + { + $slug = self::SLUG_PREFIX.$mode->value.'-'.bin2hex(random_bytes(4)); + $endpoint = $this->endpoint($slug, $mode, $config + ['allowedActorIds' => [(string) self::CREATOR_ID]]); + $this->store->route($endpoint, 'messages', 'basecamp4.message_created'); + + return $slug; + } + + /** @param array $config */ + private function endpoint(string $slug, EndpointMode $mode, array $config = [], string $source = Basecamp4Parser::SOURCE): WebhookEndpoint + { + $endpoint = new WebhookEndpoint()->setSlug($slug)->setSourceType($source)->setMode($mode->value)->setSecret($this->secret); + foreach ($config as $field => $value) { + $endpoint->{'set'.ucfirst($field)}($value); + } + $this->store->secrets->storeNewSecret($endpoint); + + return $this->store->add($endpoint); + } + + /** + * The intake and the hand-off, as the HTTP path runs them, with the + * request path the controller receives: `/webhook//`. + */ + private function deliver(string $slug, string $body, ?string $pathSecret): IntakeOutcome + { + $path = '/webhook/'.$slug.(null === $pathSecret ? '' : '/'.rawurlencode($pathSecret)); + $request = Request::create('https://hooks.example.com'.$path, 'POST', server: [ + 'REMOTE_ADDR' => '127.0.0.1', + 'CONTENT_TYPE' => 'application/json', + 'HTTP_USER_AGENT' => 'Basecamp3 Webhook', + 'HTTP_X_REQUEST_ID' => self::REQUEST_ID, + ], content: $body); + + $outcome = $this->intake->receive($request, $slug, $pathSecret); + $this->handOff->handOff($outcome->accepted); + + return $outcome; + } + + /** + * The row of the one event of the endpoint in the mode, decided with + * the reason in the mode `process` and received and handed over in + * the mode `handler`, which has no actor filter and no routing. + * + * @return array + */ + private function assertDecision(string $slug, EndpointMode $mode, string $processReason): array + { + $row = $this->onlyRow($slug); + if (EndpointMode::Process === $mode) { + self::assertSame(WebhookEvent::STATUS_IGNORED, $row['status']); + self::assertSame($processReason, $row['reason']); + self::assertSame([], RecordingDeliveryHandler::deliveriesOf($slug)); + $this->assertRecords([['INFO', WebhookIntake::DECISION_MESSAGE, 'ignored', $processReason]]); + } else { + self::assertSame(WebhookEvent::STATUS_RECEIVED, $row['status']); + self::assertNull($row['reason']); + self::assertCount(1, RecordingDeliveryHandler::deliveriesOf($slug)); + $this->assertRecords([]); + } + + return $row; + } + + /** + * The records of the channel: level, message, status (decision lines) + * and reason, with the context keys the intake documents. + * + * @param list $expected + */ + private function assertRecords(array $expected): void + { + $records = $this->log->getRecords(); + self::assertCount(\count($expected), $records); + foreach ($expected as $i => [$level, $message, $status, $reason]) { + $record = $records[$i]; + self::assertSame('webhook', $record->channel); + self::assertSame($level, $record->level->getName()); + self::assertSame($message, $record->message); + self::assertSame([], $record->extra); + if (WebhookIntake::DECISION_MESSAGE === $message) { + self::assertSame(['delivery_id', 'event_id', 'reason', 'route', 'slug', 'status', 'type'], self::keys($record->context)); + self::assertSame($status, $record->context['status']); + } else { + self::assertSame(['delivery_id', 'ip', 'reason', 'slug'], self::keys($record->context)); + } + self::assertSame($reason, $record->context['reason']); + self::assertSame(self::REQUEST_ID, $record->context['delivery_id']); + } + } + + /** No record of the channel contains any needle. */ + private function assertNoLeak(): void + { + foreach ($this->log->getRecords() as $i => $record) { + self::assertSame([], $this->leaks($record), 'record '.$i.' ('.$record->message.') leaks'); + } + } + + /** + * The labels of the needles found in a raw record: message, context and + * extra walked recursively, plus the record as the normalizer and the + * line formatter (with stack traces) render it. + * + * @return list + */ + private function leaks(LogRecord $record): array + { + $haystack = implode("\n", [ + $record->message, + self::text($record->context), + self::text($record->extra), + (string) json_encode(new NormalizerFormatter()->format($record), \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_PARTIAL_OUTPUT_ON_ERROR), + new LineFormatter(null, null, true, true, true)->format($record), + ]); + + $needles = [ + 'secret' => $this->secret, + 'secret (URL-encoded)' => rawurlencode($this->secret), + 'secret (start)' => substr($this->secret, 0, 16), + 'wrong secret' => $this->wrongSecret, + 'wrong secret (URL-encoded)' => rawurlencode($this->wrongSecret), + ] + self::PAYLOAD_MARKERS; + + $found = []; + foreach ($needles as $label => $needle) { + if (str_contains($haystack, $needle) || str_contains($haystack, trim(json_encode($needle, \JSON_THROW_ON_ERROR), '"'))) { + $found[] = $label; + } + } + + return $found; + } + + /** A value and everything inside it as text. */ + private static function text(mixed $value, int $depth = 0): string + { + if ($depth > 20) { + return ''; + } + if (null === $value || \is_scalar($value)) { + return var_export($value, true); + } + if (\is_array($value)) { + $parts = []; + foreach ($value as $key => $item) { + $parts[] = $key.' => '.self::text($item, $depth + 1); + } + + return implode("\n", $parts); + } + if ($value instanceof \Throwable) { + return implode("\n", [$value::class, $value->getMessage(), $value->getFile(), $value->getTraceAsString(), self::text($value->getPrevious(), $depth + 1)]); + } + if ($value instanceof Request) { + return implode("\n", [(string) $value, $value->getUri(), $value->getRequestUri(), $value->getPathInfo(), self::text($value->attributes->all(), $depth + 1)]); + } + if ($value instanceof \Stringable) { + return (string) $value; + } + if ($value instanceof \UnitEnum) { + return $value->name; + } + + return print_r($value, true); + } + + /** + * @param array $context + * + * @return list + */ + private static function keys(array $context): array + { + $keys = array_map('strval', array_keys($context)); + sort($keys); + + return $keys; + } + + /** @return list> */ + private function rows(string $slug): array + { + foreach ($this->store->endpoints as $endpoint) { + if ($endpoint->getSlug() === $slug) { + return $this->store->rowsOf($endpoint); + } + } + self::fail('No endpoint '.$slug); + } + + /** @return array */ + private function onlyRow(string $slug): array + { + $rows = $this->rows($slug); + self::assertCount(1, $rows); + + return $rows[0]; + } + + private static function body(): string + { + return json_encode(self::payload(), \JSON_THROW_ON_ERROR); + } + + /** + * A `message_created` delivery in the documented shape, invented values. + * + * @return array + */ + private static function payload(): array + { + return [ + 'id' => 9007199254741001, + 'kind' => 'message_created', + 'details' => ['notified_recipient_ids' => [1049715914], 'note' => self::PAYLOAD_MARKERS['details']], + 'created_at' => '2026-01-01T10:00:00.000Z', + 'recording' => [ + 'id' => 9007199254741002, + 'status' => 'active', + 'type' => 'Message', + 'title' => self::PAYLOAD_MARKERS['title'], + 'content' => '
'.self::PAYLOAD_MARKERS['content'].'
', + 'url' => 'https://basecamp.example.com/99999999/buckets/7000001/messages/9007199254741002.json', + 'app_url' => 'https://basecamp.example.com/99999999/buckets/7000001/messages/9007199254741002', + 'bucket' => ['id' => 7000001, 'name' => self::PAYLOAD_MARKERS['bucket name'], 'type' => 'Project'], + 'creator' => ['id' => 1049715915, 'name' => self::PAYLOAD_MARKERS['recording creator name'], 'email_address' => 'recording.creator@example.com'], + ], + 'creator' => [ + 'id' => self::CREATOR_ID, + 'name' => self::PAYLOAD_MARKERS['creator name'], + 'email_address' => self::PAYLOAD_MARKERS['creator e-mail'], + 'personable_type' => 'User', + 'title' => 'Example role', + 'company' => ['id' => 1033447817, 'name' => 'Example Company'], + ], + ]; + } +} From bbdbe7ba081696894c3fad426211f2eb0eecbf62 Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 3 Dec 2026 23:11:56 +0000 Subject: [PATCH 4/5] test(adapter): Basecamp 4 fixtures and intake matrix for both endpoint modes, sequence runner shared with GitLab [*] 17 fixtures in the documented shape of the Basecamp API (origin documented or derived, every value invented, none captured), their rows with the expected status and reason in the modes process and handler for the unit harness and the database group, and the basecamp4 source of the anonymisation test. The sequence runner of the GitLab matrix becomes a shared trait that passes the path secret. Co-Authored-By: Claude Fable 5.2 --- tests/Fixtures/basecamp4/comment-created.yaml | 86 ++++++++ .../comment-own-identity-string-id.yaml | 86 ++++++++ .../basecamp4/comment-own-identity.yaml | 86 ++++++++ .../basecamp4/comment-reused-bot-name.yaml | 86 ++++++++ .../basecamp4/kanban-card-created.yaml | 86 ++++++++ .../Fixtures/basecamp4/kanban-card-moved.yaml | 84 +++++++ .../basecamp4/message-content-updated.yaml | 84 +++++++ .../message-created-creator-id-string.yaml | 88 ++++++++ .../message-created-invalid-kind.yaml | 88 ++++++++ .../message-created-other-actor.yaml | 88 ++++++++ .../basecamp4/message-created-resend.yaml | 88 ++++++++ .../message-created-without-creator.yaml | 67 ++++++ .../basecamp4/message-created-without-id.yaml | 87 ++++++++ .../message-created-without-kind.yaml | 87 ++++++++ tests/Fixtures/basecamp4/message-created.yaml | 88 ++++++++ .../basecamp4/message-title-updated.yaml | 84 +++++++ tests/Fixtures/basecamp4/message-trashed.yaml | 84 +++++++ .../Intake/Basecamp4MatrixDatabaseTest.php | 76 +++++++ .../Intake/GitlabMatrixDatabaseTest.php | 37 +--- .../Intake/IntakeMatrixDatabaseTestCase.php | 32 +++ tests/Support/Basecamp4Fixtures.php | 84 +++++++ tests/Support/Basecamp4Matrix.php | 208 ++++++++++++++++++ tests/Support/FixtureSequenceTests.php | 85 +++++++ tests/Support/FixtureSet.php | 15 +- tests/Support/IntakeHarnessSequences.php | 53 +++++ .../Fixtures/FixtureAnonymisationTest.php | 43 +++- tests/Unit/Intake/Basecamp4MatrixUnitTest.php | 170 ++++++++++++++ tests/Unit/Intake/GitlabMatrixUnitTest.php | 38 +--- 28 files changed, 2229 insertions(+), 59 deletions(-) create mode 100644 tests/Fixtures/basecamp4/comment-created.yaml create mode 100644 tests/Fixtures/basecamp4/comment-own-identity-string-id.yaml create mode 100644 tests/Fixtures/basecamp4/comment-own-identity.yaml create mode 100644 tests/Fixtures/basecamp4/comment-reused-bot-name.yaml create mode 100644 tests/Fixtures/basecamp4/kanban-card-created.yaml create mode 100644 tests/Fixtures/basecamp4/kanban-card-moved.yaml create mode 100644 tests/Fixtures/basecamp4/message-content-updated.yaml create mode 100644 tests/Fixtures/basecamp4/message-created-creator-id-string.yaml create mode 100644 tests/Fixtures/basecamp4/message-created-invalid-kind.yaml create mode 100644 tests/Fixtures/basecamp4/message-created-other-actor.yaml create mode 100644 tests/Fixtures/basecamp4/message-created-resend.yaml create mode 100644 tests/Fixtures/basecamp4/message-created-without-creator.yaml create mode 100644 tests/Fixtures/basecamp4/message-created-without-id.yaml create mode 100644 tests/Fixtures/basecamp4/message-created-without-kind.yaml create mode 100644 tests/Fixtures/basecamp4/message-created.yaml create mode 100644 tests/Fixtures/basecamp4/message-title-updated.yaml create mode 100644 tests/Fixtures/basecamp4/message-trashed.yaml create mode 100644 tests/Integration/Intake/Basecamp4MatrixDatabaseTest.php create mode 100644 tests/Support/Basecamp4Fixtures.php create mode 100644 tests/Support/Basecamp4Matrix.php create mode 100644 tests/Support/FixtureSequenceTests.php create mode 100644 tests/Support/IntakeHarnessSequences.php create mode 100644 tests/Unit/Intake/Basecamp4MatrixUnitTest.php diff --git a/tests/Fixtures/basecamp4/comment-created.yaml b/tests/Fixtures/basecamp4/comment-created.yaml new file mode 100644 index 0000000..176c7b0 --- /dev/null +++ b/tests/Fixtures/basecamp4/comment-created.yaml @@ -0,0 +1,86 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: comment_created, a comment on the message +origin: 'documented (Basecamp API docs, sections/webhooks.md: payload and headers in the documented shape, every value invented)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '1e5d8b63-4c2f-4a97-b0e3-6f8c2d4a9b51' +body: | + { + "id": 61000002, + "kind": "comment_created", + "details": { + "notified_recipient_ids": [ + 88000032 + ] + }, + "created_at": "2026-02-10T09:20:00.000Z", + "recording": { + "id": 62000002, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:20:00.000Z", + "updated_at": "2026-02-10T09:20:00.000Z", + "title": "Re: Sample message for webhook fixtures", + "inherits_status": true, + "type": "Comment", + "url": "https://basecamp.example.com/4107733/buckets/70200001/comments/62000002.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/comments/62000002", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000002/subscription.json", + "parent": { + "id": 62000001, + "title": "Sample message for webhook fixtures", + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample reply to the message.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/comment-own-identity-string-id.yaml b/tests/Fixtures/basecamp4/comment-own-identity-string-id.yaml new file mode 100644 index 0000000..d637276 --- /dev/null +++ b/tests/Fixtures/basecamp4/comment-own-identity-string-id.yaml @@ -0,0 +1,86 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: comment_created by the own identity, its id as a string +origin: 'derived from comment-own-identity (event id; top-level creator.id as a string of digits)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: 'f635c941-24f7-4815-bec6-47ce582d349f' +body: | + { + "id": 61000012, + "kind": "comment_created", + "details": { + "notified_recipient_ids": [ + 88000031 + ] + }, + "created_at": "2026-02-10T09:25:00.000Z", + "recording": { + "id": 62000004, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:20:00.000Z", + "updated_at": "2026-02-10T09:20:00.000Z", + "title": "Re: Sample message for webhook fixtures", + "inherits_status": true, + "type": "Comment", + "url": "https://basecamp.example.com/4107733/buckets/70200001/comments/62000004.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/comments/62000004", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000004/subscription.json", + "parent": { + "id": 62000001, + "title": "Sample message for webhook fixtures", + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000900, + "attachable_sgid": "sgid-fixture-person-88000900", + "name": "Agent Example", + "email_address": "agent-example@example.com", + "personable_type": "User", + "title": "Sample Bot", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000900/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample answer written by the bot.
" + }, + "creator": { + "id": "88000900", + "attachable_sgid": "sgid-fixture-person-88000900", + "name": "Agent Example", + "email_address": "agent-example@example.com", + "personable_type": "User", + "title": "Sample Bot", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000900/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/comment-own-identity.yaml b/tests/Fixtures/basecamp4/comment-own-identity.yaml new file mode 100644 index 0000000..5ebce69 --- /dev/null +++ b/tests/Fixtures/basecamp4/comment-own-identity.yaml @@ -0,0 +1,86 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: comment_created by the endpoint's own identity (the bot user) +origin: 'documented (Basecamp API docs, sections/webhooks.md: payload and headers in the documented shape, every value invented)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '4b8a1e96-7f5c-4dca-a3b6-9c1f5a7d2e84' +body: | + { + "id": 61000005, + "kind": "comment_created", + "details": { + "notified_recipient_ids": [ + 88000031 + ] + }, + "created_at": "2026-02-10T09:25:00.000Z", + "recording": { + "id": 62000004, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:20:00.000Z", + "updated_at": "2026-02-10T09:20:00.000Z", + "title": "Re: Sample message for webhook fixtures", + "inherits_status": true, + "type": "Comment", + "url": "https://basecamp.example.com/4107733/buckets/70200001/comments/62000004.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/comments/62000004", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000004/subscription.json", + "parent": { + "id": 62000001, + "title": "Sample message for webhook fixtures", + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000900, + "attachable_sgid": "sgid-fixture-person-88000900", + "name": "Agent Example", + "email_address": "agent-example@example.com", + "personable_type": "User", + "title": "Sample Bot", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000900/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample answer written by the bot.
" + }, + "creator": { + "id": 88000900, + "attachable_sgid": "sgid-fixture-person-88000900", + "name": "Agent Example", + "email_address": "agent-example@example.com", + "personable_type": "User", + "title": "Sample Bot", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000900/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/comment-reused-bot-name.yaml b/tests/Fixtures/basecamp4/comment-reused-bot-name.yaml new file mode 100644 index 0000000..3ff7f33 --- /dev/null +++ b/tests/Fixtures/basecamp4/comment-reused-bot-name.yaml @@ -0,0 +1,86 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: comment_created by another user with the display name of the bot +origin: 'derived from comment-created (event id; creator and recording creator are another user named like the bot)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '07a6da52-3508-4926-8f80-58df693e4a50' +body: | + { + "id": 61000013, + "kind": "comment_created", + "details": { + "notified_recipient_ids": [ + 88000032 + ] + }, + "created_at": "2026-02-10T09:20:00.000Z", + "recording": { + "id": 62000002, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:20:00.000Z", + "updated_at": "2026-02-10T09:20:00.000Z", + "title": "Re: Sample message for webhook fixtures", + "inherits_status": true, + "type": "Comment", + "url": "https://basecamp.example.com/4107733/buckets/70200001/comments/62000002.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/comments/62000002", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000002/subscription.json", + "parent": { + "id": 62000001, + "title": "Sample message for webhook fixtures", + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000032, + "attachable_sgid": "sgid-fixture-person-88000032", + "name": "Agent Example", + "email_address": "ben@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000032/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample reply to the message.
" + }, + "creator": { + "id": 88000032, + "attachable_sgid": "sgid-fixture-person-88000032", + "name": "Agent Example", + "email_address": "ben@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000032/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/kanban-card-created.yaml b/tests/Fixtures/basecamp4/kanban-card-created.yaml new file mode 100644 index 0000000..7f5cdb9 --- /dev/null +++ b/tests/Fixtures/basecamp4/kanban-card-created.yaml @@ -0,0 +1,86 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: kanban_card_created, a new card in a column of a card table +origin: 'documented (Basecamp API docs, sections/webhooks.md: payload and headers in the documented shape, every value invented)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '2f6e9c74-5d3a-4ba8-81f4-7a9d3e5b0c62' +body: | + { + "id": 61000003, + "kind": "kanban_card_created", + "details": { + "notified_recipient_ids": [] + }, + "created_at": "2026-02-10T10:00:00.000Z", + "recording": { + "id": 62000003, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T10:00:00.000Z", + "updated_at": "2026-02-10T10:00:00.000Z", + "title": "Sample card for webhook fixtures", + "inherits_status": true, + "type": "Kanban::Card", + "url": "https://basecamp.example.com/4107733/buckets/70200001/card_tables/cards/62000003.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/card_tables/cards/62000003", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000003/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000003/comments.json", + "parent": { + "id": 62000200, + "title": "In progress", + "type": "Kanban::Column", + "url": "https://basecamp.example.com/4107733/buckets/70200001/card_tables/columns/62000200.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/card_tables/columns/62000200" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample card with a checklist.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/kanban-card-moved.yaml b/tests/Fixtures/basecamp4/kanban-card-moved.yaml new file mode 100644 index 0000000..3750ce1 --- /dev/null +++ b/tests/Fixtures/basecamp4/kanban-card-moved.yaml @@ -0,0 +1,84 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: kanban_card_moved, a card moved to another column +origin: 'documented (Basecamp API docs, sections/webhooks.md: payload and headers in the documented shape, every value invented; the kind kanban_card_moved is not in the documented list of kinds but is used by the host application)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '3a7f0d85-6e4b-4cb9-92a5-8b0e4f6c1d73' +body: | + { + "id": 61000004, + "kind": "kanban_card_moved", + "details": {}, + "created_at": "2026-02-10T10:30:00.000Z", + "recording": { + "id": 62000003, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T10:00:00.000Z", + "updated_at": "2026-02-10T10:30:00.000Z", + "title": "Sample card for webhook fixtures", + "inherits_status": true, + "type": "Kanban::Card", + "url": "https://basecamp.example.com/4107733/buckets/70200001/card_tables/cards/62000003.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/card_tables/cards/62000003", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000003/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000003/comments.json", + "parent": { + "id": 62000201, + "title": "Done", + "type": "Kanban::Column", + "url": "https://basecamp.example.com/4107733/buckets/70200001/card_tables/columns/62000201.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/card_tables/columns/62000201" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample card with a checklist.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/message-content-updated.yaml b/tests/Fixtures/basecamp4/message-content-updated.yaml new file mode 100644 index 0000000..1023b86 --- /dev/null +++ b/tests/Fixtures/basecamp4/message-content-updated.yaml @@ -0,0 +1,84 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: message_content_updated, the content of the message edited +origin: 'derived from message-created (event id, kind message_content_updated, times, recording content, details)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '7ebd41c9-ac8f-40fd-96e9-cf4c8d0a5b17' +body: | + { + "id": 61000007, + "kind": "message_content_updated", + "details": {}, + "created_at": "2026-02-10T11:00:00.000Z", + "recording": { + "id": 62000001, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T11:00:00.000Z", + "title": "Sample message for webhook fixtures", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph, edited.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/message-created-creator-id-string.yaml b/tests/Fixtures/basecamp4/message-created-creator-id-string.yaml new file mode 100644 index 0000000..848220c --- /dev/null +++ b/tests/Fixtures/basecamp4/message-created-creator-id-string.yaml @@ -0,0 +1,88 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: message_created, the creator id as a string +origin: 'derived from message-created (event id; top-level creator.id as a string of digits)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: 'd413a72f-02e5-46f3-9cd4-25ac360b127d' +body: | + { + "id": 61000010, + "kind": "message_created", + "details": { + "notified_recipient_ids": [ + 88000032 + ] + }, + "created_at": "2026-02-10T09:15:00.000Z", + "recording": { + "id": 62000001, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T09:15:00.000Z", + "title": "Sample message for webhook fixtures", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph.
" + }, + "creator": { + "id": "88000031", + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/message-created-invalid-kind.yaml b/tests/Fixtures/basecamp4/message-created-invalid-kind.yaml new file mode 100644 index 0000000..6a2cc65 --- /dev/null +++ b/tests/Fixtures/basecamp4/message-created-invalid-kind.yaml @@ -0,0 +1,88 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: a kind outside the pattern of the adapter +origin: 'derived from message-created (event id; kind with capitals, a space and punctuation)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: 'c302961e-f1d4-45e2-8bc3-149b25fa016c' +body: | + { + "id": 61000014, + "kind": "Message Created!", + "details": { + "notified_recipient_ids": [ + 88000032 + ] + }, + "created_at": "2026-02-10T09:15:00.000Z", + "recording": { + "id": 62000001, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T09:15:00.000Z", + "title": "Sample message for webhook fixtures", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/message-created-other-actor.yaml b/tests/Fixtures/basecamp4/message-created-other-actor.yaml new file mode 100644 index 0000000..9ca8428 --- /dev/null +++ b/tests/Fixtures/basecamp4/message-created-other-actor.yaml @@ -0,0 +1,88 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: message_created by a user outside the allowlist of the matrix +origin: 'derived from message-created (event id; creator and recording creator are another user)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '5c9b2fa7-8a6d-4edb-b4c7-ad2a6b8e3f95' +body: | + { + "id": 61000006, + "kind": "message_created", + "details": { + "notified_recipient_ids": [ + 88000032 + ] + }, + "created_at": "2026-02-10T09:15:00.000Z", + "recording": { + "id": 62000001, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T09:15:00.000Z", + "title": "Sample message for webhook fixtures", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000032, + "attachable_sgid": "sgid-fixture-person-88000032", + "name": "Ben Example", + "email_address": "ben@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000032/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph.
" + }, + "creator": { + "id": 88000032, + "attachable_sgid": "sgid-fixture-person-88000032", + "name": "Ben Example", + "email_address": "ben@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000032/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/message-created-resend.yaml b/tests/Fixtures/basecamp4/message-created-resend.yaml new file mode 100644 index 0000000..dc1d542 --- /dev/null +++ b/tests/Fixtures/basecamp4/message-created-resend.yaml @@ -0,0 +1,88 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: message_created, the same delivery again +origin: 'derived from message-created (body byte-identical; only the X-Request-Id differs)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '6dac30b8-9b7e-4fec-85d8-be3b7c9f4a06' +body: | + { + "id": 61000001, + "kind": "message_created", + "details": { + "notified_recipient_ids": [ + 88000032 + ] + }, + "created_at": "2026-02-10T09:15:00.000Z", + "recording": { + "id": 62000001, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T09:15:00.000Z", + "title": "Sample message for webhook fixtures", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/message-created-without-creator.yaml b/tests/Fixtures/basecamp4/message-created-without-creator.yaml new file mode 100644 index 0000000..566f3a0 --- /dev/null +++ b/tests/Fixtures/basecamp4/message-created-without-creator.yaml @@ -0,0 +1,67 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: message_created without the top-level creator +origin: 'derived from message-created (event id; top-level creator removed, recording.creator kept)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: 'e524b830-13f6-4704-adb5-36bd471c238e' +body: | + { + "id": 61000011, + "kind": "message_created", + "details": { + "notified_recipient_ids": [ + 88000032 + ] + }, + "created_at": "2026-02-10T09:15:00.000Z", + "recording": { + "id": 62000001, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T09:15:00.000Z", + "title": "Sample message for webhook fixtures", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph.
" + } + } diff --git a/tests/Fixtures/basecamp4/message-created-without-id.yaml b/tests/Fixtures/basecamp4/message-created-without-id.yaml new file mode 100644 index 0000000..fec5e25 --- /dev/null +++ b/tests/Fixtures/basecamp4/message-created-without-id.yaml @@ -0,0 +1,87 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: message_created without the top-level event id +origin: 'derived from message-created (top-level id removed)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: 'a1e074fc-dfb2-43c0-89a1-f27fb03d8e4a' +body: | + { + "kind": "message_created", + "details": { + "notified_recipient_ids": [ + 88000032 + ] + }, + "created_at": "2026-02-10T09:15:00.000Z", + "recording": { + "id": 62000001, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T09:15:00.000Z", + "title": "Sample message for webhook fixtures", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/message-created-without-kind.yaml b/tests/Fixtures/basecamp4/message-created-without-kind.yaml new file mode 100644 index 0000000..734dfa9 --- /dev/null +++ b/tests/Fixtures/basecamp4/message-created-without-kind.yaml @@ -0,0 +1,87 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: message_created without the kind +origin: 'derived from message-created (kind removed)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: 'b2f1850d-e0c3-44d1-9ab2-038a14e9f05b' +body: | + { + "id": 61000001, + "details": { + "notified_recipient_ids": [ + 88000032 + ] + }, + "created_at": "2026-02-10T09:15:00.000Z", + "recording": { + "id": 62000001, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T09:15:00.000Z", + "title": "Sample message for webhook fixtures", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/message-created.yaml b/tests/Fixtures/basecamp4/message-created.yaml new file mode 100644 index 0000000..ec0dd80 --- /dev/null +++ b/tests/Fixtures/basecamp4/message-created.yaml @@ -0,0 +1,88 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: message_created, a new message on the message board +origin: 'documented (Basecamp API docs, sections/webhooks.md: payload and headers in the documented shape, every value invented)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '0d4c7a52-3b1e-4f86-a9d2-5e7b1c3f8a40' +body: | + { + "id": 61000001, + "kind": "message_created", + "details": { + "notified_recipient_ids": [ + 88000032 + ] + }, + "created_at": "2026-02-10T09:15:00.000Z", + "recording": { + "id": 62000001, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T09:15:00.000Z", + "title": "Sample message for webhook fixtures", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/message-title-updated.yaml b/tests/Fixtures/basecamp4/message-title-updated.yaml new file mode 100644 index 0000000..55a8524 --- /dev/null +++ b/tests/Fixtures/basecamp4/message-title-updated.yaml @@ -0,0 +1,84 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: message_title_updated, the title of the message edited +origin: 'derived from message-created (event id, kind message_title_updated, times, recording title, details)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '8fce52da-bd90-41ae-a7fa-d05d9e1b6c28' +body: | + { + "id": 61000008, + "kind": "message_title_updated", + "details": {}, + "created_at": "2026-02-10T11:05:00.000Z", + "recording": { + "id": 62000001, + "status": "active", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T11:05:00.000Z", + "title": "Sample message for webhook fixtures, renamed", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Fixtures/basecamp4/message-trashed.yaml b/tests/Fixtures/basecamp4/message-trashed.yaml new file mode 100644 index 0000000..035ea07 --- /dev/null +++ b/tests/Fixtures/basecamp4/message-trashed.yaml @@ -0,0 +1,84 @@ +# file generated with AI assistance: Claude Code - 2026-12-03 23:08:00 UTC +# Basecamp 4 delivery, built from the API documentation: message_trashed, the message moved to the trash +origin: 'derived from message-created (event id, kind message_trashed, recording status trashed, times, details)' +headers: + Content-Type: 'application/json' + User-Agent: 'Basecamp3 Webhook' + X-Request-Id: '90df63eb-cea1-42bf-b80b-e16eaf2c7d39' +body: | + { + "id": 61000009, + "kind": "message_trashed", + "details": {}, + "created_at": "2026-02-10T12:00:00.000Z", + "recording": { + "id": 62000001, + "status": "trashed", + "visible_to_clients": false, + "created_at": "2026-02-10T09:15:00.000Z", + "updated_at": "2026-02-10T12:00:00.000Z", + "title": "Sample message for webhook fixtures", + "inherits_status": true, + "type": "Message", + "url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", + "subscription_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/subscription.json", + "comments_count": 0, + "comments_url": "https://basecamp.example.com/4107733/buckets/70200001/recordings/62000001/comments.json", + "parent": { + "id": 62000100, + "title": "Message Board", + "type": "Message::Board", + "url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100.json", + "app_url": "https://basecamp.example.com/4107733/buckets/70200001/message_boards/62000100" + }, + "bucket": { + "id": 70200001, + "name": "Sample Project", + "type": "Project" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + }, + "content": "
A sample message with a short paragraph.
" + }, + "creator": { + "id": 88000031, + "attachable_sgid": "sgid-fixture-person-88000031", + "name": "Ann Example", + "email_address": "ann@example.com", + "personable_type": "User", + "title": "Sample Role", + "bio": null, + "created_at": "2026-01-05T08:00:00.000Z", + "updated_at": "2026-01-05T08:00:00.000Z", + "admin": false, + "owner": false, + "client": false, + "employee": true, + "time_zone": "Etc/UTC", + "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", + "company": { + "id": 40500001, + "name": "Example Company" + } + } + } diff --git a/tests/Integration/Intake/Basecamp4MatrixDatabaseTest.php b/tests/Integration/Intake/Basecamp4MatrixDatabaseTest.php new file mode 100644 index 0000000..10c96ef --- /dev/null +++ b/tests/Integration/Intake/Basecamp4MatrixDatabaseTest.php @@ -0,0 +1,76 @@ + + */ + public static function rows(): iterable + { + yield from Basecamp4Matrix::rows(); + } + + #[DataProvider('rows')] + public function testModeProcess(IntakeCase $case): void + { + $this->check($case, EndpointMode::Process); + } + + #[DataProvider('rows')] + public function testModeHandler(IntakeCase $case): void + { + $this->check($case, EndpointMode::Handler); + } + + protected static function fixtureMatrix(): FixtureMatrix + { + return Basecamp4Matrix::matrix(); + } + + protected static function fixtureSequences(): iterable + { + return Basecamp4Matrix::sequences(); + } + + public function testAnUnknownSlugIs404(): void + { + $slug = static::PREFIX.'unknown-'.bin2hex(random_bytes(4)); + $set = Basecamp4Fixtures::set(); + + $response = $this->deliver($slug, $set->headers('message-created'), $set->body('message-created'), Basecamp4Fixtures::SECRET); + + self::assertSame(404, $response->getStatusCode()); + self::assertSame([], $this->eventRows($slug)); + } +} diff --git a/tests/Integration/Intake/GitlabMatrixDatabaseTest.php b/tests/Integration/Intake/GitlabMatrixDatabaseTest.php index b9a1359..9880871 100644 --- a/tests/Integration/Intake/GitlabMatrixDatabaseTest.php +++ b/tests/Integration/Intake/GitlabMatrixDatabaseTest.php @@ -7,10 +7,11 @@ namespace Dmstr\Webhook\Tests\Integration\Intake; use Dmstr\Webhook\Model\EndpointMode; +use Dmstr\Webhook\Tests\Support\FixtureMatrix; +use Dmstr\Webhook\Tests\Support\FixtureSequenceTests; use Dmstr\Webhook\Tests\Support\GitlabFixtures; use Dmstr\Webhook\Tests\Support\GitlabMatrix; use Dmstr\Webhook\Tests\Support\IntakeCase; -use Dmstr\Webhook\Tests\Support\RecordingDeliveryHandler; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; @@ -20,12 +21,15 @@ * enabled: every row in both modes, the sequences of several deliveries * (edit next to its original, retry with a new delivery UUID, other actions * on one merge request, the accepted collision, create and delete of a tag, - * the rate limit per actor), and an unknown slug. The same without + * the rate limit per actor, through the shared runner + * {@see FixtureSequenceTests}), and an unknown slug. The same without * database: {@see \Dmstr\Webhook\Tests\Unit\Intake\GitlabMatrixUnitTest}. */ #[Group('database')] final class GitlabMatrixDatabaseTest extends IntakeMatrixDatabaseTestCase { + use FixtureSequenceTests; + protected const string PREFIX = 'test-webhook-gitlab-'; /** @@ -48,33 +52,14 @@ public function testModeHandler(IntakeCase $case): void $this->check($case, EndpointMode::Handler); } - /** - * @return iterable, deliveries: list}>, process: list, handler: list}, EndpointMode}> - */ - public static function sequences(): iterable + protected static function fixtureMatrix(): FixtureMatrix { - foreach (GitlabMatrix::sequences() as $name => [$sequence]) { - yield $name.' [process]' => [$sequence, EndpointMode::Process]; - yield $name.' [handler]' => [$sequence, EndpointMode::Handler]; - } + return GitlabMatrix::matrix(); } - /** - * @param array{endpoint: array, deliveries: list}>, process: list, handler: list} $sequence - */ - #[DataProvider('sequences')] - public function testSequence(array $sequence, EndpointMode $mode): void + protected static function fixtureSequences(): iterable { - [$slug] = $this->endpointFor(GitlabMatrix::endpointCase($sequence['endpoint']), $mode); - - foreach ($sequence['deliveries'] as [$fixture, $headers]) { - self::assertSame(202, $this->deliver($slug, GitlabFixtures::headers($fixture, $headers), GitlabFixtures::body($fixture))->getStatusCode(), $fixture); - } - - $expected = EndpointMode::Handler === $mode ? $sequence['handler'] : $sequence['process']; - $rows = $this->eventRows($slug); - self::assertSame($expected, array_map(static fn (array $row): array => [$row['status'], $row['reason']], $rows)); - self::assertCount(EndpointMode::Handler === $mode ? \count($rows) : 0, RecordingDeliveryHandler::deliveriesOf($slug)); + return GitlabMatrix::sequences(); } public function testAnUnknownSlugIs404(): void @@ -87,3 +72,5 @@ public function testAnUnknownSlugIs404(): void self::assertSame([], $this->eventRows($slug)); } } + +// - revised 2026-12-03 (sequences through the shared runner FixtureSequenceTests) diff --git a/tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php b/tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php index ee999f9..b98a367 100644 --- a/tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php +++ b/tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php @@ -28,6 +28,8 @@ * A source with fixtures extends this class with its own data provider * and calls {@see self::check()} per row and mode; its adapter must be * enabled in {@see \Dmstr\Webhook\Tests\Kernel\TestKernel::ADAPTERS}. + * With {@see \Dmstr\Webhook\Tests\Support\FixtureSequenceTests} it also + * runs the source's sequences through the three steps of this class. * * Endpoints carry the slug prefix {@see self::PREFIX}; their events and * routes go with them (ON DELETE CASCADE, {@see TestDatabase::removeEndpoints()}). @@ -189,6 +191,34 @@ protected function eventRows(string $slug): array return $rows; } + /** + * The endpoint of a sequence ({@see \Dmstr\Webhook\Tests\Support\FixtureSequenceTests}); its slug. + */ + protected function createSequenceEndpoint(IntakeCase $case, EndpointMode $mode): string + { + return $this->endpointFor($case, $mode)[0]; + } + + /** + * One delivery of a sequence; the HTTP status. + * + * @param array $headers + */ + protected function deliverInSequence(string $slug, array $headers, string $body, ?string $pathSecret): int + { + return $this->deliver($slug, $headers, $body, $pathSecret)->getStatusCode(); + } + + /** + * The event rows of a sequence as `[status, reason]`, oldest first. + * + * @return list + */ + protected function sequenceEvents(string $slug): array + { + return array_map(static fn (array $row): array => [(string) $row['status'], null === $row['reason'] ? null : (string) $row['reason']], $this->eventRows($slug)); + } + protected function dbal(): Connection { /** @var Connection $connection */ @@ -209,3 +239,5 @@ private static function cleanUp(): void static::ensureKernelShutdown(); } } + +// - revised 2026-12-03 (steps of the shared sequence runner FixtureSequenceTests) diff --git a/tests/Support/Basecamp4Fixtures.php b/tests/Support/Basecamp4Fixtures.php new file mode 100644 index 0000000..79095c1 --- /dev/null +++ b/tests/Support/Basecamp4Fixtures.php @@ -0,0 +1,84 @@ + + * origin: documented () | derived from () + * headers: {Content-Type: …, User-Agent: Basecamp3 Webhook, X-Request-Id: …} + * body: | + * { pretty-printed JSON in the documented shape } + * + * No real Basecamp delivery was recorded: the `documented` files follow + * the payload and headers of the Basecamp API documentation (bc3-api, + * `sections/webhooks.md`) with every value invented; `derived` files + * change single values of one of them (other actor, edit and trash kinds, + * a missing id, kind or creator, ids as strings). Basecamp sends no secret + * header: the secret travels in the path ({@see self::SECRET}). The + * identities below are the ones the files use. + */ +final class Basecamp4Fixtures +{ + public const string DIR = __DIR__.'/../Fixtures/basecamp4'; + + /** The secret path segment of every request (the endpoint secret of the matrix). */ + public const string SECRET = 'fixture-secret-basecamp4-Hq7Zr2Wm9Tx4Lc8Np3Vb6K'; + + /** The endpoint's own identity: the bot user. */ + public const string BOT_ID = '88000900'; + public const string BOT_NAME = 'Agent Example'; + + /** The author of the documented deliveries (on the allowlist of the matrix). */ + public const string ANN_ID = '88000031'; + /** Another user: author of `message-created-other-actor` and `comment-reused-bot-name`. */ + public const string OTHER_ID = '88000032'; + + /** The project (`recording.bucket.id`) of every fixture. */ + public const int PROJECT_ID = 70200001; + + /** The free-text fields of a Basecamp payload ({@see self::texts()}). */ + public const array TEXT_KEYS = ['title', 'content', 'bio']; + + private static ?FixtureSet $set = null; + + /** The fixture files of {@see self::DIR}. */ + public static function set(): FixtureSet + { + return self::$set ??= new FixtureSet(self::DIR, 'Basecamp 4'); + } + + /** + * The delivery as a request to the parser, with the secret path segment + * as the intake passes it. + * + * @param array $headers header overrides + * @param string|null $pathSecret the secret path segment; null: none + */ + public static function request(string $name, array $headers = [], ?string $pathSecret = self::SECRET): Request + { + return self::set()->request($name, '/webhook/basecamp4', null, $headers, pathSecret: $pathSecret); + } + + /** + * The free texts of a payload (titles, HTML content, bios): what must + * never leave the stored payload. + * + * @param array $payload + * + * @return list + */ + public static function texts(array $payload): array + { + return FixtureSet::texts($payload, self::TEXT_KEYS); + } +} diff --git a/tests/Support/Basecamp4Matrix.php b/tests/Support/Basecamp4Matrix.php new file mode 100644 index 0000000..db6973f --- /dev/null +++ b/tests/Support/Basecamp4Matrix.php @@ -0,0 +1,208 @@ + Basecamp4Parser::SOURCE, + 'secret' => Basecamp4Fixtures::SECRET, + 'actorId' => Basecamp4Fixtures::BOT_ID, + 'allowedActorIds' => [Basecamp4Fixtures::ANN_ID], + 'routes' => [['name' => 'all']], + ], Basecamp4Fixtures::SECRET); + } + + /** + * @return iterable + */ + public static function rows(): iterable + { + $matrix = self::matrix(); + $routed = IntakeExpectation::routed('all'); + $handed = IntakeExpectation::handedOver(); + $ignored = IntakeExpectation::ignored(...); + $unauthorized = IntakeExpectation::rejected(401); + $notAllowed = ['allowedActorIds' => [Basecamp4Fixtures::OTHER_ID]]; + $type = static fn (string $kind): string => Basecamp4Parser::TYPE_PREFIX.$kind; + + // Created kinds of an allowed actor, and kinds without an edit fact. + yield 'message created' => [$matrix->case('message-created', $routed, $handed)]; + yield 'comment created' => [$matrix->case('comment-created', $routed, $handed)]; + yield 'card created' => [$matrix->case('kanban-card-created', $routed, $handed)]; + yield 'card moved (kind outside the documented list)' => [$matrix->case('kanban-card-moved', $routed, $handed)]; + yield 'message trashed (edit unknown)' => [$matrix->case('message-trashed', $routed, $handed)]; + yield 'creator id as a string' => [$matrix->case('message-created-creator-id-string', $routed, $handed)]; + + // Edits: ignored in the mode process before the allowlist, handed over in the mode handler. + yield 'message content updated' => [$matrix->case('message-content-updated', $ignored(IgnoreReason::Edit), $handed)]; + yield 'message title updated' => [$matrix->case('message-title-updated', $ignored(IgnoreReason::Edit), $handed)]; + yield 'edit by an actor outside the allowlist' => [$matrix->case('message-content-updated', $ignored(IgnoreReason::Edit), $handed, $notAllowed)]; + + // Own identity: in both modes, whatever the allowlist says. + yield 'own identity, id as int' => [$matrix->case('comment-own-identity', $ignored(IgnoreReason::OwnActor), $ignored(IgnoreReason::OwnActor))]; + yield 'own identity, id as string' => [$matrix->case('comment-own-identity-string-id', $ignored(IgnoreReason::OwnActor), $ignored(IgnoreReason::OwnActor))]; + yield 'own identity on the allowlist' => [$matrix->case('comment-own-identity', $ignored(IgnoreReason::OwnActor), $ignored(IgnoreReason::OwnActor), [ + 'allowedActorIds' => [Basecamp4Fixtures::ANN_ID, Basecamp4Fixtures::BOT_ID], + ])]; + yield 'name of the bot, another id' => [$matrix->case('comment-reused-bot-name', $ignored(IgnoreReason::ActorNotAllowed), $handed)]; + yield 'name of the bot, another id on the allowlist' => [$matrix->case('comment-reused-bot-name', $routed, $handed, [ + 'allowedActorIds' => [Basecamp4Fixtures::OTHER_ID], + ])]; + + // Allowlist. + yield 'actor outside the allowlist' => [$matrix->case('message-created-other-actor', $ignored(IgnoreReason::ActorNotAllowed), $handed)]; + yield 'allowlist without the author' => [$matrix->case('message-created', $ignored(IgnoreReason::ActorNotAllowed), $handed, $notAllowed)]; + yield 'empty allowlist' => [$matrix->case('message-created', $ignored(IgnoreReason::ActorNotAllowed), $handed, ['allowedActorIds' => []])]; + yield 'creator missing (recording creator not taken)' => [$matrix->case('message-created-without-creator', $ignored(IgnoreReason::ActorNotAllowed), $handed)]; + + // No id or no valid kind: dedupe key from the body hash; the byte-identical duplicate is checked per row. + yield 'without id' => [$matrix->case('message-created-without-id', $routed, $handed)]; + yield 'without kind' => [$matrix->case('message-created-without-kind', $routed, $handed)]; + yield 'invalid kind' => [$matrix->case('message-created-invalid-kind', $routed, $handed)]; + + // Routes on the declared attributes. + yield 'no matching route' => [$matrix->case('message-created', $ignored(IgnoreReason::NoRoute), $handed, [ + 'routes' => [['name' => 'todos', 'eventType' => $type('todo_created')]], + ])]; + yield 'route by event type and attributes' => [$matrix->case('kanban-card-moved', IntakeExpectation::routed('card-moves'), $handed, [ + 'routes' => [ + ['name' => 'fallback', 'priority' => 9], + ['name' => 'messages', 'eventType' => $type('message_created'), 'priority' => 1], + ['name' => 'other-project', 'filters' => ['project_id' => Basecamp4Fixtures::PROJECT_ID + 1], 'priority' => 2], + ['name' => 'card-moves', 'eventType' => $type('kanban_card_moved'), 'filters' => [ + 'kind' => 'kanban_card_moved', + 'project_id' => Basecamp4Fixtures::PROJECT_ID, + 'recording_type' => 'Kanban::Card', + ], 'priority' => 3], + ], + ])]; + yield 'route by recording type' => [$matrix->case('comment-created', IntakeExpectation::routed('comments'), $handed, [ + 'routes' => [ + ['name' => 'messages', 'filters' => ['recording_type' => 'Message'], 'priority' => 1], + ['name' => 'comments', 'filters' => ['recording_type' => 'Comment'], 'priority' => 2], + ], + ])]; + yield 'route on the kind, delivery without kind' => [$matrix->case('message-created-without-kind', $ignored(IgnoreReason::NoRoute), $handed, [ + 'routes' => [['name' => 'messages', 'filters' => ['kind' => 'message_created']]], + ])]; + yield 'route on the unknown type, delivery with an invalid kind' => [$matrix->case('message-created-invalid-kind', IntakeExpectation::routed('unknown'), $handed, [ + 'routes' => [['name' => 'unknown', 'eventType' => Basecamp4Parser::TYPE_UNKNOWN]], + ])]; + + // Secret path segment and endpoint. + yield 'wrong secret' => [$matrix->case('message-created', $unauthorized, $unauthorized, pathSecret: 'another-path-secret-0123456789abcdefghij')]; + yield 'wrong endpoint secret' => [$matrix->case('message-created', $unauthorized, $unauthorized, ['secret' => 'another-endpoint-secret-0123456789abcdef'])]; + yield 'missing secret segment' => [$matrix->case('message-created', $unauthorized, $unauthorized, pathSecret: null)]; + yield 'secret with a prefix' => [$matrix->case('message-created', $unauthorized, $unauthorized, pathSecret: 'x'.Basecamp4Fixtures::SECRET)]; + yield 'secret with a suffix' => [$matrix->case('message-created', $unauthorized, $unauthorized, pathSecret: Basecamp4Fixtures::SECRET.'x')]; + yield 'prefix of the secret' => [$matrix->case('message-created', $unauthorized, $unauthorized, pathSecret: substr(Basecamp4Fixtures::SECRET, 0, -1))]; + yield 'secret with a further path segment' => [$matrix->case('message-created', $unauthorized, $unauthorized, pathSecret: Basecamp4Fixtures::SECRET.'/extra')]; + yield 'secret in a header instead of the path' => [$matrix->case('message-created', $unauthorized, $unauthorized, headers: ['Authorization' => 'Bearer '.Basecamp4Fixtures::SECRET], pathSecret: null)]; + yield 'inactive endpoint' => [$matrix->case('message-created', IntakeExpectation::rejected(404), IntakeExpectation::rejected(404), ['active' => false])]; + } + + /** + * Cases with several deliveries to one endpoint, in the shape of + * {@see FixtureSequenceTests::testSequence()}: the endpoint overrides, + * the deliveries (fixture and header overrides, in order) and, per + * mode, the event rows expected afterwards as `[status, reason]`, + * oldest first. + * + * @return iterable, deliveries: list}>, process: list, handler: list}}> + */ + public static function sequences(): iterable + { + $routed = [WebhookEvent::STATUS_ROUTED, null]; + $received = [WebhookEvent::STATUS_RECEIVED, null]; + $ignored = static fn (IgnoreReason $reason): array => [WebhookEvent::STATUS_IGNORED, $reason->value]; + $otherHeaders = ['X-Request-Id' => '3b9e5c17-0d2a-4f6e-8a41-c7d0e2b5f938', 'User-Agent' => null]; + + // Basecamp retries a delivery with the same event id; the + // X-Request-Id never enters the dedupe key. + yield 'same delivery again with another X-Request-Id' => [[ + 'endpoint' => [], + 'deliveries' => [['message-created', []], ['message-created-resend', []]], + 'process' => [$routed], + 'handler' => [$received], + ]]; + yield 'same delivery again with other headers' => [[ + 'endpoint' => [], + 'deliveries' => [['message-created', []], ['message-created', $otherHeaders]], + 'process' => [$routed], + 'handler' => [$received], + ]]; + yield 'without id, the same body again with other headers' => [[ + 'endpoint' => [], + 'deliveries' => [['message-created-without-id', []], ['message-created-without-id', $otherHeaders]], + 'process' => [$routed], + 'handler' => [$received], + ]]; + yield 'without kind, the same body again with other headers' => [[ + 'endpoint' => [], + 'deliveries' => [['message-created-without-kind', []], ['message-created-without-kind', $otherHeaders]], + 'process' => [$routed], + 'handler' => [$received], + ]]; + yield 'without id and without kind, two different bodies' => [[ + 'endpoint' => [], + 'deliveries' => [['message-created-without-id', []], ['message-created-without-kind', []], ['message-created', []]], + 'process' => [$routed, $routed, $routed], + 'handler' => [$received, $received, $received], + ]]; + yield 'created, edited twice and trashed, the same message' => [[ + 'endpoint' => [], + 'deliveries' => [['message-created', []], ['message-content-updated', []], ['message-title-updated', []], ['message-trashed', []]], + 'process' => [$routed, $ignored(IgnoreReason::Edit), $ignored(IgnoreReason::Edit), $routed], + 'handler' => [$received, $received, $received, $received], + ]]; + yield 'actor over the rate limit' => [[ + 'endpoint' => ['actorRateLimit' => 1], + 'deliveries' => [['message-created', []], ['comment-created', []]], + 'process' => [$routed, $ignored(IgnoreReason::ActorRateLimited)], + 'handler' => [$received, $received], + ]]; + yield 'filtered events and duplicates use no budget' => [[ + 'endpoint' => ['actorRateLimit' => 1], + 'deliveries' => [ + ['message-content-updated', []], + ['message-created-other-actor', []], + ['message-created', []], + ['message-created-resend', []], + ['comment-created', []], + ], + 'process' => [$ignored(IgnoreReason::Edit), $ignored(IgnoreReason::ActorNotAllowed), $routed, $ignored(IgnoreReason::ActorRateLimited)], + 'handler' => [$received, $received, $received, $received], + ]]; + } +} diff --git a/tests/Support/FixtureSequenceTests.php b/tests/Support/FixtureSequenceTests.php new file mode 100644 index 0000000..3566916 --- /dev/null +++ b/tests/Support/FixtureSequenceTests.php @@ -0,0 +1,85 @@ +, deliveries: list}>, process: list, handler: list} + */ +trait FixtureSequenceTests +{ + /** The source's fixtures, default endpoint and secret path segment. */ + abstract protected static function fixtureMatrix(): FixtureMatrix; + + /** + * The source's sequences, e.g. {@see GitlabMatrix::sequences()}. + * + * @return iterable + */ + abstract protected static function fixtureSequences(): iterable; + + /** Creates the endpoint (and its routes) of a sequence; its slug. */ + abstract protected function createSequenceEndpoint(IntakeCase $case, EndpointMode $mode): string; + + /** + * One delivery to the endpoint, hand-over included; the HTTP status. + * + * @param array $headers + */ + abstract protected function deliverInSequence(string $slug, array $headers, string $body, ?string $pathSecret): int; + + /** + * The event rows of the endpoint as `[status, reason]`, oldest first. + * + * @return list + */ + abstract protected function sequenceEvents(string $slug): array; + + /** + * @return iterable + */ + public static function sequences(): iterable + { + foreach (static::fixtureSequences() as $name => [$sequence]) { + yield $name.' [process]' => [$sequence, EndpointMode::Process]; + yield $name.' [handler]' => [$sequence, EndpointMode::Handler]; + } + } + + /** + * @param Sequence $sequence + */ + #[DataProvider('sequences')] + public function testSequence(array $sequence, EndpointMode $mode): void + { + $matrix = static::fixtureMatrix(); + $slug = $this->createSequenceEndpoint($matrix->endpointCase($sequence['endpoint']), $mode); + + foreach ($sequence['deliveries'] as [$fixture, $headers]) { + self::assertSame(202, $this->deliverInSequence($slug, $matrix->fixtures->headers($fixture, $headers), $matrix->fixtures->body($fixture), $matrix->pathSecret), $fixture); + } + + $events = $this->sequenceEvents($slug); + self::assertSame(EndpointMode::Handler === $mode ? $sequence['handler'] : $sequence['process'], $events); + self::assertCount(EndpointMode::Handler === $mode ? \count($events) : 0, RecordingDeliveryHandler::deliveriesOf($slug)); + } +} diff --git a/tests/Support/FixtureSet.php b/tests/Support/FixtureSet.php index 0f2fe78..1be3f08 100644 --- a/tests/Support/FixtureSet.php +++ b/tests/Support/FixtureSet.php @@ -16,14 +16,15 @@ * * # file generated with AI assistance: … * # delivery, anonymised: - * origin: captured | derived from () + * origin: captured | documented () | derived from () * headers: {Content-Type: …, …} * body: | * { pretty-printed JSON, the field names, nesting and types of a real delivery } * * `captured` files keep the structure of a real delivery with neutral - * values; `derived` files change single values of another fixture of the - * same source ({@see self::ORIGIN_PATTERN}, {@see self::derivedFrom()}). + * values; `documented` files follow the payload a source documents, every + * value invented, for sources without recorded deliveries; `derived` files + * change single values of another fixture of the same source ({@see self::ORIGIN_PATTERN}, {@see self::derivedFrom()}). * A source's own class (e.g. {@see GitlabFixtures}) holds one instance and * the identities its files use. */ @@ -32,8 +33,8 @@ final class FixtureSet /** The keys of a fixture file, in this order. */ public const array KEYS = ['origin', 'headers', 'body']; - /** The `origin` of a fixture: captured, or derived from another fixture of the same source. */ - public const string ORIGIN_PATTERN = '/^(captured|derived from [a-z0-9-]+ \(.+\))$/'; + /** The `origin` of a fixture: captured, documented (built from the source's documentation), or derived from another fixture of the same source. */ + public const string ORIGIN_PATTERN = '/^(captured|documented \(.+\)|derived from [a-z0-9-]+ \(.+\))$/'; /** @var array, body: string}> by file path */ private static array $loaded = []; @@ -158,9 +159,11 @@ public static function texts(array $payload, array $keys): array return array_values(array_unique($texts)); } - /** The fixture an `origin` is derived from; null for a captured one. */ + /** The fixture an `origin` is derived from; null for a captured or documented one. */ public static function derivedFrom(string $origin): ?string { return str_starts_with($origin, 'derived from ') ? explode(' ', $origin)[2] : null; } } + +// - revised 2026-12-03 (origin `documented` for fixtures built from a source's documentation) diff --git a/tests/Support/IntakeHarnessSequences.php b/tests/Support/IntakeHarnessSequences.php new file mode 100644 index 0000000..f655d17 --- /dev/null +++ b/tests/Support/IntakeHarnessSequences.php @@ -0,0 +1,53 @@ +sequenceHarness = new IntakeHarness($this); + $slug = 'sequence-'.$mode->value; + [$this->sequenceEndpoint] = $this->sequenceHarness->endpointFor($case, $mode, $slug); + + return $slug; + } + + /** + * @param array $headers + */ + protected function deliverInSequence(string $slug, array $headers, string $body, ?string $pathSecret): int + { + \assert(null !== $this->sequenceHarness); + + return $this->sequenceHarness->deliver($slug, $headers, $body, $pathSecret)->statusCode(); + } + + /** + * @return list + */ + protected function sequenceEvents(string $slug): array + { + \assert(null !== $this->sequenceHarness && null !== $this->sequenceEndpoint); + + return array_map(static fn (array $row): array => [$row['status'], $row['reason']], $this->sequenceHarness->store->rowsOf($this->sequenceEndpoint)); + } +} diff --git a/tests/Unit/Fixtures/FixtureAnonymisationTest.php b/tests/Unit/Fixtures/FixtureAnonymisationTest.php index fd1a5ff..cf69787 100644 --- a/tests/Unit/Fixtures/FixtureAnonymisationTest.php +++ b/tests/Unit/Fixtures/FixtureAnonymisationTest.php @@ -6,6 +6,7 @@ namespace Dmstr\Webhook\Tests\Unit\Fixtures; +use Dmstr\Webhook\Tests\Support\Basecamp4Fixtures; use Dmstr\Webhook\Tests\Support\FixtureSet; use Dmstr\Webhook\Tests\Support\GitlabFixtures; use PHPUnit\Framework\Attributes\DataProvider; @@ -14,7 +15,8 @@ /** * Guards the anonymisation of the fixtures under `tests/Fixtures/`, which - * are derived from real deliveries but published with this package. Every + * are derived from real deliveries (or, for Basecamp 4, built from the + * source's documentation) and published with this package. Every * source with fixtures is one entry of {@see self::sources()}; every * fixture file belongs to one of them. * @@ -24,7 +26,7 @@ * URLs, SSH remotes, e-mail addresses and headers such as * `X-Gitlab-Instance`; no placeholder that a source writes for a redacted * value; no avatar service; ASCII only; every fixture says whether it is - * captured or derived; the source's headers carry fixture values only + * captured, documented or derived; the source's headers carry fixture values only * (e.g. every token is a fixture token). * * Layer 2, local only: with the source's environment variable @@ -91,6 +93,34 @@ private static function sources(): array 'avatar', 'merge_requests', 'issues', 'commit', ], ], + // No recorded deliveries: every fixture is documented or derived, + // every value invented; layer 2 runs only once captures exist. + 'basecamp4' => [ + 'fixtures' => Basecamp4Fixtures::set(), + 'minFixtures' => 17, + 'allowedHosts' => ['basecamp.example.com', 'example.com'], + 'headers' => [ + 'Content-Type' => 'application/json', + 'User-Agent' => 'Basecamp3 Webhook', + ], + 'headerPatterns' => [ + 'X-Request-Id' => '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', + ], + 'cleanSample' => '"app_url": "https://basecamp.example.com/4107733/buckets/70200001/messages/62000001", "avatar_url": "https://basecamp.example.com/4107733/people/88000031/avatar", "email_address": "ann@example.com", "content": "
Sample link
"', + 'capturesEnv' => 'WEBHOOK_RAW_CAPTURES_DIR_BASECAMP4', + 'structural' => [ + 'application/json', 'Basecamp3 Webhook', + 'Message', 'Comment', 'Kanban::Card', 'Kanban::Column', 'Kanban::Step', 'Message::Board', + 'Todo', 'Todolist', 'Document', 'Upload', 'Question', 'Schedule::Entry', 'Vault', + 'Project', 'User', 'Agent', 'active', 'archived', 'trashed', 'Etc/UTC', + 'message_created', 'message_content_updated', 'message_title_updated', 'message_trashed', + 'comment_created', 'kanban_card_created', 'kanban_card_moved', 'todo_created', 'todo_completed', + 'notified_recipient_ids', + // URL path keywords of the source. + 'buckets', 'messages', 'message_boards', 'comments', 'card_tables', 'cards', 'columns', + 'recordings', 'subscription', 'people', 'avatar', 'todos', 'todolists', 'webhooks', + ], + ], ]; } @@ -185,6 +215,14 @@ public function testLayer1RulesFireOnBrokenSamples(string $source): void 'other e-mail domain' => '"email": "someone@mail.other-host.test"', 'other instance' => "X-Gitlab-Instance: 'https://gitlab.other-host.test'", 'not ASCII' => '"name": "J'."\u{fc}".'rgen"', + // Basecamp forms: avatar and app URLs, e-mail address fields, HTML content. + 'avatar on another host' => '"avatar_url": "https://assets.other-host.test/4107733/people/1/avatar"', + 'app URL on another host' => '"app_url": "https://app.other-host.test/4107733/buckets/1/messages/2"', + 'API URL on another host' => '"url": "https://api.other-host.test/4107733/buckets/1/messages/2.json"', + 'e-mail address field' => '"email_address": "someone@other-host.test"', + 'link in HTML content' => '"content": ""', + 'e-mail in HTML content' => '"content": "
Write to someone@other-host.test
"', + 'not ASCII in HTML content' => '"content": "
Caf'."\u{e9}".'
"', ]; foreach ($samples as $name => $sample) { self::assertNotSame([], self::structuralViolations($sample, $definition['allowedHosts']), $name); @@ -359,3 +397,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) diff --git a/tests/Unit/Intake/Basecamp4MatrixUnitTest.php b/tests/Unit/Intake/Basecamp4MatrixUnitTest.php new file mode 100644 index 0000000..1e62aca --- /dev/null +++ b/tests/Unit/Intake/Basecamp4MatrixUnitTest.php @@ -0,0 +1,170 @@ + + */ + public static function rows(): iterable + { + yield from Basecamp4Matrix::rows(); + } + + #[DataProvider('rows')] + public function testModeProcess(IntakeCase $case): void + { + new IntakeHarness($this)->check($case, EndpointMode::Process); + } + + #[DataProvider('rows')] + public function testModeHandler(IntakeCase $case): void + { + new IntakeHarness($this)->check($case, EndpointMode::Handler); + } + + protected static function fixtureMatrix(): FixtureMatrix + { + return Basecamp4Matrix::matrix(); + } + + protected static function fixtureSequences(): iterable + { + return Basecamp4Matrix::sequences(); + } + + public function testAHandlerEndpointGetsEveryKindOnceAndUnchanged(): void + { + $harness = new IntakeHarness($this); + $harness->endpointFor(Basecamp4Matrix::matrix()->endpointCase([]), EndpointMode::Handler, 'basecamp4-handler'); + $set = Basecamp4Fixtures::set(); + $fixtures = [ + 'message-created' => 'basecamp4.message_created', + 'comment-created' => 'basecamp4.comment_created', + 'kanban-card-created' => 'basecamp4.kanban_card_created', + 'kanban-card-moved' => 'basecamp4.kanban_card_moved', + 'message-content-updated' => 'basecamp4.message_content_updated', + 'message-title-updated' => 'basecamp4.message_title_updated', + 'message-trashed' => 'basecamp4.message_trashed', + 'message-created-other-actor' => 'basecamp4.message_created', + 'message-created-without-creator' => 'basecamp4.message_created', + 'message-created-without-id' => 'basecamp4.message_created', + 'message-created-without-kind' => Basecamp4Parser::TYPE_UNKNOWN, + 'message-created-invalid-kind' => Basecamp4Parser::TYPE_UNKNOWN, + ]; + + foreach ([...array_keys($fixtures), ...array_keys($fixtures), 'message-created-resend'] as $fixture) { + self::assertSame(202, $harness->deliver('basecamp4-handler', $set->headers($fixture), $set->body($fixture), Basecamp4Fixtures::SECRET)->statusCode(), $fixture); + } + + $delivered = RecordingDeliveryHandler::deliveriesOf('basecamp4-handler'); + self::assertSame(array_values($fixtures), array_map(static fn ($delivery): string => $delivery->event->getName(), $delivered)); + foreach (array_keys($fixtures) as $i => $fixture) { + self::assertSame($set->payload($fixture), $delivered[$i]->event->getPayload(), $fixture); + self::assertSame($set->body($fixture), $harness->row($delivered[$i]->eventId)['payload'], $fixture); + } + } + + /** Not a matrix row: against the database, `/webhook//` with an empty segment does not reach the intake. */ + public function testAnEmptySecretSegmentIs401(): void + { + $harness = new IntakeHarness($this); + [$endpoint] = $harness->endpointFor(Basecamp4Matrix::matrix()->endpointCase([]), EndpointMode::Handler, 'basecamp4-empty'); + $set = Basecamp4Fixtures::set(); + + $outcome = $harness->deliver('basecamp4-empty', $set->headers('message-created'), $set->body('message-created'), ''); + + self::assertSame(401, $outcome->statusCode()); + self::assertSame([], $harness->store->rowsOf($endpoint)); + } + + public function testAnUnknownSlugIs404(): void + { + $harness = new IntakeHarness($this); + $set = Basecamp4Fixtures::set(); + + $outcome = $harness->deliver('basecamp4-unknown', $set->headers('message-created'), $set->body('message-created'), Basecamp4Fixtures::SECRET); + + self::assertSame(404, $outcome->statusCode()); + self::assertSame([], $harness->store->rows); + } + + /** + * @return iterable + */ + public static function fixtureNames(): iterable + { + foreach (Basecamp4Fixtures::set()->names() as $name) { + yield $name => [$name]; + } + } + + /** + * The context of every fixture (actor, references, facts, filter + * attributes) carries no title, content or bio of the delivery, and no + * name but the actor's display name. + */ + #[DataProvider('fixtureNames')] + public function testNoTextOfTheDeliveryInTheContext(string $fixture): void + { + $event = new Basecamp4Parser()->parse(Basecamp4Fixtures::request($fixture), Basecamp4Fixtures::SECRET); + self::assertInstanceOf(RemoteEvent::class, $event); + $context = WebhookRemoteEvent::contextOf($event); + $exported = var_export($context, true); + + $payload = Basecamp4Fixtures::set()->payload($fixture); + $texts = Basecamp4Fixtures::texts($payload); + self::assertNotSame([], $texts, 'the fixture has texts to look for'); + foreach ([...$texts, 'Sample Project', 'Example Company'] as $text) { + self::assertStringNotContainsString($text, $exported, $fixture); + } + foreach ($context->attributes as $name => $value) { + self::assertContains($name, array_keys(Basecamp4Parser::ATTRIBUTES), $fixture); + self::assertNotContains($value, $texts, $fixture); + } + } + + public function testTheContextOfADocumentedDelivery(): void + { + $event = new Basecamp4Parser()->parse(Basecamp4Fixtures::request('kanban-card-moved'), Basecamp4Fixtures::SECRET); + self::assertInstanceOf(RemoteEvent::class, $event); + $context = WebhookRemoteEvent::contextOf($event); + + self::assertSame('basecamp4.kanban_card_moved', $event->getName()); + self::assertSame('basecamp4:event:61000004', $event->getId()); + self::assertSame(Basecamp4Fixtures::ANN_ID, $context->actorId()); + self::assertSame(['kind' => 'kanban_card_moved', 'project_id' => Basecamp4Fixtures::PROJECT_ID, 'recording_type' => 'Kanban::Card'], $context->attributes); + } +} diff --git a/tests/Unit/Intake/GitlabMatrixUnitTest.php b/tests/Unit/Intake/GitlabMatrixUnitTest.php index a219a43..927a654 100644 --- a/tests/Unit/Intake/GitlabMatrixUnitTest.php +++ b/tests/Unit/Intake/GitlabMatrixUnitTest.php @@ -8,10 +8,12 @@ use Dmstr\Webhook\Adapter\GitlabParser; use Dmstr\Webhook\Model\EndpointMode; +use Dmstr\Webhook\Tests\Support\FixtureMatrix; use Dmstr\Webhook\Tests\Support\GitlabFixtures; use Dmstr\Webhook\Tests\Support\GitlabMatrix; use Dmstr\Webhook\Tests\Support\IntakeCase; use Dmstr\Webhook\Tests\Support\IntakeHarness; +use Dmstr\Webhook\Tests\Support\IntakeHarnessSequences; use Dmstr\Webhook\Tests\Support\RecordingDeliveryHandler; use Monolog\LogRecord; use PHPUnit\Framework\Attributes\DataProvider; @@ -21,13 +23,16 @@ * Every GitLab row of {@see GitlabMatrix} in both endpoint modes, without * kernel and database ({@see IntakeHarness}): exact status and reason, * route, writes, hand-over exactly once with the payload unchanged or none, - * the duplicate of the same request; the sequences of several deliveries; + * the duplicate of the same request; the sequences of several deliveries + * (the shared runner {@see IntakeHarnessSequences}); * an unknown slug; and the log lines of the intake, which carry neither the * token nor any text of a fixture. The same rows against the database are * {@see \Dmstr\Webhook\Tests\Integration\Intake\GitlabMatrixDatabaseTest}. */ final class GitlabMatrixUnitTest extends TestCase { + use IntakeHarnessSequences; + /** * @return iterable */ @@ -48,35 +53,14 @@ public function testModeHandler(IntakeCase $case): void new IntakeHarness($this)->check($case, EndpointMode::Handler); } - /** - * @return iterable, deliveries: list}>, process: list, handler: list}, EndpointMode}> - */ - public static function sequences(): iterable + protected static function fixtureMatrix(): FixtureMatrix { - foreach (GitlabMatrix::sequences() as $name => [$sequence]) { - yield $name.' [process]' => [$sequence, EndpointMode::Process]; - yield $name.' [handler]' => [$sequence, EndpointMode::Handler]; - } + return GitlabMatrix::matrix(); } - /** - * @param array{endpoint: array, deliveries: list}>, process: list, handler: list} $sequence - */ - #[DataProvider('sequences')] - public function testSequence(array $sequence, EndpointMode $mode): void + protected static function fixtureSequences(): iterable { - $harness = new IntakeHarness($this); - $slug = 'gitlab-'.$mode->value; - [$endpoint] = $harness->endpointFor(GitlabMatrix::endpointCase($sequence['endpoint']), $mode, $slug); - - foreach ($sequence['deliveries'] as [$fixture, $headers]) { - self::assertSame(202, $harness->deliver($slug, GitlabFixtures::headers($fixture, $headers), GitlabFixtures::body($fixture))->statusCode(), $fixture); - } - - $expected = EndpointMode::Handler === $mode ? $sequence['handler'] : $sequence['process']; - $rows = $harness->store->rowsOf($endpoint); - self::assertSame($expected, array_map(static fn (array $row): array => [$row['status'], $row['reason']], $rows)); - self::assertCount(EndpointMode::Handler === $mode ? \count($rows) : 0, RecordingDeliveryHandler::deliveriesOf($slug)); + return GitlabMatrix::sequences(); } public function testAHandlerEndpointGetsNoteMergeRequestAndTagPushEventsOnceAndUnchanged(): void @@ -129,3 +113,5 @@ public function testTheLogCarriesNeitherTheTokenNorAnyTextOfTheDelivery(): void } } } + +// - revised 2026-12-03 (sequences through the shared runner IntakeHarnessSequences) From 445cf62356ec1d913758646d683be1798d62914d Mon Sep 17 00:00:00 2001 From: "t.munk (workhorse)" Date: Thu, 3 Dec 2026 23:16:24 +0000 Subject: [PATCH 5/5] docs: Basecamp 4 adapter, documented fixtures and the shared test support, changelog for 0.2.1 [*] Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 16 +++++++++++ CLAUDE.md | 5 ++-- README.md | 66 +++++++++++++++++++++++++++++++++++++++---- src/WebhookBundle.php | 6 ++-- 4 files changed, 84 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34dc27d..a6da949 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ 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.2.1] - 2026-12-03 + +No action is needed on upgrade: the new adapter is disabled by default, and there is no migration. + +### Added + +- The adapter `basecamp4` (`Adapter\Basecamp4Parser`, disabled by default, enable with `dmstr_webhook.adapters.basecamp4: true`) for project webhooks of Basecamp 4, built against the Basecamp API documentation (`sections/webhooks.md` of `basecamp/bc3-api`), not against captured deliveries. Verification by the secret as path segment (`VerificationStrategy::PathSecret`, hook URL `https:///webhook//`), because Basecamp signs nothing and sends no secret header; use a token secret, and mask the segment in the access logs of every proxy in front of the application. Every verified delivery is one event of the type `basecamp4.` (`basecamp4.unknown` without a valid `kind`), including kinds outside the documented list such as `kanban_card_moved`; the payload is stored unchanged. Event context: the actor `creator.id` (never a name), the project `recording.bucket.id`, the target of the reference kind `recording` (`recording.id`); the fact edit is Yes for kinds ending in `_title_updated` or `_content_updated`, No for kinds ending in `_created` and unknown otherwise; the facts system generated, confidential and mentions the endpoint are always unknown. Filter attributes `kind` (string), `project_id` (integer) and `recording_type` (string). Event time: the top-level `created_at`. Dedupe key `basecamp4:event:` from the top-level event `id`, or `basecamp4:event:sha256:` without an `id` or a valid `kind`; it assumes that a retried delivery keeps its `id`, which the documentation does not say. In the mode `process` there is no mention gate: every event of an allowed creator that is not an edit and matches a route is routed, so routes should name an `eventType` or a `kind` filter, or the endpoint should use the mode `handler`. +- Fixtures of Basecamp 4 deliveries in the documented shape with invented values (`tests/Fixtures/basecamp4/`, origin `documented (…)` or derived from such a fixture, none captured), a fixture-driven intake matrix for both modes without and with database (`Basecamp4MatrixUnitTest`, `Basecamp4MatrixDatabaseTest`), and a test that the raw log records of a Basecamp 4 delivery, written without the redaction processor, carry neither the path secret nor payload text (`Basecamp4LogTest`). +- README section on the Basecamp 4 adapter. + +### Changed + +- `AbstractWebhookParser::verifyPathSecret()` is available to adapters: the check of the strategy `PathSecret` (the secret path segment must equal the endpoint secret, compared in constant time, else `RejectWebhookException` with 401). `PassthroughPathParser` uses it; its behaviour is unchanged. +- Test support: the fixture loader and the building block of a source's matrix rows are source-neutral (`tests/Support/FixtureSet.php`, `FixtureMatrix.php`), the sequence runner is shared by the sources (`FixtureSequenceTests`, `IntakeHarnessSequences`), and the fixture origin may also be `documented (…)` next to `captured` and `derived from …`. The anonymisation guard (`FixtureAnonymisationTest`) has one definition per source; the raw captures of Basecamp 4 are compared when `WEBHOOK_RAW_CAPTURES_DIR_BASECAMP4` is set, those of GitLab still with `WEBHOOK_RAW_CAPTURES_DIR`. + ## [0.2.0] - 2026-12-03 Breaking for 0.1.x: endpoints have a mandatory mode, and only endpoints in the mode `handler` hand their events to delivery handlers. @@ -113,3 +128,4 @@ Initial public release. + diff --git a/CLAUDE.md b/CLAUDE.md index c543ba8..28e8621 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,9 +17,9 @@ PHP >= 8.5 (see `composer.json`). The PHPUnit suite (configuration `phpunit.dist - `unit` (`tests/Unit`): no kernel, no database. Run it with `vendor/bin/phpunit --testsuite unit`. - `integration` (`tests/Integration`): boots the test kernel in `tests/Kernel` (neutral test roles, a stand-in permission voter, a frozen `clock`). 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`); the schema is created by running the migrations, the bundle's own ones included. The workflow `Tests` (`.github/workflows/tests.yml`) runs both suites, group `database` included, as a matrix on PostgreSQL 16 and MySQL 8.0. Without a server, run `vendor/bin/phpunit --testsuite integration --exclude-group database`. -Test helpers live only under `tests/`. The intake is tested through a data-driven matrix: `tests/Support/IntakeCase.php` (one row: endpoint configuration, request, expected result per mode), `IntakeExpectation.php`, `IntakeHarness.php` (the real intake over an in-memory store, no kernel) and `IntakeMatrix.php` (the source-neutral rows); the same rows run against the database in `tests/Integration/Intake/IntakeMatrixDatabaseTest.php`. Test adapters live in `tests/Kernel/` (`ContextTestAdapter`, `ActorlessTestAdapter`, `FilterAttributesTestAdapter`); a source adapter with fixtures adds its rows in its own provider with the same row shape. The GitLab adapter does so: `tests/Fixtures/gitlab/` holds one anonymised GitLab 15.11 delivery per YAML file (`origin` captured or derived, `headers`, `body`), loaded by `tests/Support/GitlabFixtures.php` and turned into rows by `tests/Support/GitlabMatrix.php`. +Test helpers live only under `tests/`. The intake is tested through a data-driven matrix: `tests/Support/IntakeCase.php` (one row: endpoint configuration, request, expected result per mode), `IntakeExpectation.php`, `IntakeHarness.php` (the real intake over an in-memory store, no kernel) and `IntakeMatrix.php` (the source-neutral rows); the same rows run against the database in `tests/Integration/Intake/IntakeMatrixDatabaseTest.php`. Test adapters live in `tests/Kernel/` (`ContextTestAdapter`, `ActorlessTestAdapter`, `FilterAttributesTestAdapter`); a source adapter with fixtures adds its rows in its own provider with the same row shape. Its fixtures live in `tests/Fixtures//`, one delivery per YAML file (`origin`, `headers`, `body`), loaded through the source-neutral `tests/Support/FixtureSet.php` and turned into rows through `tests/Support/FixtureMatrix.php` (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 `IntakeHarnessSequences.php` run a source's sequences without database, and `tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php` runs rows and sequences against the database. `origin` is `captured` (a recorded delivery with neutral values), `documented ()` (built from the source's documentation, every value invented) or `derived from ()` (`FixtureSet::ORIGIN_PATTERN`). Two sources do so: GitLab (`tests/Fixtures/gitlab/`, captured GitLab 15.11 deliveries and fixtures derived from them; `tests/Support/GitlabFixtures.php`, `GitlabMatrix.php`) and Basecamp 4 (`tests/Fixtures/basecamp4/`, built from the Basecamp API documentation, so every fixture is documented or derived and none is captured; `tests/Support/Basecamp4Fixtures.php`, `Basecamp4Matrix.php`). Mark a fixture `captured` only when it is anonymised from a real delivery. `tests/Unit/Intake/Basecamp4LogTest.php` checks the raw log records of Basecamp 4 deliveries without the redaction processor (no path secret, no request path, no payload text) and proves its detector with a leaking test adapter. -Fixtures are public: never copy a raw capture or any of its values into `tests/Fixtures/`; use neutral values (`example.com` hosts, invented ids, names, UUIDs, SHAs and texts). `tests/Unit/Fixtures/FixtureAnonymisationTest.php` enforces structural rules always and, with `WEBHOOK_RAW_CAPTURES_DIR` pointing to a local directory of raw captures (kept outside the repository), fails on any captured value found in a fixture; run it locally whenever fixtures change. +Fixtures are public: never copy a raw capture or any of its values into `tests/Fixtures/`; use neutral values (`example.com` hosts, invented ids, names, UUIDs, SHAs and texts). `tests/Unit/Fixtures/FixtureAnonymisationTest.php` has one definition per source (`sources()`: fixture set, allowed hosts, header values, captures variable, structural values; a new source adds one entry, and every fixture file must belong to a source). It enforces structural rules always and, with the source's variable pointing to a local directory of raw captures (kept outside the repository; `WEBHOOK_RAW_CAPTURES_DIR` for GitLab, `WEBHOOK_RAW_CAPTURES_DIR_BASECAMP4` for Basecamp 4), fails on any captured value found in a fixture of any source; run it locally whenever fixtures change. Replay-window tests build their Standard Webhooks signatures with the time of a frozen clock (`MockClock`), never with `time()`; only the test of the system-time fallback uses `time()`. @@ -40,3 +40,4 @@ Replay-window tests build their Standard Webhooks signatures with the time of a + diff --git a/README.md b/README.md index 02ad35c..a3ddd8c 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,7 @@ The secret is encrypted at rest with `CREDENTIALS_ENCRYPTION_KEY`, the key of `d # config/packages/dmstr_webhook.yaml dmstr_webhook: adapters: + basecamp4: false # off by default gitlab: false # off by default passthrough: true # on by default passthrough_path: false # off by default @@ -225,7 +226,7 @@ Both modes share the checks of the [intake](#intake) (404, 403, 413, 429, 401) a 2. Otherwise the event is inserted as `received` (one write). A duplicate writes nothing and is not handed over again. 3. After the response, the new event goes to every [delivery handler](#delivery-handlers) of the application, once, with the payload unchanged. The handlers set its terminal status (`handled`, `ignored` or `failed`). No other filter, no rate limit per actor and no routing apply; routes of such an endpoint are stored but never consulted. -Which mode fits: the mode `process` needs an adapter that reports who caused an event (an actor), because the allowlist allows no event without one (see [Filters and reasons](#filters-and-reasons)). A source whose adapter reports no actor, which includes the shipped adapters `passthrough`, `passthrough_path` and `standard_webhooks`, is in practice only usable in the mode `handler`; the shipped [GitLab adapter](#gitlab) reports an actor and works in both modes. +Which mode fits: the mode `process` needs an adapter that reports who caused an event (an actor), because the allowlist allows no event without one (see [Filters and reasons](#filters-and-reasons)). A source whose adapter reports no actor, which includes the shipped adapters `passthrough`, `passthrough_path` and `standard_webhooks`, is in practice only usable in the mode `handler`; the shipped adapters [GitLab](#gitlab) and [Basecamp 4](#basecamp-4) report an actor and work in both modes (for Basecamp 4 mind the missing mention fact in the mode `process`). ## Secrets @@ -327,7 +328,7 @@ A route is a routing rule of an endpoint in the mode `process` (`Dmstr\Webhook\E **Matching.** A route matches an event when it is active, its `eventType` is null or exactly the event's type, and every entry of `filters` is strictly equal (`===`) to the event's attribute of that name: `"1"` does not match `1`, `1` does not match `true`, and an attribute the event does not carry matches no value. The active routes of the endpoint are tried by `priority` ascending, then `createdAt`, then `id`; the first match wins. -**Validation against the adapter.** Each adapter declares the attributes a route may filter on, by name and kind (`string`, `integer` or `boolean`; see [Writing an own adapter](#writing-an-own-adapter)). Creating or changing a route checks every filter against the declaration of the endpoint's adapter: a filter on an undeclared attribute, or with a value of another kind, is rejected with 422 at `filters[]`, and the message lists the declared names. Filters on an endpoint whose source type is not an enabled adapter are rejected at `filters`. The GitLab adapter declares `project_id`, `project_path`, `noteable_type`, `target_iid` and `action` (see [GitLab](#gitlab)); the other shipped adapters declare no attributes, so their routes can only use `eventType`. +**Validation against the adapter.** Each adapter declares the attributes a route may filter on, by name and kind (`string`, `integer` or `boolean`; see [Writing an own adapter](#writing-an-own-adapter)). Creating or changing a route checks every filter against the declaration of the endpoint's adapter: a filter on an undeclared attribute, or with a value of another kind, is rejected with 422 at `filters[]`, and the message lists the declared names. Filters on an endpoint whose source type is not an enabled adapter are rejected at `filters`. The GitLab adapter declares `project_id`, `project_path`, `noteable_type`, `target_iid` and `action` (see [GitLab](#gitlab)), the Basecamp 4 adapter `kind`, `project_id` and `recording_type` (see [Basecamp 4](#basecamp-4)); the other shipped adapters declare no attributes, so their routes can only use `eventType`. **Result on the event.** A matching route sets the event to `routed` and stores the route's id (a UUID string, no foreign key) in the event's `route`; the id stays when the route is renamed or deleted. Without a match the event is `ignored` with `no_route`. Starting the process of a `routed` event is not part of the bundle yet (see [Not built yet](#not-built-yet)). @@ -409,8 +410,9 @@ An adapter is a `symfony/webhook` request parser for one source type that also d | `passthrough_path` | disabled | path secret: the secret as path segment, `/webhook//`, for sources that cannot send a header | SHA-256 hex of the body | `webhook.passthrough_path` | none | | `standard_webhooks` | disabled | [Standard Webhooks](https://www.standardwebhooks.com/), see below | `webhook-id` | `payload.type` if it is a non-empty string, else `webhook.standard_webhooks` | `payload.timestamp` if it is an RFC 3339 date-time, else none | | `gitlab` | disabled | header token: header `X-Gitlab-Token` equal to the secret, see [GitLab](#gitlab) | semantic key per hook kind, see below | `gitlab.note`, `gitlab.merge_request`, `gitlab.tag_push` | `object_attributes.updated_at` of notes and merge requests, none for tag pushes | +| `basecamp4` | disabled | path secret: the secret as path segment, `/webhook//`, see [Basecamp 4](#basecamp-4) | `basecamp4:event:`, see below | `basecamp4.`, `basecamp4.unknown` without a valid `kind` | top-level `created_at` if it is an ISO 8601 date-time with `Z` or an offset, else none | -The adapters `passthrough`, `passthrough_path` and `standard_webhooks` report no event context: no actor, all facts unknown, no references and no filter attributes. In the mode `process` every one of their events ends `ignored` with `actor_not_allowed`, so use them in the mode `handler`. The `gitlab` adapter reports a context and declares filter attributes, see [GitLab](#gitlab). +The adapters `passthrough`, `passthrough_path` and `standard_webhooks` report no event context: no actor, all facts unknown, no references and no filter attributes. In the mode `process` every one of their events ends `ignored` with `actor_not_allowed`, so use them in the mode `handler`. The adapters `gitlab` and `basecamp4` report a context and declare filter attributes, see [GitLab](#gitlab) and [Basecamp 4](#basecamp-4). The pass-through adapters set no event time. The event row always stores the raw body; for a body that is not a JSON object or array, the decoded payload of the remote event (the one a [delivery handler](#delivery-handlers) receives) is empty. @@ -503,6 +505,59 @@ Accepted collisions of the semantic key: two updates of one merge request with t **What GitLab 15.11 does not deliver.** The edit of a note and system notes (e.g. "changed the description", "approved this merge request") produced no Note Hook delivery on GitLab 15.11. The adapter still evaluates `edit` and `systemGenerated` for later versions that send them; the fixtures of these cases are derived from captured deliveries and marked as derived. +### Basecamp 4 + +Project webhooks of Basecamp 4 (the API documented as `bc3-api`, section [Webhooks](https://github.com/basecamp/bc3-api/blob/master/sections/webhooks.md)). The adapter is built against that documentation, not against captured deliveries: the fixtures in `./tests/Fixtures/basecamp4/` follow the documented payload and headers with invented values and are marked `documented` or derived from such a fixture; none is `captured` (see [Tests](#tests)). Where the documentation is silent, the adapter makes an assumption, listed under "What the documentation leaves open" below. + +**Enable it** in the bundle configuration and create an endpoint with the source type `basecamp4`, a token secret (see below) and the Basecamp person ids allowed to trigger a run in `allowedActorIds`; `actorId` is the person id of the application's own Basecamp account, with the caveat under "Event context". `actorHandle` has no effect for this source. + +```yaml +# config/packages/dmstr_webhook.yaml +dmstr_webhook: + adapters: + basecamp4: true +``` + +**Secret in the path.** Basecamp signs nothing and sends no secret header, so the endpoint secret is the last segment of the hook URL (`VerificationStrategy::PathSecret`): `https:///webhook//`. The segment is compared with the endpoint secret in constant time; a wrong, missing, shortened or extended segment, a further path segment after it, and a secret sent in a header instead of the path all fail with 401 and store nothing. + +- Use a token secret: at least 32 and at most 512 characters from `A-Z a-z 0-9 _ -` (the format the endpoint validates, see [Secrets](#secrets)), which needs no encoding in a URL path. The endpoint would also accept a Standard Webhooks secret `whsec_`, but its base64 may contain `+`, `/` and `=`; do not use one for this source. +- Basecamp requires an HTTPS `payload_url`, so the secret travels only inside TLS. +- The secret ends up wherever the URL is logged. The bundle masks the segment after `/webhook//` on every Monolog channel (see [Log redaction](#log-redaction)); the reverse proxy and every proxy or load balancer in front of the application must mask it in their access logs as well (the `request>uri` filter of the Caddy example). Rotating the secret means changing the hook URL in Basecamp. + +**Hook settings in Basecamp.** Register the hook URL per project, in the project's webhook settings (Project, Webhooks) or through the API with `POST /buckets//webhooks.json` and a JSON body with `payload_url` (the hook URL above) and `types` (the recording types to deliver, e.g. `Comment`, `Message`, `Kanban::Card`). Basecamp documents the delivery headers `Content-Type: application/json`, `User-Agent: Basecamp3 Webhook` and `X-Request-Id`; none of them is used for verification or the dedupe key (`X-Request-Id` only appears as `delivery_id` in the log lines, see [Audit and logging](#audit-and-logging)). Basecamp retries a delivery that does not get a 2xx answer, up to 10 attempts with exponential backoff, and follows no redirects: point the hook at the final URL. The intake answers every verified delivery with `202`, so an accepted delivery is not retried. + +**Event types.** Every verified delivery is one event, whatever its kind; no kind is dropped. The type is `basecamp4.` with the payload's `kind` taken verbatim when it consists of 1 to 100 characters from `a-z 0-9 _` (e.g. `basecamp4.message_created`, `basecamp4.comment_created`, `basecamp4.todo_completed`), and `basecamp4.unknown` when `kind` is missing or does not fit. The kind `kanban_card_moved` is not in the documented list of kinds; it is known from use and treated like any other kind (`basecamp4.kanban_card_moved`). A body that is not JSON is still an event of the type `basecamp4.unknown` with an empty decoded payload; the stored payload is always the raw body, unchanged. + +**Event context.** + +- Actor: the person id of the top-level `creator` (`creator.id`, an integer or a string of digits) as a string, display name `creator.name`. A name or e-mail address is never the id, so a person who takes over the display name of the application's account gains nothing. An event without a usable top-level `creator.id` has no actor (the `creator` inside `recording` is not taken) and ends `ignored` with `actor_not_allowed` in the mode `process`. +- Own identity: the endpoint's `actorId` is compared with `creator.id`, and a match is `ignored` with `own_actor` in both modes. Basecamp names the account that performed an action as `creator`, so when the application writes to Basecamp with the account set as `actorId`, the deliveries of its own writes are ignored. An endpoint whose application writes with that account and still needs those deliveries must not set `actorId`. +- References: project `recording.bucket.id`; target of the reference kind `recording` with `recording.id`, the recording the event is about; no note and no discussion. For a comment the target is the comment itself: the recording it belongs to (e.g. the card or message) is only in the payload (`recording.parent`). For copy and move kinds the destination (`copy.bucket.id`) is only in the payload as well. +- `edit`: Yes for a kind ending in `_title_updated` or `_content_updated` (the edit of an existing recording), No for a kind ending in `_created`, unknown for every other kind (archived, unarchived, trashed, untrashed, copied, moved, completed, assignment changes, …) and without a valid kind. +- `systemGenerated`, `confidential` and `mentionsEndpoint`: always unknown; the payload has no equivalent, so their filters never fire. + +**No mention gate in the mode `process`.** With `mentionsEndpoint` unknown, the filter `not_mentioned` never applies: every event of an allowed creator that is not an edit and matches a route is `routed`, including trashed, archived, moved and unknown kinds, whose `edit` fact is unknown. A catch-all route therefore starts a process for every such event. Give routes an `eventType` or a `kind` filter, or use the mode `handler` and decide in a [delivery handler](#delivery-handlers). + +**Filter attributes**, each only on the events whose payload has it: + +| Attribute | Kind | Value | +| --- | --- | --- | +| `kind` | string | `kind`, only when it fits the pattern above, e.g. `comment_created` | +| `project_id` | integer | `recording.bucket.id` | +| `recording_type` | string | `recording.type`, e.g. `Message`, `Comment`, `Todo`, `Kanban::Card` | + +A route for new comments in one project: + +```json +{"endpoint": "/api/admin/webhook_endpoints/", "name": "new-comments", "eventType": "basecamp4.comment_created", "filters": {"project_id": 70200001, "recording_type": "Comment"}, "processDefinitionKey": "answer-comment"} +``` + +No text of a delivery (titles, content, `details`, names other than the actor's display name) enters the context, the attributes, the type, the dedupe key or a log line; it stays in the stored payload, which a delivery handler receives unchanged. + +**Dedupe key.** `basecamp4:event:` from the top-level event `id` (an integer or a string of digits) when the payload also has a valid `kind`; otherwise `basecamp4:event:sha256:`. Headers never enter the key, so a delivery that arrives again with another `X-Request-Id` and the same body is a duplicate. Each change in Basecamp is an event with an id of its own, so the creation, every edit and the trashing of a recording are separate events. + +**What the documentation leaves open.** It does not say whether the top-level `id` stays the same when Basecamp retries a delivery. The dedupe key assumes it does; if a retry carried a new `id`, the retry would be stored as a second event. It does not list `kanban_card_moved` among the kinds, and it describes no field that tells a system-generated, confidential or mentioning event apart, hence the unknown facts. + ## Events @@ -712,7 +767,7 @@ An adapter is a service implementing `Dmstr\Webhook\Adapter\WebhookAdapterInterf The attribute tags the service `dmstr_webhook.adapter` with the source name; when the source is not enabled under `dmstr_webhook.adapters`, the service is removed from the container. Classes under the application's own namespace need autoconfiguration (the default in `config/services.yaml`) for the attribute to take effect. -The usual base is `Dmstr\Webhook\Adapter\AbstractWebhookParser`, an `AbstractRequestParser` that matches `POST` only, declares no filter attributes (`FilterAttributes::none()`) and offers `bodyHash()` (SHA-256 hex of the raw body), `jsonPayload()` (the body decoded as a JSON object or array, an empty array otherwise) and `endpointHandle()` (the endpoint's handle, see below). Return a `Dmstr\Webhook\Adapter\WebhookRemoteEvent` to also pass the event time and the event context; a plain `RemoteEvent` has neither. +The usual base is `Dmstr\Webhook\Adapter\AbstractWebhookParser`, an `AbstractRequestParser` that matches `POST` only, declares no filter attributes (`FilterAttributes::none()`) and offers `bodyHash()` (SHA-256 hex of the raw body), `jsonPayload()` (the body decoded as a JSON object or array, an empty array otherwise) `endpointHandle()` (the endpoint's handle, see below) and `verifyPathSecret()` (the check of the strategy `PathSecret`: the secret path segment must equal the endpoint secret, compared in constant time, else a `RejectWebhookException` with 401; the adapters `passthrough_path` and `basecamp4` use it). Return a `Dmstr\Webhook\Adapter\WebhookRemoteEvent` to also pass the event time and the event context; a plain `RemoteEvent` has neither. How the intake calls `parse(Request $request, string $secret)`: @@ -853,7 +908,7 @@ The PHPUnit suites live in this repository (configuration `./phpunit.dist.xml`, - `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. -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: the GitLab rows (`./tests/Support/GitlabMatrix.php`) are built from the YAML fixtures in `./tests/Fixtures/gitlab/` (one delivery per file with `origin`, `headers` and `body`; `origin` says whether it is a captured GitLab 15.11 delivery with neutral values or derived from one). `./tests/Unit/Fixtures/FixtureAnonymisationTest.php` guards the anonymisation: structural rules on every fixture (only `example.com` hosts, no redaction placeholders, no avatar service, ASCII only), and, when `WEBHOOK_RAW_CAPTURES_DIR` points to a local directory of raw captures (never committed), a check that no value of those captures occurs in any fixture. +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. ```bash composer install @@ -878,3 +933,4 @@ MIT, see [LICENSE](LICENSE). + diff --git a/src/WebhookBundle.php b/src/WebhookBundle.php index 3a07659..338bffc 100644 --- a/src/WebhookBundle.php +++ b/src/WebhookBundle.php @@ -39,8 +39,9 @@ * config/routes.yaml; {@see Intake\WebhookIntake}) and its console twin * `webhook:deliver`, with the adapters `passthrough` (header token), * `passthrough_path` (secret path segment), `standard_webhooks` - * (signature) and `gitlab` (header token, notes, merge requests and tag - * pushes with an event context), and the hand-off seam + * (signature), `gitlab` (header token, notes, merge requests and tag + * pushes with an event context) and `basecamp4` (secret path segment, + * every project webhook event with an event context), and the hand-off seam * {@see DeliveryHandlerInterface} * (tag `dmstr_webhook.delivery_handler`, no implementation shipped); * - a Monolog processor that masks the secret path segment and secret @@ -172,3 +173,4 @@ public function build(ContainerBuilder $container): void // - revised 2026-11-27 (intake: delivery handler tag, class doc) // - 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)