Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions KNOWLEDGE_BASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,7 @@ A signed request sees what the web shows you, such as your own pending commits a
- read a guild's board as its page does, 30 threads a page with reply previews, with the guild, its pinned commit and whether you moderate it, while guilds are available to you. The pinned commit also keeps its place in the list, so an app that shows it apart skips it there by its id;
- list a guild's members as its members page does, the moderator first and then the newest joins, 50 a page, with whether you follow each one and whether each one follows you, and the moderator's id, while guilds are available to you;
- create a guild, or claim a paused one, as the Guilds page does, with the same rules and limit of 100, where a guild the moderation flags waits for an admin's review instead, while guilds are available to you;
- edit the display name, description, emoji and icon of a guild you moderate, as Edit guild does, where an edit the moderation flags waits for an admin's review and the guild stays as it was, while guilds are available to you;
- join or leave a guild, where joining clears your mute of it, as the Join button does, while guilds are available to you;
- report a guild you don't moderate to the admins, privately, as the Report button does, where reporting it again keeps your first report until an admin dismisses it, while guilds are available to you;
- mute or unmute a guild, which hides its commits from logs and search, Following included, even while you stay a member, while guilds are available to you;
Expand Down
25 changes: 25 additions & 0 deletions app/Http/Controllers/Api/GuildController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
namespace App\Http\Controllers\Api;

use App\Actions\CreateGuild;
use App\Actions\UpdateGuild;
use App\Exceptions\GuildModeratorRemoved;
use App\Http\Requests\CreateApiGuildRequest;
use App\Http\Requests\CreateGuildRequest;
use App\Http\Requests\ListApiGuildsRequest;
use App\Http\Requests\ShowApiGuildRequest;
use App\Http\Requests\UpdateApiGuildRequest;
use App\Http\Resources\CommitResource;
use App\Http\Resources\GuildResource;
use App\Models\Commit;
Expand All @@ -23,6 +25,7 @@
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\UploadedFile;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

final readonly class GuildController
{
Expand Down Expand Up @@ -82,6 +85,28 @@ public function show(ShowApiGuildRequest $request, Guild $guild, #[CurrentUser]
]);
}

/**
* Edits the guild's display name, description, emoji and icon, as the web does. An edit the moderation flags waits
* for an admin instead, so it answers 202 with the web's message, and the guild stays as it was.
*/
public function update(UpdateApiGuildRequest $request, Guild $guild, #[CurrentUser] User $user, UpdateGuild $action, GuildsQuery $guilds): JsonResponse
{
$icon = $request->file('images.0');
assert($icon instanceof UploadedFile || $icon === null);

try {
$action->handle($guild, $user, $request->string('name')->value(), $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->boolean('remove_icon'), $request->isFlagged());
} catch (GuildModeratorRemoved) {
throw new NotFoundHttpException;
}

if ($request->isFlagged()) {
return response()->json(['message' => 'Your changes are waiting for review. They go live once an admin approves them.'], 202);
}

return GuildResource::make($guilds->find($guild, $user))->response();
}

/**
* A race lost after validation, answered as the validation would have answered it.
*/
Expand Down
60 changes: 60 additions & 0 deletions app/Http/Requests/UpdateApiGuildRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Enums\Feature;
use App\Models\Guild;
use App\Rules\FlaggedGuild;
use App\Services\EmojiShortcodes;
use App\Services\Features;
use Closure;
use Illuminate\Auth\Access\Response;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\UploadedFile;
use Illuminate\Validation\Rules\In;
use Illuminate\Validation\Validator;

final class UpdateApiGuildRequest extends FormRequest
{
private bool $isFlagged = false;

public function authorize(Features $features): Response
{
$guild = $this->route('guild');
assert($guild instanceof Guild);

return $features->available(Feature::Guilds, $this->user()) && $guild->user_id === $this->user()?->id
? Response::allow() : Response::denyAsNotFound();
}

/** @return array<string, list<string|In>> */
public function rules(EmojiShortcodes $emoji): array
{
return UpdateGuildRequest::guildRules($emoji);
}

/** @return list<Closure(Validator): void> */
public function after(FlaggedGuild $flagged): array
{
return [function (Validator $validator) use ($flagged): void {
if ($validator->errors()->isNotEmpty()) {
return;
}

$guild = $this->route('guild');
assert($guild instanceof Guild);
$icon = $this->file('images.0');
$this->isFlagged = UpdateGuildRequest::validateEdit($validator, $flagged, $guild, $this->string('name')->value(), $this->string('description')->value(), $icon instanceof UploadedFile ? $icon : null);
}];
}

/**
* Whether the moderation flagged the edit, so it waits for an admin instead of being published.
*/
public function isFlagged(): bool
{
return $this->isFlagged;
}
}
50 changes: 34 additions & 16 deletions app/Http/Requests/UpdateGuildRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,38 @@ final class UpdateGuildRequest extends FormRequest
{
private bool $isFlagged = false;

/**
* The rules a guild edit follows, wherever it's made.
*
* @return array<string, list<string|In>>
*/
public static function guildRules(EmojiShortcodes $emoji): array
{
return [
'name' => ['required', 'string', 'max:60'],
'description' => ['required', 'string', 'max:500'],
'emoji' => ['required', 'string', Rule::in($emoji->emoji())],
'images' => ['nullable', 'list', 'max:1'],
'images.*' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048', 'dimensions:max_width=6000,max_height=6000'],
'remove_icon' => ['required', 'boolean'],
];
}

/**
* Refuses a name that doesn't match the guild's hashtag. An edit that passes is moderated, and the answer says
* whether the moderation flagged it.
*/
public static function validateEdit(Validator $validator, FlaggedGuild $flagged, Guild $guild, string $name, string $description, ?UploadedFile $icon): bool
{
if (CreateGuildRequest::hashtagOf($name) !== $guild->handle) {
$validator->errors()->add('name', "Guild display name doesn't match hashtag");

return false;
}

return $flagged->validate($validator, $name."\n\n".$description, $icon);
}

public function authorize(Features $features): Response
{
$guild = $this->route('guild');
Expand All @@ -33,14 +65,7 @@ public function authorize(Features $features): Response
/** @return array<string, list<string|In>> */
public function rules(EmojiShortcodes $emoji): array
{
return [
'name' => ['required', 'string', 'max:60'],
'description' => ['required', 'string', 'max:500'],
'emoji' => ['required', 'string', Rule::in($emoji->emoji())],
'images' => ['nullable', 'list', 'max:1'],
'images.*' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048', 'dimensions:max_width=6000,max_height=6000'],
'remove_icon' => ['required', 'boolean'],
];
return self::guildRules($emoji);
}

/** @return list<Closure(Validator): void> */
Expand All @@ -53,15 +78,8 @@ public function after(FlaggedGuild $flagged): array

$guild = $this->route('guild');
assert($guild instanceof Guild);

if ($this->string('name')->replaceMatches('/[^\p{L}\p{M}\p{N}_]+/u', '')->lower()->value() !== $guild->handle) {
$validator->errors()->add('name', "Guild display name doesn't match hashtag");

return;
}

$icon = $this->file('images.0');
$this->isFlagged = $flagged->validate($validator, $this->string('name')->value()."\n\n".$this->string('description')->value(), $icon instanceof UploadedFile ? $icon : null);
$this->isFlagged = self::validateEdit($validator, $flagged, $guild, $this->string('name')->value(), $this->string('description')->value(), $icon instanceof UploadedFile ? $icon : null);
}];
}

