diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index a3c033a43..374f5a30a 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -139,7 +139,7 @@ Every organization has a color, /dev/null's blue until an admin chooses another Signed in, you can **Follow** an organization from its page, which shows how many people follow it. Once you follow it, the button opens a menu where you can unfollow. Following puts the organization's own commits in your Following log, and ranks them higher in Trending, like the people you follow. **Watch**, which will also show the commits that mention the organization, is planned and shown as coming soon. The organizations you follow are listed on your Following list, above the people, a few at a time with **Show more organizations**, and count toward your following count. They are in your data export and go when you delete your account. -Sources: [organization page](resources/js/pages/organization/show.tsx), [commits](app/Queries/OrganizationCommitsQuery.php), [posting as an organization](app/Rules/OrganizationToPostAs.php), [mentions](app/Queries/OrganizationMentionsQuery.php), [organization lookups](app/Actions/UpdateCommitTopics.php), [claims](app/Http/Controllers/OrganizationAdminController.php), [color](app/Http/Controllers/OrganizationLaneController.php), [members](app/Http/Controllers/OrganizationMemberController.php). +Sources: [organization page](resources/js/pages/organization/show.tsx), [commits](app/Queries/OrganizationCommitsQuery.php), [posting as an organization](app/Rules/OrganizationToPostAs.php), [mentions](app/Queries/OrganizationMentionsQuery.php), [organization lookups](app/Actions/UpdateCommitTopics.php), [claims](app/Http/Controllers/OrganizationAdminController.php), [color](app/Http/Controllers/OrganizationLaneController.php), [members](app/Http/Controllers/OrganizationMemberController.php), [members in the API](app/Http/Controllers/Api/OrganizationMemberController.php). ### Developers not on /dev/null yet @@ -607,6 +607,7 @@ A signed request sees what the web shows you, such as your own pending commits a - create polls on commits that are neither replies nor quotes, and vote on polls; - change Remotes settings, read and send messages with images, link cards, and voice notes in conversations and orgs, mark them pulled, react to messages and list your reactions, pin and unpin org messages as a maintainer, find people, and start orgs; - rename orgs, add people to them, change their roles, remove them, and leave an org, with the same maintainer rules as the web; +- list your organizations' members, and as an admin add members, change their roles, remove them, or choose the organization's color; leave an organization, with the same last-admin rule as the web; - stash or reopen conversations and orgs, pin and mute them, merge or drop message requests, and send typing indicators; - switch Pastéis mode and give pastéis; - report commits; diff --git a/app/Http/Controllers/Api/OrganizationLaneController.php b/app/Http/Controllers/Api/OrganizationLaneController.php new file mode 100644 index 000000000..1ef85737f --- /dev/null +++ b/app/Http/Controllers/Api/OrganizationLaneController.php @@ -0,0 +1,23 @@ +organization(); + assert($organization instanceof Organization); + + $action->handle($organization, $request->lane(), $request->color()); + + return new OrganizationResource($organization); + } +} diff --git a/app/Http/Controllers/Api/OrganizationMemberController.php b/app/Http/Controllers/Api/OrganizationMemberController.php new file mode 100644 index 000000000..6194254ae --- /dev/null +++ b/app/Http/Controllers/Api/OrganizationMemberController.php @@ -0,0 +1,91 @@ +organization(); + assert($organization instanceof Organization); + + return OrganizationMemberResource::collection($members->get($organization)); + } + + public function store(CreateApiOrganizationMemberRequest $request, CreateOrganizationMember $action, OrganizationMembersQuery $members): JsonResponse + { + $organization = $request->organization(); + assert($organization instanceof Organization); + + $member = $request->member(); + assert($member instanceof User); + + $action->handle($organization, $member); + + return new OrganizationMemberResource($members->find($organization, $member))->response()->setStatusCode(201); + } + + public function update(UpdateApiOrganizationMemberRequest $request, string $handle, User $member, UpdateOrganizationMemberRole $action, OrganizationMembersQuery $members): OrganizationMemberResource|JsonResponse + { + $organization = $request->organization(); + assert($organization instanceof Organization); + + $role = $request->role(); + assert($role instanceof OrganizationRole); + + try { + $action->handle($organization, $member, $role); + } catch (OrganizationMustHaveAnAdmin $organizationMustHaveAnAdmin) { + return $this->refused('role', $organizationMustHaveAnAdmin); + } + + return new OrganizationMemberResource($members->find($organization, $member)); + } + + public function destroy(DeleteApiOrganizationMemberRequest $request, string $handle, User $member, DeleteOrganizationMember $action): Response|JsonResponse + { + $organization = $request->organization(); + assert($organization instanceof Organization); + + try { + $action->handle($organization, $member); + } catch (OrganizationMustHaveAnAdmin $organizationMustHaveAnAdmin) { + return $this->refused('member', $organizationMustHaveAnAdmin); + } + + return response()->noContent(); + } + + /** + * Another admin was made a member or left meanwhile: the same 422 the form request gives the last admin's change. + */ + private function refused(string $field, OrganizationMustHaveAnAdmin $exception): JsonResponse + { + return response()->json([ + 'message' => $exception->getMessage(), + 'errors' => [$field => [$exception->getMessage()]], + ], 422); + } +} diff --git a/app/Http/Controllers/OrganizationMemberController.php b/app/Http/Controllers/OrganizationMemberController.php index 28e363de0..da7083330 100644 --- a/app/Http/Controllers/OrganizationMemberController.php +++ b/app/Http/Controllers/OrganizationMemberController.php @@ -16,6 +16,7 @@ use App\Http\Requests\UpdateOrganizationMemberRequest; use App\Models\Organization; use App\Models\User; +use App\Queries\OrganizationMembersQuery; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Container\Attributes\CurrentUser; use Illuminate\Database\Eloquent\Collection; @@ -31,17 +32,13 @@ /** * Every member sees who the members are, first joined first. Only admins can change them. */ - public function index(ListOrganizationMembersRequest $request, #[CurrentUser] User $user, Organization $organization): Response + public function index(ListOrganizationMembersRequest $request, #[CurrentUser] User $user, Organization $organization, OrganizationMembersQuery $members): Response { return Inertia::render('organization-member/index', [ 'organization' => $organization, // Changed by another admin, the members and the user's own role read again, the form being filled in stays. 'role' => Inertia::live(fn (): ?OrganizationRole => $organization->roleOf($user), UserUpdate::Account->value, new PrivateChannel($user)), - 'members' => Inertia::live(fn (): Collection => $organization->members() - ->oldest('organization_members.created_at') - ->withCasts(['joined_at' => 'datetime']) - ->get(['users.*', 'organization_members.role', 'organization_members.created_at as joined_at']) - ->makeHidden('pivot'), UserUpdate::Account->value, new PrivateChannel($user)), + 'members' => Inertia::live(fn (): Collection => $members->get($organization), UserUpdate::Account->value, new PrivateChannel($user)), ]); } diff --git a/app/Http/Requests/CreateApiOrganizationMemberRequest.php b/app/Http/Requests/CreateApiOrganizationMemberRequest.php new file mode 100644 index 000000000..14702b5c4 --- /dev/null +++ b/app/Http/Requests/CreateApiOrganizationMemberRequest.php @@ -0,0 +1,93 @@ +user(); + assert($user instanceof User); + + $organization = $this->organization(); + + return match (true) { + ! $organization instanceof Organization || ! $organization->isMember($user) => Response::denyAsNotFound(), + ! $organization->isAdmin($user) => Response::deny('Only admins can add members.'), + default => Response::allow(), + }; + } + + /** + * @return array> + */ + public function rules(): array + { + return [ + 'handle' => ['required', 'string', 'max:40'], + ]; + } + + /** + * @return list + */ + public function after(): array + { + return [function (Validator $validator): void { + if ($validator->errors()->isNotEmpty()) { + return; + } + + $user = $this->user(); + assert($user instanceof User); + + $organization = $this->organization(); + assert($organization instanceof Organization); + + $member = $this->member(); + + if (! $member instanceof User) { + $validator->errors()->add('handle', "There's no @{$this->handle()} on /dev/null."); + } elseif ($user->hasBlockWith($member)) { + $validator->errors()->add('handle', "You can't add {$member->mention()}."); + } elseif ($organization->isMember($member)) { + $validator->errors()->add('handle', "{$member->mention()} is already a member."); + } + }]; + } + + public function organization(): ?Organization + { + $handle = $this->route('handle'); + assert(is_string($handle)); + + return $this->organization ??= Organization::query() + ->whereRelation('profile', 'handle', $handle) + ->first(); + } + + /** + * The user at the handle, with or without its "@", resolved like "@handle" URLs, whatever its case. + */ + public function member(): ?User + { + $member = (new User)->resolveRouteBinding($this->handle(), 'handle'); + + return $member instanceof User ? $member : null; + } + + private function handle(): string + { + return $this->string('handle')->trim()->ltrim('@')->value(); + } +} diff --git a/app/Http/Requests/DeleteApiOrganizationMemberRequest.php b/app/Http/Requests/DeleteApiOrganizationMemberRequest.php new file mode 100644 index 000000000..c132f3746 --- /dev/null +++ b/app/Http/Requests/DeleteApiOrganizationMemberRequest.php @@ -0,0 +1,77 @@ +user(); + assert($user instanceof User); + + $organization = $this->organization(); + + return match (true) { + ! $organization instanceof Organization || ! $organization->isMember($user) || ! $organization->isMember($this->member()) => Response::denyAsNotFound(), + ! $user->is($this->member()) && ! $organization->isAdmin($user) => Response::deny('Only admins can remove members.'), + default => Response::allow(), + }; + } + + /** + * @return array{} + */ + public function rules(): array + { + return []; + } + + /** + * @return list + */ + public function after(): array + { + return [function (Validator $validator): void { + $organization = $this->organization(); + assert($organization instanceof Organization); + + $isLastAdmin = $organization->isAdmin($this->member()) + && $organization->admins()->whereKeyNot($this->member()->id)->doesntExist(); + + if ($isLastAdmin) { + $validator->errors()->add('member', "@{$organization->handle} needs at least one admin."); + } + }]; + } + + public function organization(): ?Organization + { + $handle = $this->route('handle'); + assert(is_string($handle)); + + return $this->organization ??= Organization::query() + ->whereRelation('profile', 'handle', $handle) + ->first(); + } + + public function member(): User + { + $member = $this->route('member'); + assert($member instanceof User); + + return $member; + } +} diff --git a/app/Http/Requests/ListApiOrganizationMembersRequest.php b/app/Http/Requests/ListApiOrganizationMembersRequest.php new file mode 100644 index 000000000..6da30f593 --- /dev/null +++ b/app/Http/Requests/ListApiOrganizationMembersRequest.php @@ -0,0 +1,44 @@ +user(); + assert($user instanceof User); + + return $this->organization()?->isMember($user) === true ? Response::allow() : Response::denyAsNotFound(); + } + + /** + * @return array{} + */ + public function rules(): array + { + return []; + } + + public function organization(): ?Organization + { + $handle = $this->route('handle'); + assert(is_string($handle)); + + return $this->organization ??= Organization::query() + ->whereRelation('profile', 'handle', $handle) + ->first(); + } +} diff --git a/app/Http/Requests/UpdateApiOrganizationLaneRequest.php b/app/Http/Requests/UpdateApiOrganizationLaneRequest.php new file mode 100644 index 000000000..598f74bb0 --- /dev/null +++ b/app/Http/Requests/UpdateApiOrganizationLaneRequest.php @@ -0,0 +1,57 @@ +user(); + assert($user instanceof User); + + return $this->organization()?->isAdmin($user) === true ? Response::allow() : Response::denyAsNotFound(); + } + + /** + * @return array> + */ + public function rules(): array + { + return [ + 'lane' => ['present', 'nullable', 'integer', 'between:0,5'], + 'color' => ['nullable', 'string', 'regex:/^#[0-9a-f]{6}$/', 'prohibits:lane'], + ]; + } + + public function organization(): ?Organization + { + $handle = $this->route('handle'); + assert(is_string($handle)); + + return $this->organization ??= Organization::query() + ->whereRelation('profile', 'handle', $handle) + ->first(); + } + + public function lane(): ?int + { + return $this->filled('lane') ? $this->integer('lane') : null; + } + + public function color(): ?string + { + return $this->filled('color') ? $this->string('color')->toString() : null; + } +} diff --git a/app/Http/Requests/UpdateApiOrganizationMemberRequest.php b/app/Http/Requests/UpdateApiOrganizationMemberRequest.php new file mode 100644 index 000000000..c249dc7e8 --- /dev/null +++ b/app/Http/Requests/UpdateApiOrganizationMemberRequest.php @@ -0,0 +1,89 @@ +user(); + assert($user instanceof User); + + $organization = $this->organization(); + + return match (true) { + ! $organization instanceof Organization || ! $organization->isMember($user) || ! $organization->isMember($this->member()) => Response::denyAsNotFound(), + ! $organization->isAdmin($user) => Response::deny('Only admins can change roles.'), + $user->is($this->member()) && $this->role() === OrganizationRole::Admin => Response::deny("You're already an admin."), + default => Response::allow(), + }; + } + + /** + * @return array> + */ + public function rules(): array + { + return [ + 'role' => ['required', Rule::enum(OrganizationRole::class)], + ]; + } + + /** + * @return list + */ + public function after(): array + { + return [function (Validator $validator): void { + $organization = $this->organization(); + assert($organization instanceof Organization); + + if ($this->role() === OrganizationRole::Member && $organization->admins()->whereKeyNot($this->member()->id)->doesntExist()) { + $validator->errors()->add('role', "@{$organization->handle} needs at least one admin."); + } + }]; + } + + public function organization(): ?Organization + { + $handle = $this->route('handle'); + assert(is_string($handle)); + + return $this->organization ??= Organization::query() + ->whereRelation('profile', 'handle', $handle) + ->first(); + } + + public function member(): User + { + $member = $this->route('member'); + assert($member instanceof User); + + return $member; + } + + /** + * Null for anything but a string, which the enum rule then rejects, as authorization reads it before validation. + */ + public function role(): ?OrganizationRole + { + return is_string($this->input('role')) ? $this->enum('role', OrganizationRole::class) : null; + } +} diff --git a/app/Http/Requests/UpdateOrganizationMemberRequest.php b/app/Http/Requests/UpdateOrganizationMemberRequest.php index bc72d7d1b..8c7a5b9c8 100644 --- a/app/Http/Requests/UpdateOrganizationMemberRequest.php +++ b/app/Http/Requests/UpdateOrganizationMemberRequest.php @@ -70,8 +70,11 @@ public function member(): User return $member; } + /** + * Null for anything but a string, which the enum rule then rejects, as authorization reads it before validation. + */ public function role(): ?OrganizationRole { - return $this->enum('role', OrganizationRole::class); + return is_string($this->input('role')) ? $this->enum('role', OrganizationRole::class) : null; } } diff --git a/app/Http/Resources/OrganizationMemberResource.php b/app/Http/Resources/OrganizationMemberResource.php new file mode 100644 index 000000000..acae1737c --- /dev/null +++ b/app/Http/Resources/OrganizationMemberResource.php @@ -0,0 +1,33 @@ + + */ + public function toArray(Request $request): array + { + $joinedAt = $this->getAttribute('joined_at'); + assert($joinedAt instanceof CarbonInterface); + + return [ + ...new UserResource($this->resource)->toArray($request), + 'role' => $this->getAttribute('role'), + 'joined_at' => $joinedAt->toIso8601ZuluString(), + ]; + } +} diff --git a/app/Queries/OrganizationMembersQuery.php b/app/Queries/OrganizationMembersQuery.php new file mode 100644 index 000000000..89fab954b --- /dev/null +++ b/app/Queries/OrganizationMembersQuery.php @@ -0,0 +1,42 @@ + + */ + public function get(Organization $organization): Collection + { + return $this->builder($organization)->get()->makeHidden('pivot'); + } + + /** + * One member, read like the list reads them. A member removed meanwhile is a 404. + */ + public function find(Organization $organization, User $member): User + { + return $this->builder($organization)->whereKey($member->id)->firstOrFail()->makeHidden('pivot'); + } + + /** + * @return BelongsToMany + */ + private function builder(Organization $organization): BelongsToMany + { + return $organization->members() + ->select(['users.*', 'organization_members.role', 'organization_members.created_at as joined_at']) + ->withCasts(['joined_at' => 'datetime']) + ->oldest('organization_members.created_at'); + } +} diff --git a/routes/api.php b/routes/api.php index 9a0422ab6..f2d60b88d 100644 --- a/routes/api.php +++ b/routes/api.php @@ -54,6 +54,8 @@ use App\Http\Controllers\Api\OrganizationCommitController; use App\Http\Controllers\Api\OrganizationController; use App\Http\Controllers\Api\OrganizationFollowController; +use App\Http\Controllers\Api\OrganizationLaneController; +use App\Http\Controllers\Api\OrganizationMemberController; use App\Http\Controllers\Api\OrganizationMentionController; use App\Http\Controllers\Api\OrgArchiveController; use App\Http\Controllers\Api\OrgCallController; @@ -371,6 +373,17 @@ ->middleware('throttle:10,1,organization-claims:') ->name('api-organization-admin.store'); + // Organization Members: who belongs to it, and the roles its admins give them... + Route::get('organizations/{handle}/members', [OrganizationMemberController::class, 'index'])->name('api-organization-member.index'); + Route::post('organizations/{handle}/members', [OrganizationMemberController::class, 'store']) + ->middleware('throttle:30,1,organization-members:') + ->name('api-organization-member.store'); + Route::put('organizations/{handle}/members/{member:handle}', [OrganizationMemberController::class, 'update'])->name('api-organization-member.update'); + Route::delete('organizations/{handle}/members/{member:handle}', [OrganizationMemberController::class, 'destroy'])->name('api-organization-member.destroy'); + + // Organization Lane: the color its admins choose... + Route::put('organizations/{handle}/lane', [OrganizationLaneController::class, 'update'])->name('api-organization-lane.update'); + // Guild Membership: joining or leaving a guild, as the web's Join button does... Route::post('guilds/{guild:handle}/membership', [GuildMembershipController::class, 'store']) ->middleware('throttle:follows') diff --git a/tests/Feature/Controllers/Api/OrganizationLaneControllerTest.php b/tests/Feature/Controllers/Api/OrganizationLaneControllerTest.php new file mode 100644 index 000000000..80a12a569 --- /dev/null +++ b/tests/Feature/Controllers/Api/OrganizationLaneControllerTest.php @@ -0,0 +1,66 @@ +create(); + $organization = Organization::factory()->create(['handle' => 'laravel', ...$attributes]); + $organization->admins()->attach($user->id, ['created_at' => now()]); + + return [$user, $organization]; +} + +it('lets an admin choose the lane of the organization, and answers with it', function (array $input, ?int $lane, ?string $color): void { + [$user, $organization] = apiOrganizationAdmin(['preferred_lane' => 2, 'lane_color' => null]); + + signedApiRequest(apiKeyPairFor($user), 'PUT', route('api-organization-lane.update', 'laravel'), $input) + ->assertOk() + ->assertJsonPath('data.handle', 'laravel') + ->assertJsonPath('data.lane', $color ?? $lane); + + expect($organization->refresh()->preferred_lane)->toBe($lane) + ->and($organization->lane_color)->toBe($color); +})->with([ + 'from the palette' => [['lane' => 5], 5, null], + 'custom' => [['lane' => null, 'color' => '#1a2b3c'], null, '#1a2b3c'], + 'none' => [['lane' => null], null, null], +]); + +it('rejects lanes and colors outside what users may choose', function (array $input, string $error): void { + [$user, $organization] = apiOrganizationAdmin(['preferred_lane' => 2]); + + signedApiRequest(apiKeyPairFor($user), 'PUT', route('api-organization-lane.update', 'laravel'), $input) + ->assertUnprocessable() + ->assertJsonValidationErrors($error); + + expect($organization->refresh()->lane())->toBe(2); +})->with([ + 'outside the palette' => [['lane' => 6], 'lane'], + 'short hex' => [['lane' => null, 'color' => '#fff'], 'color'], + 'both' => [['lane' => 1, 'color' => '#1a2b3c'], 'color'], + 'missing lane' => [[], 'lane'], +]); + +it('hides the color from everyone but admins of the organization', function (): void { + [, $organization] = apiOrganizationAdmin(['preferred_lane' => 2]); + $member = User::factory()->create(); + $organization->members()->attach($member->id, ['role' => 'member', 'created_at' => now()]); + + signedApiRequest(apiKeyPairFor($member), 'PUT', route('api-organization-lane.update', 'laravel'), ['lane' => 1])->assertNotFound(); + signedApiRequest(apiKeyPairFor($member), 'PUT', route('api-organization-lane.update', $member->handle), ['lane' => 1])->assertNotFound(); + + expect($organization->refresh()->lane())->toBe(2); +}); + +it('requires a signed request', function (): void { + apiOrganizationAdmin(); + + $this->putJson(route('api-organization-lane.update', 'laravel'), ['lane' => 1])->assertUnauthorized(); +}); diff --git a/tests/Feature/Controllers/Api/OrganizationMemberControllerTest.php b/tests/Feature/Controllers/Api/OrganizationMemberControllerTest.php new file mode 100644 index 000000000..fbe81ae50 --- /dev/null +++ b/tests/Feature/Controllers/Api/OrganizationMemberControllerTest.php @@ -0,0 +1,251 @@ +create(['handle' => 'laravel']); + $admin = User::factory()->create(); + $member = User::factory()->create(); + $organization->admins()->attach($admin->id, ['created_at' => now()->subDay()]); + $organization->members()->attach($member->id, ['role' => OrganizationRole::Member, 'created_at' => now()]); + + return [$organization, $admin, $member]; +} + +/** + * @return array{handle: string, member: string} + */ +function apiMemberRoute(User $member): array +{ + return ['handle' => 'laravel', 'member' => $member->handle]; +} + +it('lists the members of the organization to its members, first joined first, with their roles', function (): void { + $this->freezeSecond(); + [, $admin, $member] = apiOrganizationWithAdminAndMember(); + + signedApiRequest(apiKeyPairFor($member), 'GET', route('api-organization-member.index', 'laravel')) + ->assertOk() + ->assertJsonCount(2, 'data') + ->assertJsonPath('data.0.handle', $admin->handle) + ->assertJsonPath('data.0.role', 'admin') + ->assertJsonPath('data.0.joined_at', now()->subDay()->toIso8601ZuluString()) + ->assertJsonPath('data.1.handle', $member->handle) + ->assertJsonPath('data.1.role', 'member') + ->assertJsonMissingPath('data.0.email') + ->assertJsonMissingPath('data.0.pivot'); +}); + +it('hides the members of the organization from everyone else', function (): void { + apiOrganizationWithAdminAndMember(); + $keyPair = apiKeyPairFor($user = User::factory()->create()); + + signedApiRequest($keyPair, 'GET', route('api-organization-member.index', 'laravel'))->assertNotFound(); + signedApiRequest($keyPair, 'GET', route('api-organization-member.index', $user->handle))->assertNotFound(); + signedApiRequest($keyPair, 'GET', route('api-organization-member.index', 'nobody'))->assertNotFound(); +}); + +it('lets admins add a member by their handle, whatever its case and with its @', function (): void { + [$organization, $admin] = apiOrganizationWithAdminAndMember(); + $user = User::factory()->create(); + + signedApiRequest(apiKeyPairFor($admin), 'POST', route('api-organization-member.store', 'laravel'), ['handle' => ' @'.mb_strtoupper($user->handle)]) + ->assertCreated() + ->assertJsonPath('data.handle', $user->handle) + ->assertJsonPath('data.role', 'member'); + + expect($organization->roleOf($user))->toBe(OrganizationRole::Member); +}); + +it('refuses to add someone who is not on /dev/null or already a member', function (string $handle, string $error): void { + [$organization, $admin, $member] = apiOrganizationWithAdminAndMember(); + + signedApiRequest(apiKeyPairFor($admin), 'POST', route('api-organization-member.store', 'laravel'), ['handle' => $handle === 'member' ? $member->handle : $handle]) + ->assertUnprocessable() + ->assertJsonValidationErrors(['handle' => str_replace('@member', "@{$member->handle}", $error)]); + + expect($organization->members()->count())->toBe(2); +})->with([ + 'empty' => ['', 'The handle field is required.'], + 'nobody' => ['nobody-here', "There's no @nobody-here on /dev/null."], + 'the organization' => ['laravel', "There's no @laravel on /dev/null."], + 'a member' => ['member', '@member is already a member.'], +]); + +it('refuses to add someone across a block, either way', function (): void { + [$organization, $admin] = apiOrganizationWithAdminAndMember(); + $blocked = User::factory()->create(); + $blocker = User::factory()->create(); + $admin->blocking()->attach($blocked->id); + $blocker->blocking()->attach($admin->id); + + foreach ([$blocked, $blocker] as $user) { + signedApiRequest(apiKeyPairFor($admin), 'POST', route('api-organization-member.store', 'laravel'), ['handle' => $user->handle]) + ->assertJsonValidationErrors(['handle' => "You can't add @{$user->handle}."]); + } + + expect($organization->members()->count())->toBe(2); +}); + +it('only lets admins add members', function (): void { + [$organization, , $member] = apiOrganizationWithAdminAndMember(); + $user = User::factory()->create(); + + signedApiRequest(apiKeyPairFor($member), 'POST', route('api-organization-member.store', 'laravel'), ['handle' => $user->handle])->assertForbidden(); + signedApiRequest(apiKeyPairFor($user), 'POST', route('api-organization-member.store', 'laravel'), ['handle' => $user->handle])->assertNotFound(); + signedApiRequest(apiKeyPairFor($user), 'POST', route('api-organization-member.store', 'nobody'), ['handle' => $user->handle])->assertNotFound(); + signedApiRequest(apiKeyPairFor($user), 'POST', route('api-organization-member.store', $user->handle), ['handle' => $user->handle])->assertNotFound(); + + expect($organization->roleOf($user))->toBeNull(); +}); + +it('shares the web’s 30 member adds a minute, apart from other limits', function (): void { + [$organization, $admin] = apiOrganizationWithAdminAndMember(); + $keyPair = apiKeyPairFor($admin); + $ownCommit = Commit::factory()->for($admin)->create(); + + foreach (range(1, 30) as $attempt) { + $this->actingAs($admin)->postJson(route('commit-pastel.store', $ownCommit))->assertForbidden(); + } + + foreach (range(1, 15) as $attempt) { + $this->postJson(route('organization-member.store', $organization), ['handle' => ''])->assertUnprocessable(); + signedApiRequest($keyPair, 'POST', route('api-organization-member.store', 'laravel'), ['handle' => ''])->assertUnprocessable(); + } + + signedApiRequest($keyPair, 'POST', route('api-organization-member.store', 'laravel'), ['handle' => '']) + ->assertTooManyRequests() + ->assertJsonPath('code', 'rate_limited'); +}); + +it('lets admins make a member an admin, and an admin a member again', function (): void { + [$organization, $admin, $member] = apiOrganizationWithAdminAndMember(); + + signedApiRequest(apiKeyPairFor($admin), 'PUT', route('api-organization-member.update', apiMemberRoute($member)), ['role' => 'admin']) + ->assertOk() + ->assertJsonPath('data.handle', $member->handle) + ->assertJsonPath('data.role', 'admin'); + + signedApiRequest(apiKeyPairFor($member), 'PUT', route('api-organization-member.update', apiMemberRoute($admin)), ['role' => 'member']) + ->assertOk() + ->assertJsonPath('data.role', 'member'); + + expect($organization->roleOf($member))->toBe(OrganizationRole::Admin) + ->and($organization->roleOf($admin))->toBe(OrganizationRole::Member); +}); + +it('keeps the last admin of the organization', function (): void { + [$organization, $admin] = apiOrganizationWithAdminAndMember(); + + signedApiRequest(apiKeyPairFor($admin), 'PUT', route('api-organization-member.update', apiMemberRoute($admin)), ['role' => 'member']) + ->assertJsonValidationErrors(['role' => '@laravel needs at least one admin.']); + + signedApiRequest(apiKeyPairFor($admin), 'DELETE', route('api-organization-member.destroy', apiMemberRoute($admin))) + ->assertJsonValidationErrors(['member' => '@laravel needs at least one admin.']); + + expect($organization->roleOf($admin))->toBe(OrganizationRole::Admin); +}); + +it('keeps the last admin when another admin was made a member after the request was allowed', function (): void { + [$organization, $admin, $member] = apiOrganizationWithAdminAndMember(); + $organization->members()->updateExistingPivot($member->id, ['role' => OrganizationRole::Admin]); + + app()->resolving(UpdateOrganizationMemberRole::class, fn () => $organization->members()->updateExistingPivot($admin->id, ['role' => OrganizationRole::Member])); + + signedApiRequest(apiKeyPairFor($admin), 'PUT', route('api-organization-member.update', apiMemberRoute($member)), ['role' => 'member']) + ->assertUnprocessable() + ->assertJsonValidationErrors(['role' => '@laravel needs at least one admin.']); + + expect($organization->roleOf($member))->toBe(OrganizationRole::Admin); +}); + +it('keeps the last admin when another admin left after the request was allowed', function (): void { + [$organization, $admin, $member] = apiOrganizationWithAdminAndMember(); + $organization->members()->updateExistingPivot($member->id, ['role' => OrganizationRole::Admin]); + + app()->resolving(DeleteOrganizationMember::class, fn () => $organization->members()->detach($member->id)); + + signedApiRequest(apiKeyPairFor($admin), 'DELETE', route('api-organization-member.destroy', apiMemberRoute($admin))) + ->assertUnprocessable() + ->assertJsonValidationErrors(['member' => '@laravel needs at least one admin.']); + + expect($organization->roleOf($admin))->toBe(OrganizationRole::Admin); +}); + +it('only lets admins change roles, of members', function (): void { + [$organization, $admin, $member] = apiOrganizationWithAdminAndMember(); + $user = User::factory()->create(); + + signedApiRequest(apiKeyPairFor($member), 'PUT', route('api-organization-member.update', apiMemberRoute($member)), ['role' => 'admin'])->assertForbidden(); + signedApiRequest(apiKeyPairFor($admin), 'PUT', route('api-organization-member.update', apiMemberRoute($user)), ['role' => 'admin'])->assertNotFound(); + signedApiRequest(apiKeyPairFor($admin), 'PUT', route('api-organization-member.update', ['handle' => 'nobody', 'member' => $member->handle]), ['role' => 'admin'])->assertNotFound(); + signedApiRequest(apiKeyPairFor($admin), 'PUT', route('api-organization-member.update', ['handle' => $admin->handle, 'member' => $member->handle]), ['role' => 'admin'])->assertNotFound(); + signedApiRequest(apiKeyPairFor($admin), 'PUT', route('api-organization-member.update', apiMemberRoute($member)), ['role' => 'owner'])->assertJsonValidationErrors('role'); + signedApiRequest(apiKeyPairFor($admin), 'PUT', route('api-organization-member.update', apiMemberRoute($member)), ['role' => ['admin']])->assertJsonValidationErrors('role'); + signedApiRequest(apiKeyPairFor($admin), 'PUT', route('api-organization-member.update', apiMemberRoute($admin)), ['role' => ['member']])->assertJsonValidationErrors('role'); + + expect($organization->roleOf($member))->toBe(OrganizationRole::Member) + ->and($organization->roleOf($user))->toBeNull(); +}); + +it('never lets admins make themselves admins, which would undo another admin making them a member meanwhile', function (): void { + [$organization, $admin] = apiOrganizationWithAdminAndMember(); + + signedApiRequest(apiKeyPairFor($admin), 'PUT', route('api-organization-member.update', apiMemberRoute($admin)), ['role' => 'admin'])->assertForbidden(); + + expect($organization->roleOf($admin))->toBe(OrganizationRole::Admin); +}); + +it('lets admins remove members, and members leave', function (): void { + [$organization, $admin, $member] = apiOrganizationWithAdminAndMember(); + $other = User::factory()->create(); + $organization->members()->attach($other->id, ['role' => OrganizationRole::Member, 'created_at' => now()]); + + signedApiRequest(apiKeyPairFor($admin), 'DELETE', route('api-organization-member.destroy', apiMemberRoute($member)))->assertNoContent(); + signedApiRequest(apiKeyPairFor($other), 'DELETE', route('api-organization-member.destroy', apiMemberRoute($other)))->assertNoContent(); + + expect($organization->roleOf($member))->toBeNull() + ->and($organization->roleOf($other))->toBeNull() + ->and($organization->roleOf($admin))->toBe(OrganizationRole::Admin); +}); + +it('lets an admin leave while another one stays', function (): void { + [$organization, $admin, $member] = apiOrganizationWithAdminAndMember(); + $organization->members()->updateExistingPivot($member->id, ['role' => OrganizationRole::Admin]); + + signedApiRequest(apiKeyPairFor($admin), 'DELETE', route('api-organization-member.destroy', apiMemberRoute($admin)))->assertNoContent(); + + expect($organization->roleOf($admin))->toBeNull(); +}); + +it('only lets admins remove someone else', function (): void { + [$organization, $admin, $member] = apiOrganizationWithAdminAndMember(); + $user = User::factory()->create(); + + signedApiRequest(apiKeyPairFor($member), 'DELETE', route('api-organization-member.destroy', apiMemberRoute($admin)))->assertForbidden(); + signedApiRequest(apiKeyPairFor($user), 'DELETE', route('api-organization-member.destroy', apiMemberRoute($member)))->assertNotFound(); + signedApiRequest(apiKeyPairFor($admin), 'DELETE', route('api-organization-member.destroy', ['handle' => 'nobody', 'member' => $member->handle]))->assertNotFound(); + signedApiRequest(apiKeyPairFor($admin), 'DELETE', route('api-organization-member.destroy', ['handle' => $admin->handle, 'member' => $member->handle]))->assertNotFound(); + + expect($organization->members()->count())->toBe(2); +}); + +it('requires a signed request', function (): void { + [, , $member] = apiOrganizationWithAdminAndMember(); + + $this->getJson(route('api-organization-member.index', 'laravel'))->assertUnauthorized(); + $this->postJson(route('api-organization-member.store', 'laravel'), ['handle' => 'someone'])->assertUnauthorized(); + $this->putJson(route('api-organization-member.update', apiMemberRoute($member)), ['role' => 'admin'])->assertUnauthorized(); + $this->deleteJson(route('api-organization-member.destroy', apiMemberRoute($member)))->assertUnauthorized(); +}); diff --git a/tests/Feature/Controllers/OrganizationMemberControllerTest.php b/tests/Feature/Controllers/OrganizationMemberControllerTest.php index b0e37fb21..595722636 100644 --- a/tests/Feature/Controllers/OrganizationMemberControllerTest.php +++ b/tests/Feature/Controllers/OrganizationMemberControllerTest.php @@ -191,6 +191,8 @@ function memberRoute(Organization $organization, User $member): array $this->actingAs($member)->put(route('organization-member.update', memberRoute($organization, $member)), ['role' => 'admin'])->assertForbidden(); $this->actingAs($admin)->put(route('organization-member.update', memberRoute($organization, $user)), ['role' => 'admin'])->assertNotFound(); $this->actingAs($admin)->put(route('organization-member.update', memberRoute($organization, $member)), ['role' => 'owner'])->assertSessionHasErrors('role'); + $this->actingAs($admin)->put(route('organization-member.update', memberRoute($organization, $member)), ['role' => ['admin']])->assertSessionHasErrors('role'); + $this->actingAs($admin)->put(route('organization-member.update', memberRoute($organization, $admin)), ['role' => ['member']])->assertSessionHasErrors('role'); expect($organization->roleOf($member))->toBe(OrganizationRole::Member) ->and($organization->roleOf($user))->toBeNull();