mastercontroller 1.3.1 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -407,9 +407,6 @@ const SESSION_BEST_PRACTICES = {
407
407
  }
408
408
  };
409
409
 
410
- // MasterController Integration
411
- const master = require('../MasterControl');
412
-
413
410
  // Create MasterController-compatible wrapper
414
411
  class MasterSessionSecurity {
415
412
  constructor() {
@@ -425,6 +422,9 @@ class MasterSessionSecurity {
425
422
  this._options = options;
426
423
  this._instance = new SessionSecurity(options);
427
424
 
425
+ // Lazy load master to avoid circular dependency
426
+ const master = require('../MasterControl');
427
+
428
428
  // Auto-register with pipeline if available
429
429
  if (master.pipeline) {
430
430
  master.pipeline.use(this._instance.middleware());
@@ -501,11 +501,12 @@ class MasterSessionSecurity {
501
501
  }
502
502
  }
503
503
 
504
- // Auto-register with MasterController
505
- master.extend("session", MasterSessionSecurity);
504
+ // Note: Auto-registration with MasterController happens in init() to avoid circular dependency
505
+ // This is called when master.session.init() is invoked in config.js
506
506
 
507
507
  module.exports = {
508
508
  SessionSecurity,
509
+ MasterSessionSecurity,
509
510
  session,
510
511
  createSessionMiddleware,
511
512
  destroySession,
@@ -0,0 +1,276 @@
1
+ // Action Filter Tests for MasterActionFilters.js
2
+ const master = require('../../MasterControl');
3
+ require('../../MasterActionFilters');
4
+
5
+ describe('Action Filters - Fixed Architecture', () => {
6
+
7
+ class TestController {
8
+ constructor() {
9
+ this.__namespace = 'test';
10
+ this._beforeActionFilters = [];
11
+ this._afterActionFilters = [];
12
+
13
+ // Import methods from MasterActionFilters
14
+ Object.assign(this, master.controllerExtensions);
15
+ }
16
+ }
17
+
18
+ describe('Multiple Filters Support', () => {
19
+ test('should support multiple beforeAction filters', () => {
20
+ const controller = new TestController();
21
+
22
+ controller.beforeAction(['show'], () => console.log('Filter 1'));
23
+ controller.beforeAction(['show'], () => console.log('Filter 2'));
24
+ controller.beforeAction(['edit'], () => console.log('Filter 3'));
25
+
26
+ // Should have 3 filters
27
+ expect(controller._beforeActionFilters).toHaveLength(3);
28
+ });
29
+
30
+ test('should not overwrite previous filters', () => {
31
+ const controller = new TestController();
32
+
33
+ controller.beforeAction(['show'], () => 'first');
34
+ controller.beforeAction(['show'], () => 'second');
35
+
36
+ // Both filters should exist
37
+ expect(controller._beforeActionFilters[0].callBack()).toBe('first');
38
+ expect(controller._beforeActionFilters[1].callBack()).toBe('second');
39
+ });
40
+
41
+ test('should support multiple afterAction filters', () => {
42
+ const controller = new TestController();
43
+
44
+ controller.afterAction(['index'], () => {});
45
+ controller.afterAction(['index'], () => {});
46
+
47
+ expect(controller._afterActionFilters).toHaveLength(2);
48
+ });
49
+ });
50
+
51
+ describe('Instance-Level Filters (Not Global)', () => {
52
+ test('should not share filters between controllers', () => {
53
+ const controller1 = new TestController();
54
+ const controller2 = new TestController();
55
+
56
+ controller1.__namespace = 'users';
57
+ controller2.__namespace = 'posts';
58
+
59
+ controller1.beforeAction(['show'], () => 'users filter');
60
+ controller2.beforeAction(['index'], () => 'posts filter');
61
+
62
+ // Each controller has independent filters
63
+ expect(controller1._beforeActionFilters).toHaveLength(1);
64
+ expect(controller2._beforeActionFilters).toHaveLength(1);
65
+
66
+ expect(controller1._beforeActionFilters[0].namespace).toBe('users');
67
+ expect(controller2._beforeActionFilters[0].namespace).toBe('posts');
68
+ });
69
+
70
+ test('should not have race conditions between requests', () => {
71
+ // Simulate two concurrent requests
72
+ const request1Controller = new TestController();
73
+ const request2Controller = new TestController();
74
+
75
+ request1Controller.__namespace = 'users';
76
+ request2Controller.__namespace = 'admin';
77
+
78
+ request1Controller.beforeAction(['show'], () => 'request 1');
79
+ request2Controller.beforeAction(['dashboard'], () => 'request 2');
80
+
81
+ // Each request has its own filter state
82
+ expect(request1Controller._beforeActionFilters[0].callBack()).toBe('request 1');
83
+ expect(request2Controller._beforeActionFilters[0].callBack()).toBe('request 2');
84
+ });
85
+ });
86
+
87
+ describe('Filter Execution', () => {
88
+ test('should execute all matching filters in order', async () => {
89
+ const controller = new TestController();
90
+ const executionOrder = [];
91
+
92
+ controller.beforeAction(['show'], () => executionOrder.push('first'));
93
+ controller.beforeAction(['show'], () => executionOrder.push('second'));
94
+ controller.beforeAction(['show'], () => executionOrder.push('third'));
95
+
96
+ const request = {
97
+ toAction: 'show',
98
+ response: { _headerSent: false, headersSent: false }
99
+ };
100
+
101
+ await controller.__callBeforeAction(controller, request, null);
102
+
103
+ expect(executionOrder).toEqual(['first', 'second', 'third']);
104
+ });
105
+
106
+ test('should only execute filters for matching actions', async () => {
107
+ const controller = new TestController();
108
+ const executed = [];
109
+
110
+ controller.beforeAction(['show'], () => executed.push('show'));
111
+ controller.beforeAction(['edit'], () => executed.push('edit'));
112
+ controller.beforeAction(['destroy'], () => executed.push('destroy'));
113
+
114
+ const request = {
115
+ toAction: 'show',
116
+ response: { _headerSent: false, headersSent: false }
117
+ };
118
+
119
+ await controller.__callBeforeAction(controller, request, null);
120
+
121
+ expect(executed).toEqual(['show']);
122
+ });
123
+ });
124
+
125
+ describe('Async Support', () => {
126
+ test('should support async filters', async () => {
127
+ const controller = new TestController();
128
+ let asyncCompleted = false;
129
+
130
+ controller.beforeAction(['index'], async () => {
131
+ await new Promise(resolve => setTimeout(resolve, 10));
132
+ asyncCompleted = true;
133
+ });
134
+
135
+ const request = {
136
+ toAction: 'index',
137
+ response: { _headerSent: false, headersSent: false }
138
+ };
139
+
140
+ await controller.__callBeforeAction(controller, request, null);
141
+
142
+ expect(asyncCompleted).toBe(true);
143
+ });
144
+
145
+ test('should await each filter before continuing', async () => {
146
+ const controller = new TestController();
147
+ const order = [];
148
+
149
+ controller.beforeAction(['index'], async () => {
150
+ order.push('start-1');
151
+ await new Promise(resolve => setTimeout(resolve, 20));
152
+ order.push('end-1');
153
+ });
154
+
155
+ controller.beforeAction(['index'], async () => {
156
+ order.push('start-2');
157
+ await new Promise(resolve => setTimeout(resolve, 10));
158
+ order.push('end-2');
159
+ });
160
+
161
+ const request = {
162
+ toAction: 'index',
163
+ response: { _headerSent: false, headersSent: false }
164
+ };
165
+
166
+ await controller.__callBeforeAction(controller, request, null);
167
+
168
+ // Should execute in order, awaiting each
169
+ expect(order).toEqual(['start-1', 'end-1', 'start-2', 'end-2']);
170
+ });
171
+ });
172
+
173
+ describe('Error Handling', () => {
174
+ test('should catch and log filter errors', async () => {
175
+ const controller = new TestController();
176
+
177
+ controller.beforeAction(['index'], () => {
178
+ throw new Error('Filter error');
179
+ });
180
+
181
+ const request = {
182
+ toAction: 'index',
183
+ response: {
184
+ _headerSent: false,
185
+ headersSent: false,
186
+ writeHead: jest.fn(),
187
+ end: jest.fn()
188
+ }
189
+ };
190
+
191
+ await expect(
192
+ controller.__callBeforeAction(controller, request, null)
193
+ ).rejects.toThrow('Filter error');
194
+
195
+ // Should send error response
196
+ expect(request.response.writeHead).toHaveBeenCalledWith(500, expect.any(Object));
197
+ });
198
+
199
+ test('should stop filter chain on error', async () => {
200
+ const controller = new TestController();
201
+ const executed = [];
202
+
203
+ controller.beforeAction(['index'], () => {
204
+ executed.push('first');
205
+ throw new Error('Stop here');
206
+ });
207
+
208
+ controller.beforeAction(['index'], () => {
209
+ executed.push('second'); // Should not execute
210
+ });
211
+
212
+ const request = {
213
+ toAction: 'index',
214
+ response: {
215
+ _headerSent: false,
216
+ headersSent: false,
217
+ writeHead: jest.fn(),
218
+ end: jest.fn()
219
+ }
220
+ };
221
+
222
+ try {
223
+ await controller.__callBeforeAction(controller, request, null);
224
+ } catch (e) {}
225
+
226
+ expect(executed).toEqual(['first']);
227
+ });
228
+ });
229
+
230
+ describe('Timeout Protection', () => {
231
+ test('should timeout slow filters', async () => {
232
+ const controller = new TestController();
233
+
234
+ controller.beforeAction(['index'], async () => {
235
+ // Simulate slow operation (6 seconds, timeout is 5 seconds)
236
+ await new Promise(resolve => setTimeout(resolve, 6000));
237
+ });
238
+
239
+ const request = {
240
+ toAction: 'index',
241
+ response: {
242
+ _headerSent: false,
243
+ headersSent: false,
244
+ writeHead: jest.fn(),
245
+ end: jest.fn()
246
+ }
247
+ };
248
+
249
+ await expect(
250
+ controller.__callBeforeAction(controller, request, null)
251
+ ).rejects.toThrow(/timeout/i);
252
+ }, 10000); // Increase test timeout
253
+ });
254
+
255
+ describe('Variable Shadowing Fix', () => {
256
+ test('should not have variable shadowing bugs', async () => {
257
+ const controller = new TestController();
258
+ const actions = ['show', 'edit', 'destroy'];
259
+
260
+ // This used to cause bugs due to variable shadowing
261
+ controller.beforeAction(actions, (req) => {
262
+ // Action list should be properly iterated
263
+ });
264
+
265
+ const request = {
266
+ toAction: 'edit',
267
+ response: { _headerSent: false, headersSent: false }
268
+ };
269
+
270
+ // Should execute without errors
271
+ await expect(
272
+ controller.__callBeforeAction(controller, request, null)
273
+ ).resolves.not.toThrow();
274
+ });
275
+ });
276
+ });
@@ -0,0 +1,214 @@
1
+ // HTTPS and Open Redirect Protection Tests
2
+ const master = require('../../MasterControl');
3
+ require('../../MasterAction');
4
+
5
+ describe('HTTPS and Open Redirect Protection', () => {
6
+
7
+ class MockController {
8
+ constructor() {
9
+ Object.assign(this, master.controllerExtensions);
10
+ this.__requestObject = {
11
+ request: {
12
+ connection: {},
13
+ headers: {}
14
+ },
15
+ response: {
16
+ _headerSent: false,
17
+ headersSent: false,
18
+ writeHead: jest.fn(),
19
+ end: jest.fn(),
20
+ setHeader: jest.fn()
21
+ },
22
+ pathName: '/login'
23
+ };
24
+ }
25
+
26
+ redirectTo(url) {
27
+ this.__requestObject.response.writeHead(302, { 'Location': url });
28
+ this.__requestObject.response.end();
29
+ }
30
+
31
+ returnError(code, message) {
32
+ this.__requestObject.response.writeHead(code, { 'Content-Type': 'application/json' });
33
+ this.__requestObject.response.end(JSON.stringify({ error: message }));
34
+ }
35
+ }
36
+
37
+ describe('requireHTTPS() - Open Redirect Fix', () => {
38
+ beforeEach(() => {
39
+ // Setup test environment
40
+ master.env = master.env || {};
41
+ master.env.server = {
42
+ hostname: 'example.com',
43
+ httpsPort: 443
44
+ };
45
+ });
46
+
47
+ test('should NOT use Host header from request', () => {
48
+ const controller = new MockController();
49
+ controller.__requestObject.request.connection.encrypted = false;
50
+ controller.__requestObject.request.headers.host = 'evil.com';
51
+
52
+ controller.requireHTTPS();
53
+
54
+ // Should redirect to configured host, NOT Host header
55
+ const writeHeadCalls = controller.__requestObject.response.writeHead.mock.calls;
56
+ const redirectCall = writeHeadCalls.find(call => call[0] === 302);
57
+
58
+ expect(redirectCall).toBeTruthy();
59
+ expect(redirectCall[1].Location).toBe('https://example.com/login');
60
+ expect(redirectCall[1].Location).not.toContain('evil.com');
61
+ });
62
+
63
+ test('should use configured hostname', () => {
64
+ const controller = new MockController();
65
+ controller.__requestObject.request.connection.encrypted = false;
66
+
67
+ master.env.server.hostname = 'myapp.com';
68
+
69
+ controller.requireHTTPS();
70
+
71
+ const writeHeadCalls = controller.__requestObject.response.writeHead.mock.calls;
72
+ const redirectCall = writeHeadCalls.find(call => call[0] === 302);
73
+
74
+ expect(redirectCall[1].Location).toBe('https://myapp.com/login');
75
+ });
76
+
77
+ test('should include port if not 443', () => {
78
+ const controller = new MockController();
79
+ controller.__requestObject.request.connection.encrypted = false;
80
+
81
+ master.env.server.hostname = 'example.com';
82
+ master.env.server.httpsPort = 8443;
83
+
84
+ controller.requireHTTPS();
85
+
86
+ const writeHeadCalls = controller.__requestObject.response.writeHead.mock.calls;
87
+ const redirectCall = writeHeadCalls.find(call => call[0] === 302);
88
+
89
+ expect(redirectCall[1].Location).toBe('https://example.com:8443/login');
90
+ });
91
+
92
+ test('should return error if hostname not configured', () => {
93
+ const controller = new MockController();
94
+ controller.__requestObject.request.connection.encrypted = false;
95
+
96
+ master.env.server.hostname = 'localhost';
97
+
98
+ const result = controller.requireHTTPS();
99
+
100
+ expect(result).toBe(false);
101
+ expect(controller.__requestObject.response.writeHead).toHaveBeenCalledWith(500, expect.any(Object));
102
+ });
103
+
104
+ test('should allow request if already HTTPS', () => {
105
+ const controller = new MockController();
106
+ controller.__requestObject.request.connection.encrypted = true;
107
+
108
+ const result = controller.requireHTTPS();
109
+
110
+ expect(result).toBe(true);
111
+ expect(controller.__requestObject.response.writeHead).not.toHaveBeenCalled();
112
+ });
113
+
114
+ test('should detect HTTPS from X-Forwarded-Proto header', () => {
115
+ const controller = new MockController();
116
+ controller.__requestObject.request.connection.encrypted = false;
117
+ controller.__requestObject.request.headers['x-forwarded-proto'] = 'https';
118
+
119
+ const result = controller.requireHTTPS();
120
+
121
+ expect(result).toBe(true);
122
+ });
123
+ });
124
+
125
+ describe('isSecure()', () => {
126
+ test('should return true for encrypted connection', () => {
127
+ const controller = new MockController();
128
+ controller.__requestObject.request.connection.encrypted = true;
129
+
130
+ expect(controller.isSecure()).toBe(true);
131
+ });
132
+
133
+ test('should return true for X-Forwarded-Proto: https', () => {
134
+ const controller = new MockController();
135
+ controller.__requestObject.request.headers['x-forwarded-proto'] = 'https';
136
+
137
+ expect(controller.isSecure()).toBe(true);
138
+ });
139
+
140
+ test('should return false for HTTP', () => {
141
+ const controller = new MockController();
142
+ controller.__requestObject.request.connection.encrypted = false;
143
+ controller.__requestObject.request.headers['x-forwarded-proto'] = 'http';
144
+
145
+ expect(controller.isSecure()).toBe(false);
146
+ });
147
+ });
148
+
149
+ describe('Real-World Attack Scenarios', () => {
150
+ beforeEach(() => {
151
+ master.env = master.env || {};
152
+ master.env.server = {
153
+ hostname: 'legitimate.com',
154
+ httpsPort: 443
155
+ };
156
+ });
157
+
158
+ test('should prevent phishing via Host header manipulation', () => {
159
+ const controller = new MockController();
160
+ controller.__requestObject.request.connection.encrypted = false;
161
+
162
+ // Attacker sets malicious Host header
163
+ controller.__requestObject.request.headers.host = 'phishing-site.com';
164
+ controller.__requestObject.pathName = '/login';
165
+
166
+ controller.requireHTTPS();
167
+
168
+ // Should redirect to legitimate site, not attacker's
169
+ const writeHeadCalls = controller.__requestObject.response.writeHead.mock.calls;
170
+ const redirectCall = writeHeadCalls.find(call => call[0] === 302);
171
+
172
+ expect(redirectCall[1].Location).toBe('https://legitimate.com/login');
173
+ expect(redirectCall[1].Location).not.toContain('phishing-site.com');
174
+ });
175
+
176
+ test('should prevent redirect to external domain', () => {
177
+ const controller = new MockController();
178
+ controller.__requestObject.request.connection.encrypted = false;
179
+
180
+ // Attacker tries various Host header values
181
+ const maliciousHosts = [
182
+ 'evil.com',
183
+ 'attacker.net',
184
+ 'phishing.org',
185
+ 'legitimate.com.evil.com'
186
+ ];
187
+
188
+ maliciousHosts.forEach(host => {
189
+ controller.__requestObject.request.headers.host = host;
190
+ controller.__requestObject.response.writeHead.mockClear();
191
+
192
+ controller.requireHTTPS();
193
+
194
+ const writeHeadCalls = controller.__requestObject.response.writeHead.mock.calls;
195
+ const redirectCall = writeHeadCalls.find(call => call[0] === 302);
196
+
197
+ expect(redirectCall[1].Location).toBe('https://legitimate.com/login');
198
+ });
199
+ });
200
+
201
+ test('should preserve original path in redirect', () => {
202
+ const controller = new MockController();
203
+ controller.__requestObject.request.connection.encrypted = false;
204
+ controller.__requestObject.pathName = '/admin/users/123';
205
+
206
+ controller.requireHTTPS();
207
+
208
+ const writeHeadCalls = controller.__requestObject.response.writeHead.mock.calls;
209
+ const redirectCall = writeHeadCalls.find(call => call[0] === 302);
210
+
211
+ expect(redirectCall[1].Location).toBe('https://legitimate.com/admin/users/123');
212
+ });
213
+ });
214
+ });