-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebhookAdminController.php
More file actions
223 lines (186 loc) · 7.52 KB
/
WebhookAdminController.php
File metadata and controls
223 lines (186 loc) · 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Webhook;
use App\Models\WebhookDelivery;
use App\Rules\ExternalUrl;
use App\Services\AuthorizationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
class WebhookAdminController extends Controller
{
/**
* Reserved header names that must not be overridden by custom headers.
*/
private const RESERVED_HEADERS = ['x-numen-signature', 'content-type', 'user-agent'];
public function __construct(private readonly AuthorizationService $authz) {}
/**
* List all webhooks for the first space the user has access to.
*/
public function index(Request $request): Response
{
// Webhooks are global — no space context required for listing.
$webhooks = Webhook::latest()
->get()
->map(fn (Webhook $w) => [
'id' => $w->id,
'url' => $w->url,
'events' => $w->events,
'is_active' => $w->is_active,
'created_at' => $w->created_at->toIso8601String(),
]);
return Inertia::render('Settings/Webhooks', [
'webhooks' => $webhooks,
'newSecret' => session('newSecret'),
]);
}
/**
* Create a new webhook.
*/
public function store(Request $request): RedirectResponse
{
$spaceId = $request->space()->id ?? abort(403, 'No space context.');
$this->authz->authorize($request->user(), 'webhooks.manage', $spaceId);
$validated = $request->validate([
'url' => ['required', 'url', 'max:2048', new ExternalUrl],
'events' => ['required', 'array', 'min:1'],
'events.*' => ['required', 'string', 'max:64'],
'is_active' => ['sometimes', 'boolean'],
'retry_policy' => ['sometimes', 'nullable', 'array'],
'headers' => ['sometimes', 'nullable', 'array'],
'headers.*' => ['string', 'regex:/^[^\r\n]+$/'],
'batch_mode' => ['sometimes', 'boolean'],
'batch_timeout' => ['sometimes', 'integer', 'min:100', 'max:300000'],
]);
if (isset($validated['headers'])) {
$validated['headers'] = $this->sanitizeHeaders($validated['headers']);
}
$validated['space_id'] = $spaceId;
$secret = Str::random(64);
$validated['secret'] = $secret;
Webhook::create($validated);
return redirect()->route('admin.webhooks')->with('success', 'Webhook created.')->with('newSecret', $secret);
}
/**
* Update a webhook.
*/
public function update(Request $request, string $id): RedirectResponse
{
$spaceId = $this->resolveSpaceId($request);
$webhook = Webhook::where('space_id', $spaceId)->findOrFail($id);
$this->authz->authorize($request->user(), 'webhooks.manage', $spaceId);
$validated = $request->validate([
'url' => ['sometimes', 'url', 'max:2048', new ExternalUrl, Rule::unique('webhooks')->where('space_id', $webhook->space_id)->ignore($webhook->id)],
'events' => ['sometimes', 'array', 'min:1'],
'events.*' => ['required_with:events', 'string', 'max:64'],
'is_active' => ['sometimes', 'boolean'],
'retry_policy' => ['sometimes', 'nullable', 'array'],
'headers' => ['sometimes', 'nullable', 'array'],
'headers.*' => ['string', 'regex:/^[^\r\n]+$/'],
'batch_mode' => ['sometimes', 'boolean'],
'batch_timeout' => ['sometimes', 'integer', 'min:100', 'max:300000'],
]);
if (isset($validated['headers'])) {
$validated['headers'] = $this->sanitizeHeaders($validated['headers']);
}
$webhook->update($validated);
return redirect()->route('admin.webhooks')->with('success', 'Webhook updated.');
}
/**
* Soft-delete a webhook.
*/
public function destroy(Request $request, string $id): RedirectResponse
{
$spaceId = $this->resolveSpaceId($request);
$webhook = Webhook::where('space_id', $spaceId)->findOrFail($id);
$this->authz->authorize($request->user(), 'webhooks.manage', $spaceId);
$webhook->delete();
return redirect()->route('admin.webhooks')->with('success', 'Webhook deleted.');
}
/**
* Rotate the signing secret.
*/
public function rotateSecret(Request $request, string $id): RedirectResponse
{
$spaceId = $this->resolveSpaceId($request);
$webhook = Webhook::where('space_id', $spaceId)->findOrFail($id);
$this->authz->authorize($request->user(), 'webhooks.manage', $spaceId);
$newSecret = Str::random(64);
$webhook->update(['secret' => $newSecret]);
return redirect()->route('admin.webhooks')->with('newSecret', $newSecret);
}
/**
* Return last 50 deliveries for a webhook as JSON.
*/
public function deliveries(Request $request, string $id): JsonResponse
{
$spaceId = $this->resolveSpaceId($request);
$webhook = Webhook::where('space_id', $spaceId)->findOrFail($id);
$this->authz->authorize($request->user(), 'webhooks.manage', $spaceId);
$deliveries = WebhookDelivery::where('webhook_id', $id)
->orderByDesc('created_at')
->limit(50)
->get()
->map(fn (WebhookDelivery $d) => [
'id' => $d->id,
'event_type' => $d->event_type,
'status' => $d->status,
'http_status' => $d->http_status,
'attempt_number' => $d->attempt_number,
'created_at' => $d->created_at->toIso8601String(),
]);
return response()->json(['data' => $deliveries]);
}
/**
* Re-queue a failed delivery.
*/
public function redeliver(Request $request, string $id, string $deliveryId): JsonResponse
{
$spaceId = $this->resolveSpaceId($request);
$webhook = Webhook::where('space_id', $spaceId)->findOrFail($id);
$this->authz->authorize($request->user(), 'webhooks.manage', $spaceId);
$delivery = WebhookDelivery::where('webhook_id', $id)
->where('id', $deliveryId)
->firstOrFail();
// Mark as pending to re-queue
$delivery->update([
'status' => WebhookDelivery::STATUS_PENDING,
'scheduled_at' => now(),
]);
return response()->json(['message' => 'Delivery re-queued for delivery.']);
}
/**
* Resolve the first space ID accessible by the authenticated user.
*/
private function resolveSpaceId(Request $request): string
{
return $request->space()->id ?? abort(403, 'No space context.');
}
/**
* Remove reserved headers and validate header key format.
*
* @param array<string, string> $headers
* @return array<string, string>
*/
private function sanitizeHeaders(array $headers): array
{
$sanitized = [];
foreach ($headers as $key => $value) {
// Reject invalid key format
if (! preg_match('/^[a-zA-Z0-9_-]+$/', (string) $key)) {
continue;
}
// Reject reserved headers (case-insensitive)
if (in_array(strtolower((string) $key), self::RESERVED_HEADERS, true)) {
continue;
}
$sanitized[$key] = $value;
}
return $sanitized;
}
}