-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.php
More file actions
337 lines (290 loc) · 11.8 KB
/
Copy pathserver.php
File metadata and controls
337 lines (290 loc) · 11.8 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
<?php
declare(strict_types=1);
/**
* Demo dev server for stromcom/http-smoke examples.
*
* Endpoints (kept short — see examples/SmokeHttp/* for what each one is exercised by):
*
* GET / HTML home
* GET /robots.txt plain text
* GET /redirect-to-login 302 → /login
* GET /login HTML login form
*
* GET /api/ping public JSON ping
* GET /api/version public JSON version
* GET /api/slow?ms=300 sleeps then 200 (timeout testing)
* GET /api/eventually/{key}/{n} first N hits return 404, then 200 (retry-on-failure)
* GET /api/fail-once 500 once, 200 thereafter (retry-on-5xx)
* GET /api/users/ 401 without auth, 200 with Bearer dev-test-token
*
* POST /api/threads/ creates thread; returns hash + initial msg hash
* GET /api/threads/{hash}/ returns stored thread
* PATCH /api/threads/{hash}/messages/{msg}/notice/ marks message as read
* DELETE /api/threads/{hash}/ deletes the thread
*
* POST /session/login sets session cookie, 302 → /session/dashboard
* GET /session/dashboard 200 with cookie, 401 without
* GET /session/projects 200 with cookie, 401 without
* POST /session/logout clears cookie, 204
*
* HEAD on any GET route reuses the GET handler.
* OPTIONS on any path returns 204 with Allow header.
*/
const AUTH_TOKEN = 'Bearer dev-test-token';
$stateFile = sys_get_temp_dir() . '/http-smoke-dev-state.json';
$sessionFile = sys_get_temp_dir() . '/http-smoke-dev-sessions.json';
$uri = is_string($_SERVER['REQUEST_URI'] ?? null) ? $_SERVER['REQUEST_URI'] : '/';
$parsed = parse_url($uri, PHP_URL_PATH);
$path = is_string($parsed) ? $parsed : '/';
$method = is_string($_SERVER['REQUEST_METHOD'] ?? null) ? $_SERVER['REQUEST_METHOD'] : 'GET';
$query = [];
$qs = parse_url($uri, PHP_URL_QUERY);
if (is_string($qs)) {
parse_str($qs, $query);
}
function respond_json(mixed $data, int $status = 200): never
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
function respond_html(string $html, int $status = 200): never
{
http_response_code($status);
header('Content-Type: text/html; charset=utf-8');
echo $html;
exit;
}
/**
* @return array<string, mixed>
*/
function load_state(string $file): array
{
if (!is_file($file)) {
return [];
}
$raw = @file_get_contents($file);
if (!is_string($raw) || $raw === '') {
return [];
}
$decoded = json_decode($raw, true);
return is_array($decoded) ? $decoded : [];
}
/**
* @param array<string, mixed> $state
*/
function save_state(string $file, array $state): void
{
file_put_contents($file, json_encode($state, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
function read_input(): string
{
$raw = file_get_contents('php://input');
return is_string($raw) ? $raw : '';
}
/**
* @return array<array-key, mixed>
*/
function read_json_input(): array
{
$raw = read_input();
if ($raw === '') {
return [];
}
$decoded = json_decode($raw, true);
return is_array($decoded) ? $decoded : [];
}
function require_bearer(): void
{
$auth = is_string($_SERVER['HTTP_AUTHORIZATION'] ?? null) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
if ($auth !== AUTH_TOKEN) {
respond_json(['status' => 'error', 'error' => 'unauthenticated'], 401);
}
}
function read_session_id(): ?string
{
$cookie = is_string($_SERVER['HTTP_COOKIE'] ?? null) ? $_SERVER['HTTP_COOKIE'] : '';
if ($cookie === '') {
return null;
}
foreach (explode(';', $cookie) as $part) {
$part = trim($part);
if (str_starts_with($part, 'session_id=')) {
return substr($part, 11);
}
}
return null;
}
if ($method === 'OPTIONS') {
header('Allow: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS');
http_response_code(204);
exit;
}
$origMethod = $method;
if ($method === 'HEAD') {
$method = 'GET';
}
// ── Routes ───────────────────────────────────────────────────────────────────
if ($path === '/' && $method === 'GET') {
header('Cache-Control: public, max-age=60');
respond_html('<!doctype html><html><head><title>Smoke Demo</title></head><body><h1>Welcome</h1><p>Demo dev server for http-smoke examples.</p></body></html>');
}
if ($path === '/robots.txt' && $method === 'GET') {
header('Content-Type: text/plain; charset=utf-8');
echo "User-agent: *\nDisallow:\n";
exit;
}
if ($path === '/redirect-to-login' && $method === 'GET') {
http_response_code(302);
header('Location: /login');
exit;
}
if ($path === '/login' && $method === 'GET') {
respond_html('<!doctype html><html><head><title>Login</title></head><body><form method="post" action="/session/login"><input name="username"><input name="password" type="password"><button>Sign in</button></form></body></html>');
}
// ── Public API ──────────────────────────────────────────────────────────────
if ($path === '/api/ping' && $method === 'GET') {
respond_json(['status' => 'ok', 'pong' => true, 'time' => time()]);
}
if ($path === '/api/version' && $method === 'GET') {
respond_json(['version' => '1.0.0', 'commit' => 'demo-' . substr(md5(__FILE__), 0, 7)]);
}
if ($path === '/api/slow' && $method === 'GET') {
$ms = isset($query['ms']) && is_numeric($query['ms']) ? (int) $query['ms'] : 200;
usleep($ms * 1000);
respond_json(['status' => 'ok', 'slept_ms' => $ms]);
}
if (preg_match('#^/api/eventually/([a-zA-Z0-9_-]+)/(\d+)$#', $path, $m) === 1 && $method === 'GET') {
$key = $m[1];
$hitsBeforeOk = (int) $m[2];
$state = load_state($stateFile);
$counts = is_array($state['eventually'] ?? null) ? $state['eventually'] : [];
$current = isset($counts[$key]) && is_int($counts[$key]) ? $counts[$key] : 0;
$counts[$key] = $current + 1;
$state['eventually'] = $counts;
save_state($stateFile, $state);
if ($current < $hitsBeforeOk) {
respond_json(['status' => 'pending', 'attempt' => $current + 1, 'needed' => $hitsBeforeOk + 1], 404);
}
respond_json(['status' => 'ready', 'attempt' => $current + 1]);
}
if ($path === '/api/fail-once' && $method === 'GET') {
$state = load_state($stateFile);
$count = isset($state['fail_once_count']) && is_int($state['fail_once_count']) ? $state['fail_once_count'] : 0;
$state['fail_once_count'] = $count + 1;
save_state($stateFile, $state);
if ($count === 0) {
respond_json(['status' => 'error', 'message' => 'first attempt fails by design'], 500);
}
respond_json(['status' => 'ok', 'attempt' => $count + 1]);
}
if ($path === '/api/users/' && $method === 'GET') {
require_bearer();
respond_json([
'status' => 'success',
'data' => [
['id' => 'u-1', 'name' => 'Alice'],
['id' => 'u-2', 'name' => 'Bob'],
],
'meta' => ['count' => 2],
]);
}
// ── Authenticated CRUD: threads with messages ───────────────────────────────
if ($path === '/api/threads/' && $method === 'POST') {
require_bearer();
$payload = read_json_input();
$threadHash = 'th_' . bin2hex(random_bytes(6));
$messageHash = 'msg_' . bin2hex(random_bytes(6));
$state = load_state($stateFile);
$threads = is_array($state['threads'] ?? null) ? $state['threads'] : [];
$threads[$threadHash] = [
'hash' => $threadHash,
'code' => is_string($payload['thread_code'] ?? null) ? $payload['thread_code'] : 'untitled',
'messages' => [
$messageHash => [
'hash' => $messageHash,
'body' => is_string($payload['message'] ?? null) ? $payload['message'] : '',
'read' => false,
],
],
];
$state['threads'] = $threads;
save_state($stateFile, $state);
respond_json([
'status' => 'success',
'data' => [
'thread' => ['hash' => $threadHash, 'code' => $threads[$threadHash]['code']],
'message' => ['hash' => $messageHash],
],
], 201);
}
if (preg_match('#^/api/threads/([^/]+)/$#', $path, $m) === 1 && $method === 'GET') {
require_bearer();
$state = load_state($stateFile);
$threads = is_array($state['threads'] ?? null) ? $state['threads'] : [];
if (!isset($threads[$m[1]])) {
respond_json(['status' => 'error', 'error' => 'not found'], 404);
}
respond_json(['status' => 'success', 'data' => $threads[$m[1]]]);
}
if (preg_match('#^/api/threads/([^/]+)/messages/([^/]+)/notice/$#', $path, $m) === 1 && $method === 'PATCH') {
require_bearer();
$payload = read_json_input();
$action = is_string($payload['action'] ?? null) ? $payload['action'] : '';
$state = load_state($stateFile);
$threads = is_array($state['threads'] ?? null) ? $state['threads'] : [];
if (!isset($threads[$m[1]]) || !is_array($threads[$m[1]]['messages'] ?? null) || !isset($threads[$m[1]]['messages'][$m[2]])) {
respond_json(['status' => 'error', 'error' => 'not found'], 404);
}
$threads[$m[1]]['messages'][$m[2]]['read'] = $action === 'read';
$state['threads'] = $threads;
save_state($stateFile, $state);
respond_json(['status' => 'success']);
}
if (preg_match('#^/api/threads/([^/]+)/$#', $path, $m) === 1 && $method === 'DELETE') {
require_bearer();
$state = load_state($stateFile);
$threads = is_array($state['threads'] ?? null) ? $state['threads'] : [];
if (!isset($threads[$m[1]])) {
respond_json(['status' => 'error', 'error' => 'not found'], 404);
}
unset($threads[$m[1]]);
$state['threads'] = $threads;
save_state($stateFile, $state);
http_response_code(204);
exit;
}
// ── Cookie-based session flow ───────────────────────────────────────────────
if ($path === '/session/login' && $method === 'POST') {
$sessionId = bin2hex(random_bytes(8));
$sessions = load_state($sessionFile);
$sessions[$sessionId] = ['user' => 'demo', 'created' => time()];
save_state($sessionFile, $sessions);
header('Set-Cookie: session_id=' . $sessionId . '; Path=/; HttpOnly');
http_response_code(302);
header('Location: /session/dashboard');
exit;
}
if (str_starts_with($path, '/session/') && in_array($path, ['/session/dashboard', '/session/projects'], true) && $method === 'GET') {
$sessionId = read_session_id();
$sessions = load_state($sessionFile);
if ($sessionId === null || !isset($sessions[$sessionId])) {
respond_json(['status' => 'error', 'error' => 'unauthenticated'], 401);
}
respond_json(['status' => 'success', 'page' => $path, 'session' => $sessionId]);
}
if ($path === '/session/logout' && $method === 'POST') {
$sessionId = read_session_id();
if ($sessionId !== null) {
$sessions = load_state($sessionFile);
unset($sessions[$sessionId]);
save_state($sessionFile, $sessions);
}
header('Set-Cookie: session_id=; Path=/; Max-Age=0');
http_response_code(204);
exit;
}
// ── Fallback ────────────────────────────────────────────────────────────────
respond_json(['status' => 'error', 'error' => 'route not found', 'path' => $path, 'method' => $origMethod], 404);