Expand Down
3 changes: 3 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,9 @@
->middleware([PreventPostingInTimeout::class, 'throttle:10,1,guilds:'])
->name('api-guild.store');
Route::get('guilds/{guild:handle}', [GuildController::class, 'show'])->name('api-guild.show');
Route::put('guilds/{guild:handle}', [GuildController::class, 'update'])
Comment thread
WendellAdriel marked this conversation as resolved.
Resolved
->middleware([PreventPostingInTimeout::class, 'throttle:10,1,guilds:'])
->name('api-guild.update');
Route::get('guilds/{guild:handle}/members', [GuildMembershipController::class, 'index'])->name('api-guild-membership.index');

// Composer suggestions: people to mention and /dev/null issues to reference, as the web's composer suggests them...
Expand Down
102 changes: 102 additions & 0 deletions tests/Feature/Controllers/Api/GuildControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
declare(strict_types=1);

use App\Actions\CreateGuild;
use App\Actions\UpdateGuild;
use App\Actions\UpdateGuildMembership;
use App\Actions\UpdateGuildMute;
use App\Contracts\Services\ModerationProvider;
Expand Down Expand Up @@ -384,3 +385,104 @@

signedApiRequest($this->keyPair, 'POST', route('api-guild.store'), ['name' => 'Jobs', 'description' => 'Hiring.', 'emoji' => '💼'])->assertTooManyRequests();
});

