-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSession.php
More file actions
393 lines (348 loc) · 11.5 KB
/
Copy pathSession.php
File metadata and controls
393 lines (348 loc) · 11.5 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<?php
declare(strict_types=1);
namespace flight;
use SessionHandlerInterface;
/**
* A lightweight, file-based session handler for the Flight framework.
* Supports non-blocking behavior, optional encryption, and auto-commit.
*/
class Session implements SessionHandlerInterface
{
private string $savePath;
private array $data = [];
private bool $changed = false;
private ?string $sessionId = null;
private ?string $encryptionKey = null;
private bool $autoCommit = true;
private bool $testMode = false;
/**
* Constructor to initialize the session handler.
*
* @param array $config Configuration options:
* - save_path: Directory where session files are stored (default: system temp dir/flight_sessions)
* - encryption_key: Optional encryption key for session data (recommended 32 bytes for AES-256)
* - auto_commit: Whether to auto-commit session changes on shutdown (default: true)
* - start_session: Whether to start the session automatically (default: true)
* - test_mode: Run in test mode without altering PHP's session state (default: false)
* - test_session_id: Custom session ID to use in test mode (default: random ID)
*/
public function __construct(array $config = [])
{
$this->savePath = $config['save_path'] ?? sys_get_temp_dir() . '/flight_sessions';
$this->encryptionKey = $config['encryption_key'] ?? null;
$this->autoCommit = $config['auto_commit'] ?? true;
$startSession = $config['start_session'] ?? true;
$this->testMode = $config['test_mode'] ?? false;
// Set test session ID if provided
if ($this->testMode === true && isset($config['test_session_id'])) {
$this->sessionId = $config['test_session_id'];
}
// Set the save path, defaulting to a subdirectory in the system temp directory
if (is_dir($this->savePath) === false) {
mkdir($this->savePath, 0700, true); // Secure permissions: owner-only access
}
// Initialize session handler
$this->initializeSession($startSession);
}
/**
* Initialize the session handler and optionally start the session.
*
* @param bool $startSession Whether to start the session automatically
* @return void
*/
private function initializeSession(bool $startSession): void
{
// In test mode, generate a test session ID if none was provided
if ($this->testMode) {
if ($this->sessionId === null) {
$this->sessionId = bin2hex(random_bytes(16)); // Generate a test session ID
}
$this->read($this->sessionId); // Load session data for the test session ID
return; // Skip actual session operations in test mode
}
// @codeCoverageIgnoreStart
// Register the session handler only if no session is active yet
if ($startSession === true && session_status() === PHP_SESSION_NONE) {
session_set_save_handler($this, true);
// Start the session if requested
session_start(['read_and_close' => true]);
$this->sessionId = session_id();
} elseif (session_status() === PHP_SESSION_ACTIVE) {
// If session is already active, ensure we have the session ID
$this->sessionId = session_id();
}
// Register auto-commit on shutdown if enabled
if ($this->autoCommit === true) {
register_shutdown_function([$this, 'commit']);
}
// @codeCoverageIgnoreEnd
}
/**
* Open a session.
*
* This method is called by PHP when a session is started. It initializes the session storage.
*
* @param string $savePath The path where to store/retrieve the session.
* @param string $sessionName The name of the session.
* @return bool Returns true always
*/
public function open($savePath, $sessionName): bool
{
return true;
}
/**
* Closes the current session.
*
* This method is called automatically when the script ends or when session_write_close() is called.
*
* @return bool Returns true always
*/
public function close(): bool
{
return true;
}
/**
* Reads the session data associated with the given session ID.
*
* @param string $id The session ID.
* @return string The session data.
*/
public function read($id): string
{
$this->sessionId = $id;
$file = $this->getSessionFile($id);
// Fail fast: no file exists
if (file_exists($file) === false) {
$this->data = [];
return serialize($this->data);
}
// Fail fast: unable to read file or empty content
$content = file_get_contents($file);
if ($content === false || strlen($content) < 1) {
$this->data = [];
return serialize($this->data);
}
// Extract prefix and data
$prefix = $content[0];
$dataStr = substr($content, 1);
// Handle plain data (no encryption)
if ($prefix === 'P' && $this->encryptionKey === null) {
$this->data = unserialize($dataStr) ?: [];
return serialize($this->data);
}
// Handle encrypted data
if ($prefix === 'E' && $this->encryptionKey !== null) {
$iv = substr($dataStr, 0, 16);
$encrypted = substr($dataStr, 16);
$decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $this->encryptionKey, 0, $iv);
$this->data = $decrypted !== false ? unserialize($decrypted) : [];
return serialize($this->data);
}
// Fail fast: mismatch between prefix and encryption state
$this->data = [];
return serialize($this->data);
}
/**
* Helper method for encryption to make testing easier.
* Protected visibility to allow mocking in tests.
*
* @param string $data Data to encrypt
* @return string|false Encrypted data or false on failure
*/
protected function encryptData(string $data)
{
$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($data, 'AES-256-CBC', $this->encryptionKey, 0, $iv);
if ($encrypted === false) {
return false; // @codeCoverageIgnore
}
return 'E' . $iv . $encrypted;
}
/**
* Modify the write method to use the encryptData helper method
*/
public function write($id, $data): bool
{
// Fail fast: no changes to write
if ($this->changed === false) {
return true;
}
$file = $this->getSessionFile($id);
$serialized = serialize($this->data);
// Handle encryption if key is provided
if ($this->encryptionKey !== null) {
$content = $this->encryptData($serialized);
// Fail fast: encryption failed
if ($content === false) {
return false;
}
} else {
$content = 'P' . $serialized;
}
// Write to file and return success
return file_put_contents($file, $content) !== false;
}
/**
* Destroys the session with the given ID.
*
* @param string $id The ID of the session to destroy.
* @return bool Returns true on success or false on failure.
*/
public function destroy($id): bool
{
$file = $this->getSessionFile($id);
if (file_exists($file)) {
unlink($file);
}
$this->data = [];
$this->changed = true;
return true;
}
/**
* Garbage collector for session data.
*
* This method is responsible for cleaning up old session data that has
* exceeded the maximum lifetime.
*
* @param int $maxLifetime The maximum lifetime of a session in seconds.
* @return int|false The number of deleted sessions on success, or false on failure.
*/
#[\ReturnTypeWillChange]
public function gc($maxLifetime)
{
$count = 0;
$time = time();
$pattern = $this->savePath . '/sess_*';
// Get session files; return 0 if glob fails or no files exist
$files = glob($pattern);
foreach ($files as $file) {
if (filemtime($file) + $maxLifetime < $time) {
if (unlink($file)) {
$count++;
}
}
}
return $count;
}
/**
* Sets a session variable.
*
* @param string $key The name of the session variable.
* @param mixed $value The value to be stored in the session variable.
* @return self Returns the current instance for method chaining.
*/
public function set(string $key, $value): self
{
$this->data[$key] = $value;
$this->changed = true;
return $this;
}
/**
* Retrieve a value from the session.
*
* @param string $key The key of the session value to retrieve.
* @param mixed $default The default value to return if the key does not exist. Default is null.
* @return mixed The value associated with the given key, or the default value if the key does not exist.
*/
public function get(string $key, $default = null)
{
return $this->data[$key] ?? $default;
}
/**
* Deletes a session variable.
*
* @param string $key The key of the session variable to delete.
* @return self Returns the current instance for method chaining.
*/
public function delete(string $key): self
{
unset($this->data[$key]);
$this->changed = true;
return $this;
}
/**
* Clears all session data.
*
* @return self Returns the current instance for method chaining.
*/
public function clear(): self
{
$this->data = [];
$this->changed = true;
return $this;
}
/**
* Retrieve all session data.
*
* @return array An associative array containing all session data.
*/
public function getAll(): array
{
return $this->data;
}
/**
* Commits the current session data and writes it to the storage.
*
* This method should be called to ensure that all session data is properly
* saved and the session is closed. It is typically called at the end of a
* request to persist any changes made to the session.
*
* @return void
*/
public function commit(): void
{
if ($this->changed && $this->sessionId) {
$this->write($this->sessionId, '');
$this->changed = false;
}
}
/**
* Get the current session ID.
*
* @return string|null The session ID if one exists, or null if no session is active.
*/
public function id(): ?string
{
return $this->sessionId;
}
/**
* Regenerates the session ID.
*
* @param bool $deleteOld Whether to delete the old session data or not.
* @return self Returns the current instance for method chaining.
*/
public function regenerate(bool $deleteOld = false): self
{
if ($this->sessionId) {
if ($this->testMode) {
// In test mode, simply generate a new ID without affecting PHP sessions
$oldId = $this->sessionId;
$this->sessionId = bin2hex(random_bytes(16));
if ($deleteOld) {
$this->destroy($oldId);
}
} else {
// @codeCoverageIgnoreStart
session_regenerate_id($deleteOld);
$newId = session_id();
if ($deleteOld) {
$this->destroy($this->sessionId);
}
$this->sessionId = $newId;
// @codeCoverageIgnoreEnd
}
$this->changed = true;
}
return $this;
}
/**
* Retrieves the file path for the session file based on the session ID.
*
* @param string $id The session ID.
* @return string The file path for the session file.
*/
private function getSessionFile(string $id): string
{
return $this->savePath . '/sess_' . $id;
}
}