diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 76b4688ff1..58afcbc112 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -582,6 +582,7 @@ A signed request sees what the web shows you, such as your own pending commits a - read your account, logs, replies, notifications (including grouped activity), and starred commits; - commit, reply, and quote, with images, and delete your commits, with the same undo window as the web; - preview commit drafts without publishing them; +- request a feature or report a bug as `/feature` and `/bug` do, with the same limit of 10 opened issues a day; - follow or unfollow people and organizations, mute or unmute, and block or unblock, and list who you muted and blocked; - read who to follow, also as it is suggested beside a profile or a commit, and mark a suggestion not interested; - read the hot topics, and each one's commits from the past week with its recap; @@ -641,9 +642,9 @@ Start a fresh commit draft with **`/bug `** or **`/feature `** to switch it into Empty issue drafts show a short Markdown template: steps and expected versus actual behavior for bugs, or the problem and proposal for features. The first top-level `# Heading` becomes the issue title and is removed from the body; the remaining Markdown is preserved. Without a heading, the first line is used as the title and the full draft remains in the body. -Successful issue creation is limited to **ten issues per day per user**. Rejected drafts and failed requests do not use that allowance. If GitHub or the connection fails, the draft stays available. Check upstream before retrying an uncertain submission to avoid duplicates. Use a commit's Report control instead when reporting abusive content. +Successful issue creation is limited to **ten issues per day per user**, shared between the web and the apps. Rejected drafts and failed requests do not use that allowance. If GitHub or the connection fails, the draft stays available. Check upstream before retrying an uncertain submission to avoid duplicates. Use a commit's Report control instead when reporting abusive content. -Sources: [issue command UI](resources/js/components/issue-command.tsx), [issue validation](app/Http/Requests/CreateIssueRequest.php), [issue controller](app/Http/Controllers/IssueController.php). +Sources: [issue command UI](resources/js/components/issue-command.tsx), [issue validation](app/Http/Requests/CreateIssueRequest.php), [issue controller](app/Http/Controllers/IssueController.php), [daily limit](app/Http/Middleware/ThrottleIssues.php), [API issue controller](app/Http/Controllers/Api/IssueController.php). ### Exporting your data diff --git a/app/Enums/ApiErrorCode.php b/app/Enums/ApiErrorCode.php index dd604800e6..2cc4924d59 100644 --- a/app/Enums/ApiErrorCode.php +++ b/app/Enums/ApiErrorCode.php @@ -23,6 +23,8 @@ enum ApiErrorCode: string case TimedOut = 'timed_out'; case Banned = 'banned'; case CommitRulesRequired = 'commit_rules_required'; + case GitHubIssueRefused = 'github_issue_refused'; + case GitHubIssueUnanswered = 'github_issue_unanswered'; public function status(): int { @@ -33,6 +35,7 @@ public function status(): int self::CommitUnavailable => 404, self::PasteisExhausted => 422, self::RateLimited => 429, + self::GitHubIssueRefused, self::GitHubIssueUnanswered => 502, self::GitHubSyncFailed => 503, }; } diff --git a/app/Exceptions/ApiException.php b/app/Exceptions/ApiException.php index 07b46997b0..76593272f0 100644 --- a/app/Exceptions/ApiException.php +++ b/app/Exceptions/ApiException.php @@ -71,6 +71,22 @@ public static function gitHubSyncFailed(): self return new self(ApiErrorCode::GitHubSyncFailed, __('Could not sync from GitHub. Try again in a minute.')); } + /** + * GitHub refused the issue, so trying again is safe, as the web says it. + */ + public static function gitHubIssueRefused(): self + { + return new self(ApiErrorCode::GitHubIssueRefused, __('GitHub did not create the issue. Your draft is safe.')); + } + + /** + * GitHub did not answer, so the issue may exist anyway and trying again may duplicate it, as the web says it. + */ + public static function gitHubIssueUnanswered(): self + { + return new self(ApiErrorCode::GitHubIssueUnanswered, __('GitHub did not respond. Check the upstream issues before trying again. Your draft is safe.')); + } + /** * The user is banned, so the only thing left for them is deleting their account. */ diff --git a/app/Http/Controllers/Api/IssueController.php b/app/Http/Controllers/Api/IssueController.php new file mode 100644 index 0000000000..62ed697127 --- /dev/null +++ b/app/Http/Controllers/Api/IssueController.php @@ -0,0 +1,38 @@ +handle( + $user, + $request->string('command')->value(), + $request->string('body')->value(), + $request->environment(), + ); + } catch (ConnectionException) { + throw ApiException::gitHubIssueUnanswered(); + } catch (RequestException) { + throw ApiException::gitHubIssueRefused(); + } + + return response()->json($issue, 201); + } +} diff --git a/app/Http/Controllers/IssueController.php b/app/Http/Controllers/IssueController.php index 08cab82ec4..60bd46f166 100644 --- a/app/Http/Controllers/IssueController.php +++ b/app/Http/Controllers/IssueController.php @@ -11,23 +11,11 @@ use Illuminate\Http\Client\ConnectionException; use Illuminate\Http\Client\RequestException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\RateLimiter; final readonly class IssueController { - private const int MaxIssuesPerDay = 10; - - /** - * Only issues that were opened count towards the daily limit, so a rejected draft or a GitHub outage costs nothing. - */ public function store(CreateIssueRequest $request, #[CurrentUser] User $user, CreateIssue $action): JsonResponse { - $key = 'issues:'.$user->id; - - if (RateLimiter::tooManyAttempts($key, self::MaxIssuesPerDay)) { - return response()->json(['message' => 'Issue limit reached: 10 a day. Try again tomorrow.'], 429); - } - try { $issue = $action->handle( $user, @@ -45,8 +33,6 @@ public function store(CreateIssueRequest $request, #[CurrentUser] User $user, Cr ], 502); } - RateLimiter::hit($key, 86400); - return response()->json($issue, 201); } } diff --git a/app/Http/Middleware/ThrottleIssues.php b/app/Http/Middleware/ThrottleIssues.php new file mode 100644 index 0000000000..49138d87f3 --- /dev/null +++ b/app/Http/Middleware/ThrottleIssues.php @@ -0,0 +1,58 @@ +user(); + assert($user instanceof User); + + $key = "issues:{$user->id}"; + + if (RateLimiter::tooManyAttempts($key, self::PER_DAY)) { + return $this->tooMany($request, RateLimiter::availableIn($key)); + } + + $response = $next($request); + + if ($response->getStatusCode() === Response::HTTP_CREATED) { + RateLimiter::hit($key, self::DECAY_SECONDS); + } + + return $response; + } + + private function tooMany(Request $request, int $retryAfter): Response + { + $message = 'Issue limit reached: '.self::PER_DAY.' a day. Try again tomorrow.'; + + // The apps read JSON with a code... + if ($request->routeIs('api-issue.store')) { + return new ApiException(ApiErrorCode::RateLimited, $message, ['Retry-After' => $retryAfter])->render(); + } + + return response()->json(['message' => $message], 429); + } +} diff --git a/app/Http/Requests/CreateApiIssueRequest.php b/app/Http/Requests/CreateApiIssueRequest.php new file mode 100644 index 0000000000..fa58bd0f13 --- /dev/null +++ b/app/Http/Requests/CreateApiIssueRequest.php @@ -0,0 +1,34 @@ +> + */ + public function rules(): array + { + return CreateIssueRequest::issueRules(); + } + + /** + * @return array + */ + public function environment(): array + { + return CreateIssueRequest::filledEnvironment($this); + } +} diff --git a/app/Http/Requests/CreateIssueRequest.php b/app/Http/Requests/CreateIssueRequest.php index b422bbf7e0..cd22bb3964 100644 --- a/app/Http/Requests/CreateIssueRequest.php +++ b/app/Http/Requests/CreateIssueRequest.php @@ -18,17 +18,12 @@ final class CreateIssueRequest extends FormRequest */ public const int MIN_BODY_LENGTH = 3; - public function prepareForValidation(): void - { - CreateCommitRequest::normalizeBody($this); - } - /** - * Issues carry text only: images are not accepted. + * The rules of every request that opens an issue, so the apps validate drafts as the web does. * * @return array> */ - public function rules(): array + public static function issueRules(): array { return [ 'command' => ['required', Rule::in(['/feature', '/bug'])], @@ -39,13 +34,38 @@ public function rules(): array } /** + * The environment fields the reporter filled, leaving out empty ones. + * * @return array */ - public function environment(): array + public static function filledEnvironment(FormRequest $request): array { /** @var array $environment */ - $environment = $this->array('environment'); + $environment = $request->array('environment'); return array_filter($environment, fn (?string $value): bool => $value !== null && $value !== ''); } + + public function prepareForValidation(): void + { + CreateCommitRequest::normalizeBody($this); + } + + /** + * Issues carry text only: images are not accepted. + * + * @return array> + */ + public function rules(): array + { + return self::issueRules(); + } + + /** + * @return array + */ + public function environment(): array + { + return self::filledEnvironment($this); + } } diff --git a/routes/api.php b/routes/api.php index 91ff152f76..cd409d9076 100644 --- a/routes/api.php +++ b/routes/api.php @@ -32,6 +32,7 @@ use App\Http\Controllers\Api\DeviceController; use App\Http\Controllers\Api\DevicePushTokenController; use App\Http\Controllers\Api\HeadlineController; +use App\Http\Controllers\Api\IssueController; use App\Http\Controllers\Api\IssueSuggestionController; use App\Http\Controllers\Api\LiveFollowingController; use App\Http\Controllers\Api\LogController; @@ -97,6 +98,7 @@ use App\Http\Middleware\PreventPostingInTimeout; use App\Http\Middleware\RequireCommitRules; use App\Http\Middleware\ThrottleCommits; +use App\Http\Middleware\ThrottleIssues; use App\Http\Middleware\UpdateLastSeenAt; use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse; use Illuminate\Cookie\Middleware\EncryptCookies; @@ -241,6 +243,11 @@ ->middleware('throttle:issue-suggestions') ->name('api-issue-suggestion.index'); + // Feature requests and bug reports, opened on GitHub as the web's /feature and /bug commands open them... + Route::post('issues', [IssueController::class, 'store']) + ->middleware([PreventPostingInTimeout::class, 'throttle:10,1', ThrottleIssues::class]) + ->name('api-issue.store'); + // User Remotes: the switch from the web's settings, and the settings menu on its Remotes page... Route::put('me/remotes', [UserRemotesController::class, 'update'])->name('api-user-remotes.update'); Route::put('me/remote-preferences', [UserRemotePreferencesController::class, 'update']) diff --git a/routes/web.php b/routes/web.php index ec2fd38f6f..13b13548d1 100644 --- a/routes/web.php +++ b/routes/web.php @@ -164,6 +164,7 @@ use App\Http\Middleware\SerializePushSessions; use App\Http\Middleware\SerializePushSubscriptions; use App\Http\Middleware\ThrottleCommits; +use App\Http\Middleware\ThrottleIssues; use App\Models\Profile; use Illuminate\Foundation\Http\Middleware\PreventRequestForgery; use Illuminate\Http\Request; @@ -369,7 +370,7 @@ Route::middleware('auth')->group(function (): void { Route::post('issues', [IssueController::class, 'store']) - ->middleware([PreventPostingInTimeout::class, 'throttle:10,1']) + ->middleware([PreventPostingInTimeout::class, 'throttle:10,1', ThrottleIssues::class]) ->name('issue.store'); // Session... diff --git a/tests/Feature/Controllers/Api/IssueControllerTest.php b/tests/Feature/Controllers/Api/IssueControllerTest.php new file mode 100644 index 0000000000..4cd8212e43 --- /dev/null +++ b/tests/Feature/Controllers/Api/IssueControllerTest.php @@ -0,0 +1,107 @@ +user = User::factory()->create(['handle' => 'taylor']); + $this->keyPair = apiKeyPairFor($this->user); +}); + +it('opens the issue as the app, crediting the reporter, with the label of the command and the environment', function (string $command, string $label): void { + $this->mock(GitHubProvider::class)->shouldReceive('createIssue') + ->once() + ->with('Search loses its filters', "Search loses its filters\n\nSteps: open search.\n\n
\nEnvironment\n\n| | |\n|---|---|\n| Os | `Linux` |\n| Viewport | `120x40` |\n\n
\n\n---\n\nReported by @taylor via [/dev/null](".route('user.show', $this->user).').', [$label]) + ->andReturn(['number' => 123, 'url' => 'https://github.com/dev-null-sh/dev-null.sh/issues/123']); + + signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), [ + 'command' => $command, + 'body' => "Search loses its filters\n\nSteps: open search.", + 'environment' => ['os' => 'Linux', 'viewport' => '120x40'], + ]) + ->assertCreated() + ->assertExactJson(['number' => 123, 'url' => 'https://github.com/dev-null-sh/dev-null.sh/issues/123']); +})->with([ + 'feature' => ['/feature', 'enhancement'], + 'bug' => ['/bug', 'bug'], +]); + +it('opens issues only for signed requests', function (): void { + $this->mock(GitHubProvider::class)->shouldNotReceive('createIssue'); + + $this->postJson(route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken.'])->assertUnauthorized(); +}); + +it('validates the command, the body and the environment as the web does', function (array $payload, string $field): void { + $this->mock(GitHubProvider::class)->shouldNotReceive('createIssue'); + + signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), $payload) + ->assertUnprocessable() + ->assertJsonValidationErrors($field); +})->with([ + 'unknown command' => [['command' => '/deploy', 'body' => 'Ship it.'], 'command'], + 'missing body' => [['command' => '/bug'], 'body'], + 'blank lines only' => [['command' => '/bug', 'body' => "a\n\n\n\n"], 'body'], + 'unknown environment field' => [['command' => '/bug', 'body' => 'Broken.', 'environment' => ['cookie' => 'secret']], 'environment'], +]); + +it('opens no issue for a user in timeout', function (): void { + $this->mock(GitHubProvider::class)->shouldNotReceive('createIssue'); + UserTimeout::factory()->for($this->user)->create(); + + signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken.']) + ->assertForbidden() + ->assertJsonPath('code', 'timed_out'); +}); + +it('keeps the draft with a code when GitHub rejects the issue or does not respond', function (Throwable $exception, string $code, string $message): void { + $this->mock(GitHubProvider::class)->shouldReceive('createIssue')->andThrow($exception); + + signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken.']) + ->assertStatus(502) + ->assertJsonPath('code', $code) + ->assertJsonPath('message', $message); +})->with([ + 'rejected' => [fn (): RequestException => new RequestException(new Response(new Psr7Response(422))), 'github_issue_refused', 'GitHub did not create the issue. Your draft is safe.'], + 'unavailable' => [fn (): ConnectionException => new ConnectionException('timeout'), 'github_issue_unanswered', 'GitHub did not respond. Check the upstream issues before trying again. Your draft is safe.'], +]); + +it('shares the limit of ten opened issues a day with the web, counting only opened ones', function (): void { + $github = $this->mock(GitHubProvider::class); + $github->shouldReceive('createIssue')->once()->andThrow(new ConnectionException('timeout')); + $github->shouldReceive('createIssue')->andReturn(['number' => 123, 'url' => 'https://github.com/dev-null-sh/dev-null.sh/issues/123']); + + signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken.'])->assertStatus(502); + signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/deploy', 'body' => 'Nope.'])->assertUnprocessable(); + + foreach (range(1, 5) as $attempt) { + $this->travel(1)->minute(); + $this->actingAs($this->user)->postJson(route('issue.store'), ['command' => '/bug', 'body' => "Broken {$attempt}."])->assertCreated(); + } + + foreach (range(6, 10) as $attempt) { + $this->travel(1)->minute(); + 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() + ->assertJsonPath('code', 'rate_limited') + ->assertJsonPath('message', 'Issue limit reached: 10 a day. Try again tomorrow.') + ->assertHeader('Retry-After', 86400 - 9 * 60); + + $this->actingAs($this->user)->postJson(route('issue.store'), ['command' => '/bug', 'body' => 'Broken again.']) + ->assertTooManyRequests() + ->assertExactJson(['message' => 'Issue limit reached: 10 a day. Try again tomorrow.']); + + $this->travel(1)->day(); + + signedApiRequest($this->keyPair, 'POST', route('api-issue.store'), ['command' => '/bug', 'body' => 'Broken later.'])->assertCreated(); +}); diff --git a/tests/Feature/Controllers/IssueControllerTest.php b/tests/Feature/Controllers/IssueControllerTest.php index 7883a2d967..d1c27dc95c 100644 --- a/tests/Feature/Controllers/IssueControllerTest.php +++ b/tests/Feature/Controllers/IssueControllerTest.php @@ -161,3 +161,20 @@ $this->actingAs($user)->postJson(route('issue.store'), ['command' => '/bug', 'body' => 'Broken.'])->assertCreated(); }); + +it('refuses any draft once the daily limit is reached, before validating it', function (): void { + $this->mock(GitHubProvider::class)->shouldReceive('createIssue')->andReturn([ + 'number' => 123, + 'url' => 'https://github.com/dev-null-sh/dev-null.sh/issues/123', + ]); + $user = User::factory()->create(); + + foreach (range(1, 10) as $attempt) { + $this->travel(1)->minute(); + $this->actingAs($user)->postJson(route('issue.store'), ['command' => '/bug', 'body' => "Broken {$attempt}."])->assertCreated(); + } + + $this->actingAs($user)->postJson(route('issue.store'), ['command' => '/deploy', 'body' => 'Nope.']) + ->assertTooManyRequests() + ->assertExactJson(['message' => 'Issue limit reached: 10 a day. Try again tomorrow.']); +});