Close anonymous write access to the public API and repair the broken test suite
Deploy Backend / deploy (push) Has been cancelled
Deploy Backend / deploy (push) Has been cancelled
Every mutating endpoint was reachable without authentication, so any visitor
could create, edit or delete posts, categories, tags, projects and about-me
records on the live site.
Security
- Split routes into an anonymous read-only group and a write group gated by
`auth:sanctum` + a new `admin` middleware.
- Add `is_admin` to users; Sanctum token support on the User model.
- Add AuthController (login / me / logout). The Sanctum token is delivered in
an httpOnly cookie and never returned in the JSON body, because the admin
panel reaches the API through a Next.js server-side proxy that breaks
Sanctum's first-party domain detection.
- AuthenticateAdminPanelSession promotes that cookie to a bearer header so
Sanctum's normal validation, expiry and revocation still apply.
- Remove the unauthenticated `/user/{id}` route, which exposed user emails.
- Non-admin accounts are refused at login and the failure shape is identical
to a bad password, so the endpoint cannot enumerate accounts.
- Fix `Route [login] not defined`: a non-JSON unauthenticated request resolved
a route that does not exist in this API-only app and returned 500.
- Reject invalid list query parameters with 422 instead of 500, and cap
per_page at 50 (`?per_page=100000` previously dumped whole tables).
Correctness
- Make the translation migration portable. It used MySQL-only JSON_OBJECTAGG,
which aborted all 29 tests during migration; the data collapse now runs in
PHP so it works on MySQL, MariaDB and SQLite.
- Add HasJsonTranslations trait providing the missing setTranslation(), which
made project create/update return 500, and replace five copy-pasted
getTranslation()/hasTranslation() bodies.
- Make posts.excerpt nullable to match StorePostRequest; omitting an excerpt
was a guaranteed SQL integrity error.
- Route the AboutMeController CRUD methods that existed but were never
registered.
- CategoryTest omitted a required description; fixed the test, the existing
schema and validation already agreed.
Tests: 83 passing / 126 assertions (was 29 failing / 0 assertions)
This commit is contained in:
1 parent
35686d82c3
commit
d2f6bd4d7d
29 files changed
+1002
-188
No files matched your search
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Controllers\Api\AuthController;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Regression coverage for the authorisation hole where every mutating endpoint
|
||||
* on the public API was anonymous, letting any visitor rewrite the whole site.
|
||||
*/
|
||||
class AdminAuthorisationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* @return array<string, array{0: string, 1: string}>
|
||||
*/
|
||||
public static function mutatingRouteProvider(): array
|
||||
{
|
||||
return [
|
||||
'create about me' => ['POST', '/api/website/about-me'],
|
||||
'update about me' => ['PUT', '/api/website/about-me/1'],
|
||||
'delete about me' => ['DELETE', '/api/website/about-me/1'],
|
||||
|
||||
'create project' => ['POST', '/api/website/projects'],
|
||||
'update project' => ['PUT', '/api/website/projects/1'],
|
||||
'delete project' => ['DELETE', '/api/website/projects/1'],
|
||||
|
||||
'create post' => ['POST', '/api/blog/posts'],
|
||||
'update post' => ['PUT', '/api/blog/posts/1'],
|
||||
'delete post' => ['DELETE', '/api/blog/posts/1'],
|
||||
|
||||
'create category' => ['POST', '/api/blog/categories'],
|
||||
'update category' => ['PUT', '/api/blog/categories/1'],
|
||||
'delete category' => ['DELETE', '/api/blog/categories/1'],
|
||||
|
||||
'create tag' => ['POST', '/api/blog/tags'],
|
||||
'update tag' => ['PUT', '/api/blog/tags/1'],
|
||||
'delete tag' => ['DELETE', '/api/blog/tags/1'],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('mutatingRouteProvider')]
|
||||
public function test_anonymous_requests_cannot_reach_write_endpoints(string $method, string $uri): void
|
||||
{
|
||||
$this->call($method, $uri)->assertUnauthorized();
|
||||
}
|
||||
|
||||
#[DataProvider('mutatingRouteProvider')]
|
||||
public function test_authenticated_non_admins_cannot_reach_write_endpoints(string $method, string $uri): void
|
||||
{
|
||||
Sanctum::actingAs(User::factory()->create());
|
||||
|
||||
$this->call($method, $uri)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_public_reads_remain_available_anonymously(): void
|
||||
{
|
||||
$this->getJson('/api/website/about-me')->assertOk();
|
||||
$this->getJson('/api/website/services/fa')->assertOk();
|
||||
$this->getJson('/api/blog/posts')->assertOk();
|
||||
$this->getJson('/api/blog/categories')->assertOk();
|
||||
$this->getJson('/api/blog/tags')->assertOk();
|
||||
}
|
||||
|
||||
public function test_user_email_endpoint_is_no_longer_public(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->getJson("/user/{$user->id}")->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_admin_can_log_in_and_receives_a_session_cookie(): void
|
||||
{
|
||||
$admin = User::factory()->admin()->create([
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'correct-horse-battery',
|
||||
]);
|
||||
|
||||
$response = $this->postJson('/api/auth/login', [
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'correct-horse-battery',
|
||||
]);
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('user.email', 'admin@parsaaghayi.ir')
|
||||
->assertCookie(AuthController::SESSION_COOKIE);
|
||||
|
||||
// The token must never be readable by client-side JavaScript.
|
||||
$cookie = $response->headers->getCookies()[0] ?? null;
|
||||
$this->assertNotNull($cookie);
|
||||
$this->assertTrue($cookie->isHttpOnly());
|
||||
$this->assertArrayNotHasKey('token', $response->json());
|
||||
|
||||
$this->assertSame(1, $admin->tokens()->count());
|
||||
}
|
||||
|
||||
public function test_login_rejects_a_valid_non_admin_account(): void
|
||||
{
|
||||
User::factory()->create([
|
||||
'email' => 'user@parsaaghayi.ir',
|
||||
'password' => 'correct-horse-battery',
|
||||
]);
|
||||
|
||||
$this->postJson('/api/auth/login', [
|
||||
'email' => 'user@parsaaghayi.ir',
|
||||
'password' => 'correct-horse-battery',
|
||||
])->assertUnprocessable();
|
||||
|
||||
$this->assertDatabaseCount('personal_access_tokens', 0);
|
||||
}
|
||||
|
||||
public function test_login_rejects_a_bad_password_without_revealing_which_field_failed(): void
|
||||
{
|
||||
User::factory()->admin()->create([
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'correct-horse-battery',
|
||||
]);
|
||||
|
||||
$wrongPassword = $this->postJson('/api/auth/login', [
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'wrong-password',
|
||||
]);
|
||||
|
||||
$unknownAccount = $this->postJson('/api/auth/login', [
|
||||
'email' => 'nobody@parsaaghayi.ir',
|
||||
'password' => 'wrong-password',
|
||||
]);
|
||||
|
||||
$wrongPassword->assertUnprocessable();
|
||||
$unknownAccount->assertUnprocessable();
|
||||
|
||||
// Identical error shape, so the endpoint cannot be used to enumerate
|
||||
// which email addresses have accounts.
|
||||
$this->assertSame(
|
||||
array_keys($wrongPassword->json('errors')),
|
||||
array_keys($unknownAccount->json('errors'))
|
||||
);
|
||||
}
|
||||
|
||||
public function test_auth_me_requires_authentication(): void
|
||||
{
|
||||
$this->getJson('/api/auth/me')->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_session_cookie_authenticates_requests(): void
|
||||
{
|
||||
User::factory()->admin()->create([
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'password',
|
||||
]);
|
||||
|
||||
$login = $this->postJson('/api/auth/login', [
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'password',
|
||||
]);
|
||||
|
||||
$token = $login->headers->getCookies()[0]->getValue();
|
||||
|
||||
// No Authorization header: the cookie alone must authenticate, which is
|
||||
// how the Next.js proxy will call the API.
|
||||
$this->withCookie(AuthController::SESSION_COOKIE, $token)
|
||||
->getJson('/api/auth/me')
|
||||
->assertOk()
|
||||
->assertJsonPath('user.is_admin', true);
|
||||
}
|
||||
|
||||
public function test_logout_revokes_the_admin_panel_token(): void
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$this->postJson('/api/auth/logout')->assertOk();
|
||||
|
||||
$this->assertDatabaseCount('personal_access_tokens', 0);
|
||||
}
|
||||
}
|
||||
@@ -40,9 +40,12 @@ class CategoryTest extends TestCase
|
||||
|
||||
public function test_can_create_category()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$response = $this->postJson('/api/blog/categories', [
|
||||
'name' => 'Tech',
|
||||
'slug' => 'tech',
|
||||
'description' => 'Everything related to software engineering.',
|
||||
]);
|
||||
|
||||
$response->assertStatus(201);
|
||||
@@ -51,6 +54,8 @@ class CategoryTest extends TestCase
|
||||
|
||||
public function test_can_delete_category()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$category = Category::factory()->create();
|
||||
|
||||
$response = $this->deleteJson("/api/blog/categories/{$category->id}");
|
||||
|
||||
@@ -4,7 +4,6 @@ namespace Tests\Feature\Blog;
|
||||
|
||||
use App\Models\Blog\Category;
|
||||
use App\Models\Blog\Post;
|
||||
use App\Models\Blog\Tag;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
@@ -34,6 +33,8 @@ class PostTest extends TestCase
|
||||
|
||||
public function test_can_create_post()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$category = Category::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
@@ -51,6 +52,8 @@ class PostTest extends TestCase
|
||||
|
||||
public function test_can_update_post()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$post = Post::factory()->create();
|
||||
|
||||
$response = $this->putJson("/api/blog/posts/{$post->id}", [
|
||||
@@ -62,6 +65,8 @@ class PostTest extends TestCase
|
||||
|
||||
public function test_can_delete_post()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$post = Post::factory()->create();
|
||||
|
||||
$response = $this->deleteJson("/api/blog/posts/{$post->id}");
|
||||
|
||||
@@ -30,6 +30,8 @@ class TagTest extends TestCase
|
||||
|
||||
public function test_can_create_tag()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$response = $this->postJson('/api/blog/tags', [
|
||||
'name' => 'Laravel',
|
||||
'slug' => 'laravel',
|
||||
@@ -41,6 +43,8 @@ class TagTest extends TestCase
|
||||
|
||||
public function test_can_delete_tag()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$tag = Tag::factory()->create();
|
||||
|
||||
$response = $this->deleteJson("/api/blog/tags/{$tag->id}");
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Blog\Category;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* The list endpoints previously forwarded raw request input into
|
||||
* `orderBy()` and `paginate()`, so a bad query string produced an HTTP 500
|
||||
* and `per_page` was unbounded.
|
||||
*/
|
||||
class ListQueryValidationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* @return array<string, array{0: string}>
|
||||
*/
|
||||
public static function badQueryProvider(): array
|
||||
{
|
||||
return [
|
||||
'categories bad direction' => ['/api/blog/categories?sort_direction=foo'],
|
||||
'categories unknown column' => ['/api/blog/categories?sort_by=no_such_column'],
|
||||
'categories oversized page' => ['/api/blog/categories?per_page=100000'],
|
||||
'categories zero page size' => ['/api/blog/categories?per_page=0'],
|
||||
'posts unknown sort column' => ['/api/blog/posts?sort_field=password'],
|
||||
'posts oversized page' => ['/api/blog/posts?per_page=9999'],
|
||||
'tags bad direction' => ['/api/blog/tags?sort_direction=sideways'],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('badQueryProvider')]
|
||||
public function test_invalid_list_parameters_are_rejected(string $url): void
|
||||
{
|
||||
$this->getJson($url)->assertStatus(422);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{0: string}>
|
||||
*/
|
||||
public static function goodQueryProvider(): array
|
||||
{
|
||||
return [
|
||||
'categories default' => ['/api/blog/categories'],
|
||||
'categories max page size' => ['/api/blog/categories?per_page=50'],
|
||||
'categories valid sort' => ['/api/blog/categories?sort_by=name&sort_direction=asc'],
|
||||
'categories filter' => ['/api/blog/categories?filter=web'],
|
||||
'posts default' => ['/api/blog/posts'],
|
||||
'posts valid sort' => ['/api/blog/posts?sort_field=views&sort_direction=asc'],
|
||||
'tags default' => ['/api/blog/tags'],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('goodQueryProvider')]
|
||||
public function test_valid_list_parameters_are_accepted(string $url): void
|
||||
{
|
||||
$this->getJson($url)->assertOk();
|
||||
}
|
||||
|
||||
public function test_page_size_is_capped(): void
|
||||
{
|
||||
Category::factory()->count(60)->create();
|
||||
|
||||
$response = $this->getJson('/api/blog/categories?per_page=50');
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('meta.per_page', 50)
|
||||
->assertJsonCount(50, 'data');
|
||||
}
|
||||
|
||||
public function test_defaults_are_unchanged_for_existing_consumers(): void
|
||||
{
|
||||
$response = $this->getJson('/api/blog/categories');
|
||||
|
||||
$response->assertOk()->assertJsonPath('meta.per_page', 10);
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,8 @@ class AboutMeTest extends TestCase
|
||||
|
||||
public function test_can_create_about_me()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$response = $this->postJson('/api/website/about-me', [
|
||||
'image' => 'test.jpg',
|
||||
]);
|
||||
@@ -53,6 +55,8 @@ class AboutMeTest extends TestCase
|
||||
|
||||
public function test_can_update_about_me()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$aboutMe = AboutMe::factory()->create();
|
||||
|
||||
$response = $this->putJson("/api/website/about-me/{$aboutMe->id}", [
|
||||
@@ -65,6 +69,8 @@ class AboutMeTest extends TestCase
|
||||
|
||||
public function test_can_delete_about_me()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$aboutMe = AboutMe::factory()->create();
|
||||
|
||||
$response = $this->deleteJson("/api/website/about-me/{$aboutMe->id}");
|
||||
|
||||
+30
-1
@@ -2,9 +2,38 @@
|
||||
|
||||
namespace Tests;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
|
||||
abstract class TestCase extends BaseTestCase
|
||||
{
|
||||
//
|
||||
/**
|
||||
* Authenticate the current request as an admin user.
|
||||
*
|
||||
* Every mutating endpoint requires both a valid session and the admin
|
||||
* flag, so tests that create or destroy content must opt in explicitly
|
||||
* rather than relying on the previous anonymous behaviour.
|
||||
*/
|
||||
protected function actingAsAdmin(): User
|
||||
{
|
||||
$admin = User::factory()->admin()->create();
|
||||
|
||||
Sanctum::actingAs($admin);
|
||||
|
||||
return $admin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate as a valid user that is *not* an admin, to prove the
|
||||
* second authorisation gate is enforced.
|
||||
*/
|
||||
protected function actingAsNonAdmin(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
Sanctum::actingAs($user);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user