it('edits the display name, description, emoji and icon of a guild the user moderates', function (): void {
Storage::fake();
$guild = Guild::factory()->create(['user_id' => $this->user->id, 'handle' => 'jobs', 'name' => 'Jobs', 'icon_path' => null]);

signedApiRequestWithImages($this->keyPair, 'PUT', route('api-guild.update', 'jobs'), [
'name' => 'J.O.B.S', 'description' => 'Remote jobs.', 'emoji' => '🌍', 'remove_icon' => false, 'handle' => 'changed',
], [UploadedFile::fake()->image('icon.png', 80, 60)])
->assertOk()
->assertJsonPath('data.handle', 'jobs')
->assertJsonPath('data.name', 'J.O.B.S')
->assertJsonPath('data.description', 'Remote jobs.')
->assertJsonPath('data.emoji', '🌍');

$icon = $guild->fresh()->icon_path;
expect($icon)->toEndWith('.webp')->and($guild->fresh()->user_id)->toBe($this->user->id);
Storage::assertExists($icon);

signedApiRequest($this->keyPair, 'PUT', route('api-guild.update', 'jobs'), ['name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '🌍', 'remove_icon' => true])
->assertOk()->assertJsonPath('data.icon_url', null);

expect($guild->fresh()->icon_path)->toBeNull();
Storage::assertMissing($icon);
});

it('holds a flagged edit for review and keeps the guild as it was', function (): void {
$guild = Guild::factory()->create(['user_id' => $this->user->id, 'handle' => 'jobs', 'name' => 'Jobs', 'description' => 'Hiring.']);
$moderation = $this->mock(ModerationProvider::class);
$moderation->shouldReceive('moderate')->andReturn(['harassment' => 0.7]);
$moderation->shouldReceive('isHarmful')->andReturn(false);

signedApiRequest($this->keyPair, 'PUT', route('api-guild.update', 'jobs'), ['name' => 'JOBS', 'description' => 'Flagged words.', 'emoji' => '💼', 'remove_icon' => false])
->assertAccepted()
->assertExactJson(['message' => 'Your changes are waiting for review. They go live once an admin approves them.']);

expect($guild->fresh())->name->toBe('Jobs')->description->toBe('Hiring.')
->and(GuildSubmission::query()->sole())->name->toBe('JOBS')->user_id->toBe($this->user->id);
});

it('rejects invalid guild edits without changing the guild', function (array $payload, string $field): void {
$guild = Guild::factory()->create(['user_id' => $this->user->id, 'handle' => 'jobs', 'name' => 'Jobs', 'description' => 'Hiring.']);

signedApiRequest($this->keyPair, 'PUT', route('api-guild.update', 'jobs'), ['name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '💼', 'remove_icon' => false, ...$payload])
->assertUnprocessable()->assertJsonValidationErrors($field);

expect($guild->fresh()->description)->toBe('Hiring.');
})->with([
'name for another hashtag' => [['name' => 'Job Board'], 'name'],
'missing description' => [['description' => ''], 'description'],
'unknown emoji' => [['emoji' => 'invalid'], 'emoji'],
'missing remove_icon' => [['remove_icon' => null], 'remove_icon'],
]);

it('does not edit a guild the user does not moderate or while guilds are not available to the user', function (bool $moderates, bool $adminOnly): void {
$guild = Guild::factory()->create(['user_id' => $moderates ? $this->user->id : User::factory(), 'handle' => 'jobs', 'name' => 'Jobs', 'description' => 'Hiring.']);
resolve(Features::class)->update(Feature::Guilds, true, adminOnly: $adminOnly);

signedApiRequest($this->keyPair, 'PUT', route('api-guild.update', 'jobs'), ['name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '💼', 'remove_icon' => false])->assertNotFound();

expect($guild->fresh()->description)->toBe('Hiring.');
})->with([
'another moderator' => [false, false],
'admin-only guilds' => [true, true],
]);

it('does not edit a guild when its moderator is removed after validation', function (): void {
$guild = Guild::factory()->create(['user_id' => $this->user->id, 'handle' => 'jobs', 'name' => 'Jobs', 'description' => 'Hiring.']);
$this->app->beforeResolving(UpdateGuild::class, function () use ($guild): void {
Guild::query()->whereKey($guild->id)->update(['user_id' => null]);
});

signedApiRequest($this->keyPair, 'PUT', route('api-guild.update', 'jobs'), ['name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '💼', 'remove_icon' => false])->assertNotFound();

expect($guild->fresh())->description->toBe('Hiring.')->user_id->toBeNull();
});

it('requires a signed request to edit a guild', function (): void {
Guild::factory()->create(['user_id' => $this->user->id, 'handle' => 'jobs']);

$this->putJson(route('api-guild.update', 'jobs'), ['name' => 'Jobs', 'description' => 'Hiring.', 'emoji' => '💼', 'remove_icon' => false])->assertUnauthorized();
});

it('refuses to edit a guild while the user is in timeout', function (): void {
$guild = Guild::factory()->create(['user_id' => $this->user->id, 'handle' => 'jobs', 'name' => 'Jobs', 'description' => 'Hiring.']);
UserTimeout::factory()->for($this->user)->create();

signedApiRequest($this->keyPair, 'PUT', route('api-guild.update', 'jobs'), ['name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '💼', 'remove_icon' => false])
->assertForbidden()->assertJsonPath('code', 'timed_out');

expect($guild->fresh()->description)->toBe('Hiring.');
});

it('counts guild edits and creations against the same limit', function (): void {
Guild::factory()->create(['user_id' => $this->user->id, 'handle' => 'jobs', 'name' => 'Jobs']);

foreach (range(1, 10) as $attempt) {
signedApiRequest($this->keyPair, 'POST', route('api-guild.store'), ['name' => 'Go', 'description' => '', 'emoji' => '💼'])->assertUnprocessable();
}

signedApiRequest($this->keyPair, 'PUT', route('api-guild.update', 'jobs'), ['name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '💼', 'remove_icon' => false])->assertTooManyRequests();
});
Loading