Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/tests/Integration/Api/Client/ApiKeyControllerTest.php
7459 views
1
<?php
2
3
namespace Pterodactyl\Tests\Integration\Api\Client;
4
5
use Pterodactyl\Models\User;
6
use Illuminate\Http\Response;
7
use Pterodactyl\Models\ApiKey;
8
use Illuminate\Support\Facades\Event;
9
use Pterodactyl\Events\ActivityLogged;
10
11
class ApiKeyControllerTest extends ClientApiIntegrationTestCase
12
{
13
/**
14
* Cleanup after tests.
15
*/
16
protected function tearDown(): void
17
{
18
ApiKey::query()->forceDelete();
19
20
parent::tearDown();
21
}
22
23
/**
24
* Test that the client's API key can be returned successfully.
25
*/
26
public function testApiKeysAreReturned()
27
{
28
/** @var User $user */
29
$user = User::factory()->create();
30
/** @var ApiKey $key */
31
$key = ApiKey::factory()->for($user)->create([
32
'key_type' => ApiKey::TYPE_ACCOUNT,
33
]);
34
35
$response = $this->actingAs($user)->get('/api/client/account/api-keys')
36
->assertOk()
37
->assertJsonPath('object', 'list')
38
->assertJsonPath('data.0.object', ApiKey::RESOURCE_NAME);
39
40
$this->assertJsonTransformedWith($response->json('data.0.attributes'), $key);
41
}
42
43
/**
44
* Test that an API key can be created for the client account. This also checks that the
45
* API key secret is returned as metadata in the response since it will not be returned
46
* after that point.
47
*/
48
#[\PHPUnit\Framework\Attributes\DataProvider('validIPAddressDataProvider')]
49
public function testApiKeyCanBeCreatedForAccount(array $data)
50
{
51
/** @var User $user */
52
$user = User::factory()->create();
53
54
// Small subtest to ensure we're always comparing the number of keys to the
55
// specific logged in account, and not just the total number of keys stored in
56
// the database.
57
ApiKey::factory()->times(10)->create([
58
'user_id' => User::factory()->create()->id,
59
'key_type' => ApiKey::TYPE_ACCOUNT,
60
]);
61
62
$response = $this->actingAs($user)->postJson('/api/client/account/api-keys', [
63
'description' => 'Test Description',
64
'allowed_ips' => $data,
65
])
66
->assertOk()
67
->assertJsonPath('object', ApiKey::RESOURCE_NAME);
68
69
/** @var ApiKey $key */
70
$key = ApiKey::query()->where('identifier', $response->json('attributes.identifier'))->firstOrFail();
71
72
$this->assertJsonTransformedWith($response->json('attributes'), $key);
73
$response->assertJsonPath('meta.secret_token', decrypt($key->token));
74
75
$this->assertActivityFor('user:api-key.create', $user, [$key, $user]);
76
}
77
78
/**
79
* Block requests to create an API key specifying more than 50 IP addresses.
80
*/
81
public function testApiKeyCannotSpecifyMoreThanFiftyIps()
82
{
83
$ips = [];
84
for ($i = 0; $i < 100; ++$i) {
85
$ips[] = '127.0.0.' . $i;
86
}
87
88
$this->actingAs(User::factory()->create())
89
->postJson('/api/client/account/api-keys', [
90
'description' => 'Test Data',
91
'allowed_ips' => $ips,
92
])
93
->assertUnprocessable()
94
->assertJsonPath('errors.0.detail', 'The allowed ips may not have more than 50 items.');
95
}
96
97
/**
98
* Test that no more than 25 API keys can exist at any one time for an account. This prevents
99
* a DoS attack vector against the panel.
100
*
101
* @see https://github.com/pterodactyl/panel/security/advisories/GHSA-pjmh-7xfm-r4x9
102
* @see https://github.com/pterodactyl/panel/issues/4394
103
*/
104
public function testApiKeyLimitIsApplied()
105
{
106
/** @var User $user */
107
$user = User::factory()->create();
108
ApiKey::factory()->times(25)->for($user)->create([
109
'key_type' => ApiKey::TYPE_ACCOUNT,
110
]);
111
112
$this->actingAs($user)->postJson('/api/client/account/api-keys', [
113
'description' => 'Test Description',
114
'allowed_ips' => ['127.0.0.1'],
115
])
116
->assertStatus(Response::HTTP_BAD_REQUEST)
117
->assertJsonPath('errors.0.code', 'DisplayException')
118
->assertJsonPath('errors.0.detail', 'You have reached the account limit for number of API keys.');
119
}
120
121
/**
122
* Test that a bad request results in a validation error being returned by the API.
123
*
124
* @see https://github.com/pterodactyl/panel/issues/2457
125
*/
126
public function testValidationErrorIsReturnedForBadRequests()
127
{
128
$this->actingAs(User::factory()->create());
129
130
$this->postJson('/api/client/account/api-keys', [
131
'description' => '',
132
'allowed_ips' => ['127.0.0.1'],
133
])
134
->assertUnprocessable()
135
->assertJsonPath('errors.0.meta.rule', 'required')
136
->assertJsonPath('errors.0.detail', 'The description field is required.');
137
138
$this->postJson('/api/client/account/api-keys', [
139
'description' => str_repeat('a', 501),
140
'allowed_ips' => ['127.0.0.1'],
141
])
142
->assertUnprocessable()
143
->assertJsonPath('errors.0.meta.rule', 'max')
144
->assertJsonPath('errors.0.detail', 'The description may not be greater than 500 characters.');
145
146
$this->postJson('/api/client/account/api-keys', [
147
'description' => 'Foobar',
148
'allowed_ips' => ['hodor', '127.0.0.1', 'hodor/24'],
149
])
150
->assertUnprocessable()
151
->assertJsonPath('errors.0.detail', '"hodor" is not a valid IP address or CIDR range.')
152
->assertJsonPath('errors.0.meta.source_field', 'allowed_ips.0')
153
->assertJsonPath('errors.1.detail', '"hodor/24" is not a valid IP address or CIDR range.')
154
->assertJsonPath('errors.1.meta.source_field', 'allowed_ips.2');
155
}
156
157
/**
158
* Tests that an API key can be deleted from the account.
159
*/
160
public function testApiKeyCanBeDeleted()
161
{
162
/** @var User $user */
163
$user = User::factory()->create();
164
/** @var ApiKey $key */
165
$key = ApiKey::factory()->for($user)->create([
166
'key_type' => ApiKey::TYPE_ACCOUNT,
167
]);
168
169
$response = $this->actingAs($user)->delete('/api/client/account/api-keys/' . $key->identifier);
170
$response->assertStatus(Response::HTTP_NO_CONTENT);
171
172
$this->assertDatabaseMissing('api_keys', ['id' => $key->id]);
173
$this->assertActivityFor('user:api-key.delete', $user, $user);
174
}
175
176
/**
177
* Test that trying to delete an API key that does not exist results in a 404.
178
*/
179
public function testNonExistentApiKeyDeletionReturns404Error()
180
{
181
/** @var User $user */
182
$user = User::factory()->create();
183
/** @var ApiKey $key */
184
$key = ApiKey::factory()->create([
185
'user_id' => $user->id,
186
'key_type' => ApiKey::TYPE_ACCOUNT,
187
]);
188
189
$response = $this->actingAs($user)->delete('/api/client/account/api-keys/1234');
190
$response->assertNotFound();
191
192
$this->assertDatabaseHas('api_keys', ['id' => $key->id]);
193
Event::assertNotDispatched(ActivityLogged::class);
194
}
195
196
/**
197
* Test that an API key that exists on the system cannot be deleted if the user
198
* who created it is not the authenticated user.
199
*/
200
public function testApiKeyBelongingToAnotherUserCannotBeDeleted()
201
{
202
/** @var User $user */
203
$user = User::factory()->create();
204
/** @var User $user2 */
205
$user2 = User::factory()->create();
206
/** @var ApiKey $key */
207
$key = ApiKey::factory()->for($user2)->create([
208
'key_type' => ApiKey::TYPE_ACCOUNT,
209
]);
210
211
$this->actingAs($user)
212
->deleteJson('/api/client/account/api-keys/' . $key->identifier)
213
->assertNotFound();
214
215
$this->assertDatabaseHas('api_keys', ['id' => $key->id]);
216
Event::assertNotDispatched(ActivityLogged::class);
217
}
218
219
/**
220
* Tests that an application API key also belonging to the logged-in user cannot be
221
* deleted through this endpoint if it exists.
222
*/
223
public function testApplicationApiKeyCannotBeDeleted()
224
{
225
/** @var User $user */
226
$user = User::factory()->create();
227
/** @var ApiKey $key */
228
$key = ApiKey::factory()->for($user)->create([
229
'key_type' => ApiKey::TYPE_APPLICATION,
230
]);
231
232
$this->actingAs($user)
233
->deleteJson('/api/client/account/api-keys/' . $key->identifier)
234
->assertNotFound();
235
236
$this->assertDatabaseHas('api_keys', ['id' => $key->id]);
237
}
238
239
/**
240
* Provides some different IP address combinations that can be used when
241
* testing that we accept the expected IP values.
242
*/
243
public static function validIPAddressDataProvider(): array
244
{
245
return [
246
[[]],
247
[['127.0.0.1']],
248
[['127.0.0.1', '::1']],
249
[['::ffff:7f00:1']],
250
[['127.0.0.1', '192.168.1.100', '192.168.10.10/28']],
251
[['127.0.0.1/32', '192.168.100.100/27', '::1', '::1/128']],
252
];
253
}
254
}
255
256