Repository navigation
feat: open /feature and /bug issues from the API #653
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
simonhamp
wants to merge
9
commits into
dev-null-sh:production
Choose a base branch
from
simonhamp:feat/api-issues
base: production
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
59cae24
feat: open /feature and /bug issues from the API
simonhamp f7a20dd
fix: answer github_issue_failed with a 503, which Cloudflare passes t…
simonhamp 3995de3
fix: take the web's issue body minimum and environment details in the…
simonhamp ac0a23f
Merge branch 'production' into feat/api-issues
simonhamp 772e82a
Merge branch 'production' into feat/api-issues
simonhamp 1a76ce9
Merge branch 'production' into feat/api-issues
simonhamp 26fef8e
Merge branch 'production' into feat/api-issues
simonhamp b8949a9
Merge branch 'production' into feat/api-issues
simonhamp 03fc8fe
Merge branch 'production' into feat/api-issues
simonhamp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\Http\Controllers\Api; | ||
|
|
||
| use App\Actions\CreateIssue; | ||
| use App\Enums\ApiErrorCode; | ||
| use App\Exceptions\ApiException; | ||
| use App\Http\Requests\CreateApiIssueRequest; | ||
| use App\Models\User; | ||
| use Illuminate\Container\Attributes\CurrentUser; | ||
| use Illuminate\Http\Client\ConnectionException; | ||
| use Illuminate\Http\Client\RequestException; | ||
| use Illuminate\Http\JsonResponse; | ||
|
|
||
| final readonly class IssueController | ||
| { | ||
| /** | ||
| * Opens an issue upstream, as the web's /feature and /bug commands do, and answers as the web does, with its number | ||
| * and URL. When GitHub didn't respond, the issue may have been opened anyway, so the message says to check first. | ||
| */ | ||
| public function store(CreateApiIssueRequest $request, #[CurrentUser] User $user, CreateIssue $action): JsonResponse | ||
| { | ||
| try { | ||
| $issue = $action->handle($user, $request->string('command')->value(), $request->string('body')->value(), $request->environment()); | ||
| } catch (ConnectionException) { | ||
| return new ApiException(ApiErrorCode::GitHubIssueFailed, __('GitHub did not respond. Check the upstream issues before trying again. Your draft is safe.'))->render(); | ||
| } catch (RequestException) { | ||
| return new ApiException(ApiErrorCode::GitHubIssueFailed, __('GitHub did not create the issue. Your draft is safe.'))->render(); | ||
| } | ||
|
|
||
| return response()->json($issue, 201); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\Http\Middleware; | ||
|
|
||
| use App\Enums\ApiErrorCode; | ||
| use App\Exceptions\ApiException; | ||
| use App\Models\User; | ||
| use Closure; | ||
| use Illuminate\Http\Request; | ||
| use Illuminate\Support\Facades\RateLimiter; | ||
| use Symfony\Component\HttpFoundation\Response; | ||
|
|
||
| final readonly class ThrottleIssues | ||
| { | ||
| private const int PER_HOUR = 5; | ||
|
|
||
| /** | ||
| * One budget of issues an hour, from the web or the mobile app. Only issues that were opened count towards it, so a | ||
| * rejected draft or a GitHub outage costs nothing. | ||
| * | ||
| * @param Closure(Request): (Response) $next | ||
| */ | ||
| public function handle(Request $request, Closure $next): Response | ||
| { | ||
| $user = $request->user(); | ||
| assert($user instanceof User); | ||
|
|
||
| $key = "issues:{$user->id}"; | ||
|
|
||
| if (RateLimiter::tooManyAttempts($key, self::PER_HOUR)) { | ||
| $message = 'Issue limit reached. Try again in an hour.'; | ||
| $headers = ['Retry-After' => RateLimiter::availableIn($key)]; | ||
|
|
||
| // The mobile app reads JSON with a code... | ||
| return $request->routeIs('api-issue.store') | ||
| ? new ApiException(ApiErrorCode::RateLimited, $message, $headers)->render() | ||
| : response()->json(['message' => $message], 429, $headers); | ||
| } | ||
|
|
||
| $response = $next($request); | ||
|
|
||
| if ($response->getStatusCode() === 201) { | ||
| RateLimiter::hit($key, 3600); | ||
| } | ||
|
|
||
| return $response; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\Http\Requests; | ||
|
|
||
| use App\Models\Commit; | ||
| use Illuminate\Foundation\Http\FormRequest; | ||
| use Illuminate\Validation\Rule; | ||
| use Illuminate\Validation\Rules\In; | ||
|
|
||
| final class CreateApiIssueRequest extends FormRequest | ||
| { | ||
| public function authorize(): bool | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| /** | ||
| * Blank lines are collapsed before the body is measured, as on the web. | ||
| */ | ||
| public function prepareForValidation(): void | ||
| { | ||
| CreateCommitRequest::normalizeBody($this); | ||
| } | ||
|
|
||
| /** | ||
| * An issue from the mobile app, sent as JSON, with the web's rules: its commands, a body long enough to act on, and | ||
| * the same environment details the web sends about the browser and screen. | ||
| * | ||
| * @return array<string, array<int, string|In>> | ||
| */ | ||
| public function rules(): array | ||
| { | ||
| return [ | ||
| 'command' => ['required', Rule::in(['/feature', '/bug'])], | ||
| 'body' => ['required', 'string', 'min:'.CreateIssueRequest::MIN_BODY_LENGTH, 'max:'.Commit::MAX_BODY_LENGTH], | ||
| 'environment' => ['nullable', 'array:'.implode(',', CreateIssueRequest::ENVIRONMENT_FIELDS)], | ||
| 'environment.*' => ['nullable', 'string', 'max:100'], | ||
| ]; | ||
| } | ||
|
|
||
| /** | ||
| * @return array<string, string> | ||
| */ | ||
| public function environment(): array | ||
| { | ||
| /** @var array<string, string|null> $environment */ | ||
| $environment = $this->array('environment'); | ||
|
|
||
| return array_filter($environment, fn (?string $value): bool => $value !== null && $value !== ''); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| use App\Models\User; | ||
| use Illuminate\Http\Client\ConnectionException; | ||
| use Illuminate\Http\Client\Request; | ||
| use Illuminate\Support\Facades\Http; | ||
|
|
||
| beforeEach(function (): void { | ||
| $key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]); | ||
| assert($key !== false); | ||
| openssl_pkey_export($key, $privateKey); | ||
|
|
||
| config(['services.github_app' => ['id' => '12345', 'private_key' => str_replace("\n", '\n', $privateKey)]]); | ||
|
|
||
| $this->user = User::factory()->create(['username' => 'taylor']); | ||
| $this->keyPair = apiKeyPairFor($this->user); | ||
| }); | ||
|
|
||
| it('opens the issue as the app, crediting the reporter, with the label of the command, as the web does', function (string $command, string $label): void { | ||
| fakeGitHubApp(); | ||
| $body = "Search loses its filters\n\nSteps: select PHP, then navigate back."; | ||
|
|
||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => $command, 'body' => $body]) | ||
| ->assertCreated() | ||
| ->assertExactJson(['number' => 123, 'url' => 'https://github.com/nunomaduro/dev-null.sh/issues/123']); | ||
|
|
||
| Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.github.com/repos/nunomaduro/dev-null.sh/issues' | ||
| && $request->hasHeader('Authorization', 'Bearer installation-token') | ||
| && $request['title'] === 'Search loses its filters' | ||
| && $request['body'] === $body."\n\n---\n\nReported by @taylor via [/dev/null](".route('user.show', $this->user).').' | ||
| && $request['labels'] === [$label]); | ||
| $this->assertDatabaseCount('commits', 0); | ||
| })->with([ | ||
| 'feature' => ['/feature', 'enhancement'], | ||
| 'bug' => ['/bug', 'bug'], | ||
| ]); | ||
|
|
||
| it('collapses blank lines before measuring and sending the body', function (): void { | ||
| fakeGitHubApp(); | ||
|
|
||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/feature', 'body' => "Dark mode\n\n\n\nplease"]) | ||
| ->assertCreated(); | ||
|
|
||
| Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/issues') | ||
| && str_starts_with((string) $request['body'], "Dark mode\n\nplease\n\n---")); | ||
| }); | ||
|
|
||
| it('folds the environment the app sends into the body, as the web does', function (): void { | ||
| fakeGitHubApp(); | ||
|
|
||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), [ | ||
| 'command' => '/bug', | ||
| 'body' => 'Broken.', | ||
| 'environment' => ['browser' => 'devnull app', 'os' => 'iOS 27.0', 'language' => ''], | ||
| ])->assertCreated(); | ||
|
|
||
| Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/issues') | ||
| && str_starts_with((string) $request['body'], "Broken.\n\n<details>\n<summary>Environment</summary>\n\n| | |\n|---|---|\n| Browser | `devnull app` |\n| Os | `iOS 27.0` |\n\n</details>\n\n---")); | ||
| }); | ||
|
|
||
| it('keeps the draft when GitHub rejects the issue or does not respond, with a code', function (Closure $response, string $message): void { | ||
| Http::fake([ | ||
| 'api.github.com/repos/nunomaduro/dev-null.sh/installation' => Http::response(['id' => 99]), | ||
| 'api.github.com/app/installations/99/access_tokens' => Http::response(['token' => 'installation-token'], 201), | ||
| 'api.github.com/repos/nunomaduro/dev-null.sh/issues' => $response, | ||
| ]); | ||
|
|
||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken.']) | ||
| ->assertServiceUnavailable() | ||
| ->assertExactJson(['message' => $message, 'code' => 'github_issue_failed']); | ||
| })->with([ | ||
| 'rejected' => [fn () => Http::response(['message' => 'Validation Failed'], 422), 'GitHub did not create the issue. Your draft is safe.'], | ||
| 'unavailable' => [fn () => throw new ConnectionException('timeout'), 'GitHub did not respond. Check the upstream issues before trying again. Your draft is safe.'], | ||
| ]); | ||
|
|
||
| it('validates the command and the body as the web does', function (array $payload, string $field): void { | ||
| Http::fake(); | ||
|
|
||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), $payload) | ||
| ->assertUnprocessable() | ||
| ->assertOnlyJsonValidationErrors($field); | ||
|
|
||
| Http::assertNothingSent(); | ||
| })->with([ | ||
| 'unknown command' => [['command' => '/deploy', 'body' => 'Ship it.'], 'command'], | ||
| 'no command' => [['body' => 'Ship it.'], 'command'], | ||
| 'missing body' => [['command' => '/bug'], 'body'], | ||
| 'blank lines only' => [['command' => '/bug', 'body' => "a\n\n\n\n"], 'body'], | ||
| 'too short for an issue' => [['command' => '/bug', 'body' => 'ab'], 'body'], | ||
| 'too long' => [['command' => '/bug', 'body' => str_repeat('a', 4001)], 'body'], | ||
| 'unknown environment field' => [['command' => '/bug', 'body' => 'Broken.', 'environment' => ['cookie' => 'secret']], 'environment'], | ||
| ]); | ||
|
|
||
| it('shares the web limit of five opened issues an hour, answering with a code', function (): void { | ||
| fakeGitHubApp(); | ||
|
|
||
| foreach (range(1, 3) as $attempt) { | ||
| $this->actingAs($this->user)->postJson(route('issue.store'), ['command' => '/bug', 'body' => "Broken {$attempt}."])->assertCreated(); | ||
| } | ||
|
|
||
| foreach (range(4, 5) as $attempt) { | ||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/bug', 'body' => "Broken {$attempt}."])->assertCreated(); | ||
| } | ||
|
|
||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken again.']) | ||
| ->assertTooManyRequests() | ||
| ->assertHeader('Retry-After', 3600) | ||
| ->assertExactJson(['message' => 'Issue limit reached. Try again in an hour.', 'code' => 'rate_limited']); | ||
|
|
||
| $this->travel(1)->hours(); | ||
|
|
||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken later.'])->assertCreated(); | ||
| }); | ||
|
|
||
| it('does not count rejected drafts or failed attempts towards the limit', function (): void { | ||
| Http::fake([ | ||
| 'api.github.com/repos/nunomaduro/dev-null.sh/installation' => Http::response(['id' => 99]), | ||
| 'api.github.com/app/installations/99/access_tokens' => Http::response(['token' => 'installation-token'], 201), | ||
| 'api.github.com/repos/nunomaduro/dev-null.sh/issues' => Http::sequence() | ||
| ->push([], 500)->push([], 500)->push([], 500) | ||
| ->push([], 500)->push([], 500)->push([], 500) | ||
| ->push(['number' => 1, 'html_url' => 'https://github.com/nunomaduro/dev-null.sh/issues/1'], 201), | ||
| ]); | ||
|
|
||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/deploy', 'body' => 'Nope.'])->assertUnprocessable(); | ||
|
|
||
| foreach (range(1, 6) as $attempt) { | ||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken.'])->assertServiceUnavailable(); | ||
| $this->travel(11)->seconds(); | ||
| } | ||
|
|
||
| signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken.'])->assertCreated(); | ||
| }); | ||
|
|
||
| it('rejects requests that are not signed', function (): void { | ||
| Http::fake(); | ||
|
|
||
| $this->actingAs($this->user)->postJson(route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken.'])->assertUnauthorized(); | ||
|
|
||
| Http::assertNothingSent(); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔎 Supported by static analysis
Script executed:
Repository: dev-null-sh/dev-null.sh
Length of output: 5605
Remove the duplicate
fakeGitHubAppdeclaration.tests/Pest.phpandtests/Feature/Controllers/IssueControllerTest.phpboth declarefakeGitHubApp(array $issue = []): voidat file top level. Neither file declares a namespace, so both declarations are global. When both files load in the same PHP process, PHP stops withCannot redeclare fakeGitHubApp(), and the test run aborts.Remove the declaration at
tests/Feature/Controllers/IssueControllerTest.php:42and call the shared helper fromtests/Pest.php. Before you remove it, confirm that the two function bodies match. If they differ, rename one helper instead.