aiwaf 1.2.1 → 1.2.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.
@@ -19,6 +19,32 @@ const SHIPPED_MODEL_SHA256 = '56254f9bdeba0f96bed3c72ce88ed9f1e5ad552d7510c84742
19
19
  const SHIPPED_MODEL = path.join(__dirname, '..', 'resources', 'model.json');
20
20
 
21
21
  /** What the regular middleware would load as its anomaly model, read without loading it. */
22
+ /** Path rules whose rate limits the native engine can apply; the others are reported. */
23
+ function nativePathRules(rules, note) {
24
+ if (rules == null) return [];
25
+ if (!Array.isArray(rules)) {
26
+ note('AIWAF_PATH_RULES', 'not carried', 'It isn\'t a list of rules.');
27
+ return [];
28
+ }
29
+ const { rateOverrides } = require('./nativePipeline');
30
+ return rules.flatMap(rule => {
31
+ if (!rule || typeof rule !== 'object' || Array.isArray(rule)) {
32
+ note('AIWAF_PATH_RULES', 'not carried', `A path rule must be an object, not ${JSON.stringify(rule)}.`);
33
+ return [];
34
+ }
35
+ let reason = null;
36
+ try {
37
+ const limits = rateOverrides(rule.RATE_LIMIT || rule.rate_limit || {});
38
+ if ((limits.window !== undefined && !(limits.window > 0)) || (limits.max !== undefined && !(limits.max > 0))
39
+ || (limits.flood !== undefined && !(limits.flood > 0))) reason = 'the native pipeline needs a positive window and limits';
40
+ } catch (error) { reason = error.message; }
41
+ if (!reason) return [rule];
42
+ note('AIWAF_PATH_RULES', 'not carried', `The RATE_LIMIT for ${JSON.stringify(rule.PREFIX ?? rule.prefix)} isn't used natively: ${reason}.`);
43
+ const { RATE_LIMIT: _a, rate_limit: _b, ...rest } = rule;
44
+ return [rest];
45
+ });
46
+ }
47
+
22
48
  function settingsModel(opts) {
23
49
  if ((opts.AIWAF_MODEL_STORAGE || 'file') !== 'file') return { kind: 'storage' };
24
50
  const file = opts.AIWAF_MODEL_PATH || SHIPPED_MODEL;
@@ -31,35 +57,45 @@ function settingsModel(opts) {
31
57
  } catch (_) { return { kind: 'unreadable', file }; }
32
58
  }
33
59
 
60
+ // Profile values an older aiwaf-wasm can't take, with the feature that adds them and the value
61
+ // the converter writes for the regular defaults. An older engine runs without them only then,
62
+ // keeping the behavior it always had.
63
+ // The regular header check skips these, unless AIWAF_STATIC_EXTENSIONS or AIWAF_STATIC_PATHS
64
+ // replace them (js/lib/headerValidation.js).
65
+ const REGULAR_STATIC_EXTENSIONS = ['.css', '.js', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg', '.woff', '.woff2', '.ttf'];
66
+ const REGULAR_STATIC_PATHS = ['/static/', '/media/', '/assets/', '/favicon.ico'];
67
+ const LEGACY_DEFAULTS = {
68
+ header_bytes_without_prefix: ['header_limits', true],
69
+ blocked_user_agents: ['header_limits', normalizeSettings({}).AIWAF_BLOCKED_USER_AGENTS.map(agent => String(agent).toLowerCase())],
70
+ login_prefixes: ['login_prefixes', [].concat(normalizeSettings({}).AIWAF_LOGIN_PATH_PREFIXES || [])],
71
+ header_max_bytes: ['header_limits'],
72
+ header_max_count: ['header_limits'],
73
+ header_max_user_agent: ['header_limits'],
74
+ header_max_accept: ['header_limits'],
75
+ exempt_keywords: ['keyword_exemptions'],
76
+ allowed_path_keywords: ['keyword_exemptions'],
77
+ post_only_suffixes: ['post_only_suffixes'],
78
+ required_headers_by_method: ['method_headers'],
79
+ // An older engine checks headers its own way when on, and not at all when off.
80
+ header_policy: ['header_policy', 'node', profile => {
81
+ if (profile.header_policy !== 'node_ua') return profile.header_policy === 'node';
82
+ profile.enabled = (profile.enabled || []).filter(stage => stage !== 'header_validation');
83
+ return true;
84
+ }],
85
+ header_skip_extensions: ['header_policy', REGULAR_STATIC_EXTENSIONS],
86
+ header_skip_paths: ['header_policy', REGULAR_STATIC_PATHS],
87
+ header_wasm_check: ['header_policy', true],
88
+ learn_context: ['learn_context', 'node'],
89
+ learn_scan_patterns: ['learn_context', [...require('./trainingLogic').SCANNING_PATTERNS]],
90
+ learn_static_keywords: ['learn_context', [...require('./featureUtils').STATIC_KW]],
91
+ suspicious_user_agents: ['user_agent_lists'],
92
+ legitimate_bots: ['user_agent_lists']
93
+ };
34
94
  const STAGES = ['geo_block', 'ip_keyword_block', 'rate_limit', 'ai_anomaly', 'honeypot', 'uuid_tamper', 'header_validation', 'logging'];
35
95
  const PATTERN = /[*?[]/;
36
96
  // Options with no native equivalent, reported when they differ from the regular defaults.
37
97
  const NOT_CARRIED = {
38
- AIWAF_ALLOWED_PATH_KEYWORDS: 'The native pipeline has its own legitimate_keywords list.',
39
- AIWAF_EXEMPT_KEYWORDS: 'The native pipeline has no exempt keywords.',
40
- AIWAF_LOGIN_PATH_PREFIXES: 'The native pipeline treats paths under /login and /admin/login as login forms.',
41
- AIWAF_POST_ONLY_SUFFIXES: 'The native method policy is allowed_methods only.',
42
- AIWAF_MAX_HEADER_BYTES: 'The native header limits are fixed.',
43
- AIWAF_MAX_HEADER_COUNT: 'The native header limits are fixed.',
44
- AIWAF_MAX_USER_AGENT_LENGTH: 'The native header limits are fixed.',
45
- AIWAF_MAX_ACCEPT_LENGTH: 'The native header limits are fixed.',
46
- AIWAF_BLOCKED_USER_AGENTS: 'The native header check has its own list of scanner user agents.',
47
- AIWAF_GEO_MMDB_PATH: 'Pass a countryLookup(req) option to the native pipeline instead.',
48
- AIWAF_GEO_CACHE_SECONDS: 'Country lookups come from countryLookup(req).',
49
- AIWAF_GEO_CACHE_PREFIX: 'Country lookups come from countryLookup(req).',
50
- AIWAF_MODEL_STORAGE: 'The native pipeline loads a model from a file only; pass a model option instead.',
51
- AIWAF_MODEL_STORAGE_FALLBACK: 'The native pipeline loads a model from a file only; pass a model option instead.',
52
- AIWAF_MODEL_CACHE_KEY: 'Pass a model option to the native pipeline instead.',
53
- AIWAF_MODEL_CACHE_TTL: 'Pass a model option to the native pipeline instead.',
54
- AIWAF_MIDDLEWARE_LOG_PATH: 'Native logs go to logPath, by default native_requests.csv in dataDir.',
55
- AIWAF_MIDDLEWARE_LOG_DB: 'The native pipeline logs to a CSV file only.',
56
- AIWAF_MIDDLEWARE_LOG_CSV: 'The native pipeline logs to a CSV file only.',
57
- AIWAF_MIDDLEWARE_LOG_CSV_PATH: 'Native logs go to logPath, by default native_requests.csv in dataDir.',
58
- AIWAF_CAPTURE_EXTENDED_REQUEST_INFO: 'The native log has fixed columns.',
59
- AIWAF_EXTENDED_INFO_MAX_HEADERS: 'The native log has fixed columns.',
60
- AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH: 'The native log has fixed columns.',
61
98
  AIWAF_DYNAMIC_KEYWORDS_DB: 'The native pipeline reads learned keywords from the keyword store.',
62
- AIWAF_MIN_AI_LOGS: 'Training settings don\'t apply to request handling.',
63
99
  AIWAF_ROUTE_PLAN_VERSION: 'The native pipeline compiles path rules once at startup.',
64
100
  AIWAF_FORCE_JSON_ERRORS: 'Native responses are always JSON.'
65
101
  };
@@ -70,7 +106,14 @@ const CARRIED = ['WINDOW_SEC', 'MAX_REQ', 'FLOOD_REQ', 'AIWAF_MIN_FORM_TIME', 'A
70
106
  'AIWAF_GEO_BLOCK_ENABLED', 'AIWAF_GEO_ALLOW_COUNTRIES', 'AIWAF_GEO_BLOCK_COUNTRIES', 'AIWAF_HEADER_VALIDATION',
71
107
  'AIWAF_REQUIRED_HEADERS', 'AIWAF_HEADER_QUALITY_MIN_SCORE', 'AIWAF_EXEMPT_PATHS', 'AIWAF_EXEMPT_IPS',
72
108
  'AIWAF_MIDDLEWARES', 'AIWAF_DISABLE_MIDDLEWARES', 'AIWAF_MIDDLEWARE_LOGGING', 'AIWAF_PATH_RULES',
73
- 'AIWAF_PATH_MANIFEST', 'AIWAF_INJECTION_RISK_MODE', 'dynamicTopN', 'AIWAF_EXEMPTIONS_DB', 'AIWAF_TRUSTED_PROXIES'];
109
+ 'AIWAF_PATH_MANIFEST', 'AIWAF_INJECTION_RISK_MODE', 'dynamicTopN', 'AIWAF_EXEMPTIONS_DB', 'AIWAF_TRUSTED_PROXIES',
110
+ 'AIWAF_GEO_MMDB_PATH', 'AIWAF_GEO_CACHE_SECONDS', 'AIWAF_GEO_CACHE_PREFIX', 'AIWAF_LOGIN_PATH_PREFIXES',
111
+ 'AIWAF_MAX_HEADER_BYTES', 'AIWAF_MAX_HEADER_COUNT', 'AIWAF_MAX_USER_AGENT_LENGTH', 'AIWAF_MAX_ACCEPT_LENGTH',
112
+ 'AIWAF_BLOCKED_USER_AGENTS', 'AIWAF_ALLOWED_PATH_KEYWORDS', 'AIWAF_EXEMPT_KEYWORDS', 'AIWAF_POST_ONLY_SUFFIXES',
113
+ 'AIWAF_MODEL_STORAGE', 'AIWAF_MODEL_STORAGE_FALLBACK', 'AIWAF_MODEL_CACHE_KEY', 'AIWAF_MODEL_CACHE_TTL',
114
+ 'AIWAF_MIDDLEWARE_LOG_PATH', 'AIWAF_MIDDLEWARE_LOG_DB', 'AIWAF_MIDDLEWARE_LOG_CSV', 'AIWAF_MIDDLEWARE_LOG_CSV_PATH',
115
+ 'AIWAF_CAPTURE_EXTENDED_REQUEST_INFO', 'AIWAF_EXTENDED_INFO_MAX_HEADERS', 'AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH',
116
+ 'AIWAF_MIN_AI_LOGS'];
74
117
  // Where settingsCompat reads each number from, in the same order, so unreadable values can be reported.
75
118
  const NUMBER_SOURCES = {
76
119
  WINDOW_SEC: ['WINDOW_SEC', 'windowSec', 'AIWAF_WINDOW_SECONDS', 'env:AIWAF_RATE_WINDOW'],
@@ -96,35 +139,111 @@ function nativeOptionsFromSettings(rawOpts = {}) {
96
139
  profile.rate_window = opts.WINDOW_SEC;
97
140
  profile.rate_max = opts.MAX_REQ;
98
141
  profile.rate_flood = opts.FLOOD_REQ;
99
- if (profile.rate_flood < profile.rate_max) {
142
+ // Values the native engine can't take are reported and left at its defaults. A count over a
143
+ // fractional limit is the same as over its whole part, as the regular comparisons work.
144
+ const unusable = (key, setting, reason) => {
145
+ delete profile[key];
146
+ note(setting, 'not carried', `The native pipeline needs ${reason}, so its default applies.`);
147
+ };
148
+ if (!(Number(profile.rate_window) > 0)) unusable('rate_window', 'WINDOW_SEC', 'a positive window');
149
+ for (const [key, setting] of [['rate_max', 'MAX_REQ'], ['rate_flood', 'FLOOD_REQ']]) {
150
+ if (Number.isFinite(Number(profile[key])) && Math.floor(profile[key]) >= 1) profile[key] = Math.floor(profile[key]);
151
+ else unusable(key, setting, 'a limit of at least 1');
152
+ }
153
+ if (profile.rate_max !== undefined && profile.rate_flood !== undefined && profile.rate_flood < profile.rate_max) {
100
154
  profile.rate_max = profile.rate_flood;
101
- note('MAX_REQ', 'changed', `It's above FLOOD_REQ (${profile.rate_flood}), so requests were flood-blocked first. The native limit is ${profile.rate_flood}.`);
155
+ note('MAX_REQ', 'carried', `It's above FLOOD_REQ (${profile.rate_flood}), so requests are flood-blocked first. The native limit is ${profile.rate_flood}, which blocks at the same point.`);
102
156
  }
103
157
  if (profile.rate_flood > 100000) {
104
158
  profile.rate_flood = 100000;
105
159
  note('FLOOD_REQ', 'changed', 'The native flood threshold is at most 100000.');
106
160
  }
107
- profile.min_form_time = opts.AIWAF_MIN_FORM_TIME;
161
+ // A negative minimum form time never blocks, as 0 doesn't.
162
+ profile.min_form_time = Number.isFinite(Number(opts.AIWAF_MIN_FORM_TIME)) ? Math.max(0, Number(opts.AIWAF_MIN_FORM_TIME)) : 1;
108
163
  if (opts.AIWAF_MAX_PAGE_TIME > 0) profile.max_page_time = opts.AIWAF_MAX_PAGE_TIME;
109
164
  else note('AIWAF_MAX_PAGE_TIME', 'not carried', 'The native page expiry must be positive, so its default applies.');
110
165
  profile.honeypot_field = opts.HONEYPOT_FIELD ? String(opts.HONEYPOT_FIELD) : '';
111
166
  profile.allowed_methods = opts.AIWAF_METHOD_POLICY_ENABLED === true
112
167
  ? (opts.AIWAF_ALLOWED_METHODS || []).map(method => String(method).toUpperCase()) : [];
113
- profile.static_keywords = [...(opts.staticKeywords || [])].map(String);
168
+ // With the method policy, a GET to a post-only path is refused. The regular check lowercases
169
+ // the path, so a suffix with capitals never matches there.
170
+ const postOnly = opts.AIWAF_METHOD_POLICY_ENABLED === true
171
+ ? [].concat(opts.AIWAF_POST_ONLY_SUFFIXES || []).map(String).filter(suffix => suffix === suffix.toLowerCase()) : [];
172
+ if (postOnly.length) profile.post_only_suffixes = postOnly;
173
+ // A keyword exempt by name, or any keyword on a path with an allowed fragment, doesn't block.
174
+ for (const [key, setting] of [['exempt_keywords', 'AIWAF_EXEMPT_KEYWORDS'], ['allowed_path_keywords', 'AIWAF_ALLOWED_PATH_KEYWORDS']]) {
175
+ const values = [].concat(opts[setting] || []).map(value => String(value).toLowerCase());
176
+ if (values.length) profile[key] = values;
177
+ }
178
+ const list = (value, setting) => {
179
+ if (value == null) return [];
180
+ if (Array.isArray(value)) return value.map(String);
181
+ if (typeof value === 'string') return value.split(',').map(item => item.trim()).filter(Boolean);
182
+ note(setting, 'not carried', 'It isn\'t a list, so the native default applies.');
183
+ return null;
184
+ };
185
+ const keywords = list(opts.staticKeywords, 'staticKeywords');
186
+ if (keywords) profile.static_keywords = keywords;
114
187
  profile.learning = opts.AIWAF_ENABLE_KEYWORD_LEARNING !== false;
115
- profile.geo_allow = [...(opts.AIWAF_GEO_ALLOW_COUNTRIES || [])];
116
- profile.geo_block = [...(opts.AIWAF_GEO_BLOCK_COUNTRIES || [])];
188
+ for (const [key, setting] of [['geo_allow', 'AIWAF_GEO_ALLOW_COUNTRIES'], ['geo_block', 'AIWAF_GEO_BLOCK_COUNTRIES']]) {
189
+ const countries = list(opts[setting], setting);
190
+ if (countries) profile[key] = countries;
191
+ }
117
192
  const required = opts.AIWAF_REQUIRED_HEADERS || [];
118
193
  if (required && typeof required === 'object' && !Array.isArray(required)) {
119
- profile.required_headers = (required.DEFAULT || []).map(headerName);
120
- note('AIWAF_REQUIRED_HEADERS', 'changed', 'Per-method lists aren\'t supported natively, so its DEFAULT list applies to every method.');
194
+ // Per method, falling back to DEFAULT, as the regular check reads them. It looks a method
195
+ // up as uppercase, so a lowercase key never applies there.
196
+ profile.required_headers = [].concat(required.DEFAULT || []).map(headerName);
197
+ const byMethod = Object.entries(required).filter(([method, list]) => method !== 'DEFAULT'
198
+ && method === method.toUpperCase() && list);
199
+ if (byMethod.length) {
200
+ profile.required_headers_by_method = Object.fromEntries(byMethod.map(([method, list]) => [method, [].concat(list).map(headerName)]));
201
+ }
121
202
  } else {
122
203
  profile.required_headers = [].concat(required).map(headerName);
123
204
  }
205
+ // The header caps, blocked user agents and login forms the regular checks use. A newer
206
+ // aiwaf-wasm takes them; an older one keeps its own, which the adapter allows only when these
207
+ // are the regular defaults (see LEGACY_DEFAULTS).
208
+ for (const [key, setting] of [['header_max_bytes', 'AIWAF_MAX_HEADER_BYTES'], ['header_max_count', 'AIWAF_MAX_HEADER_COUNT'],
209
+ ['header_max_user_agent', 'AIWAF_MAX_USER_AGENT_LENGTH'], ['header_max_accept', 'AIWAF_MAX_ACCEPT_LENGTH']]) {
210
+ if (same(opts[setting], defaults[setting])) continue;
211
+ if (Number.isInteger(opts[setting]) && opts[setting] >= 0) profile[key] = opts[setting];
212
+ else note(setting, 'not carried', 'The native header caps are whole numbers of zero or more, so the native default applies.');
213
+ }
214
+ // Node.js counts header names as sent (user-agent), without Python's HTTP_.
215
+ profile.header_bytes_without_prefix = true;
216
+ // Keywords are learned from 404s as the regular middleware learns them.
217
+ profile.learn_context = 'node';
218
+ profile.learn_scan_patterns = [...require('./trainingLogic').SCANNING_PATTERNS];
219
+ profile.learn_static_keywords = [...require('./featureUtils').STATIC_KW];
220
+ // Node.js's own header check, then aiwaf-wasm's, as the regular middleware runs them.
221
+ const wasmHeaderCheck = rawOpts.AIWAF_WASM_VALIDATION !== false && rawOpts.AIWAF_WASM_HEADER_VALIDATION !== false;
222
+ profile.header_policy = opts.AIWAF_HEADER_VALIDATION ? 'node' : 'node_ua';
223
+ profile.header_skip_extensions = [].concat(rawOpts.AIWAF_STATIC_EXTENSIONS || REGULAR_STATIC_EXTENSIONS).map(value => String(value).toLowerCase());
224
+ profile.header_skip_paths = [].concat(rawOpts.AIWAF_STATIC_PATHS || REGULAR_STATIC_PATHS).map(value => String(value).toLowerCase());
225
+ profile.header_wasm_check = wasmHeaderCheck;
226
+ // The app's own User-Agent lists are tested by the adapter, in JavaScript, exactly as the
227
+ // regular check tests them; the engine takes the verdict.
228
+ const ownAgentLists = ['AIWAF_SUSPICIOUS_USER_AGENTS', 'AIWAF_LEGITIMATE_BOTS'].filter(setting => Array.isArray(rawOpts[setting]));
229
+ for (const setting of ownAgentLists) note(setting, 'carried');
230
+ const userAgentVerdict = ownAgentLists.length ? require('./headerValidation').userAgentVerdict(opts) : null;
231
+ profile.blocked_user_agents = [].concat(opts.AIWAF_BLOCKED_USER_AGENTS || []).map(agent => String(agent).toLowerCase());
232
+ // The regular check lowercases the path, so a prefix with capitals never matches there.
233
+ profile.login_prefixes = [].concat(opts.AIWAF_LOGIN_PATH_PREFIXES || []).map(String)
234
+ .filter(prefix => prefix === prefix.toLowerCase());
124
235
  // With no required headers, the regular check also skips the quality score.
125
- profile.header_min_score = profile.required_headers.length ? opts.AIWAF_HEADER_QUALITY_MIN_SCORE : 0;
126
- profile.sql_mode = String(rawOpts.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
236
+ // Scores are whole numbers, so a fractional minimum is the next whole one.
237
+ const minScore = Number(opts.AIWAF_HEADER_QUALITY_MIN_SCORE);
238
+ if (!profile.required_headers.length && !profile.required_headers_by_method) profile.header_min_score = 0;
239
+ else if (Number.isFinite(minScore) && Math.abs(minScore) < 2 ** 31) profile.header_min_score = Math.ceil(minScore);
240
+ else note('AIWAF_HEADER_QUALITY_MIN_SCORE', 'not carried', 'It isn\'t a usable score, so the native default applies.');
241
+ profile.sql_mode = String(rawOpts.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').trim().toLowerCase();
242
+ if (!['block', 'monitor', 'off'].includes(profile.sql_mode)) unusable('sql_mode', 'AIWAF_SQL_INJECTION_MODE', 'block, monitor or off');
127
243
  profile.max_bytes = Number(rawOpts.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
244
+ if (!(Number.isInteger(profile.max_bytes) && profile.max_bytes >= 1 && profile.max_bytes <= 1048576)) {
245
+ unusable('max_bytes', 'AIWAF_PAYLOAD_MAX_BYTES', 'a whole number of bytes from 1 to 1048576');
246
+ }
128
247
 
129
248
  const paths = (opts.AIWAF_EXEMPT_PATHS || []).map(String);
130
249
  profile.exempt_paths = paths.filter(path => !PATTERN.test(path));
@@ -149,26 +268,47 @@ function nativeOptionsFromSettings(rawOpts = {}) {
149
268
  const auto = isAutoSelection(requested);
150
269
  const explicit = key => Object.hasOwn(rawOpts, key) || process.env[key] !== undefined;
151
270
  const logging = opts.AIWAF_MIDDLEWARE_LOGGING || (auto && enabled.has('logging') && !explicit('AIWAF_MIDDLEWARE_LOGGING'));
152
- if (!opts.AIWAF_HEADER_VALIDATION) enabled.delete('header_validation');
271
+ // With AIWAF_HEADER_VALIDATION off, the regular middleware still runs aiwaf-wasm's User-Agent
272
+ // check where the header stage applies, unless its aiwaf-wasm checks are off too.
273
+ if (!opts.AIWAF_HEADER_VALIDATION && !wasmHeaderCheck) enabled.delete('header_validation');
153
274
  if (!logging) enabled.delete('logging');
154
275
  profile.enabled = STAGES.filter(stage => enabled.has(stage));
155
- if (enabled.has('logging')) {
156
- note('AIWAF_MIDDLEWARE_LOGGING', 'changed', 'Requests are logged to native_requests.csv in dataDir, with the native log\'s columns.');
157
- }
276
+ // Requests are logged by the regular request logger, beside the native pipeline, to the same
277
+ // JSONL, CSV or database log, with the same columns.
278
+ const regularLog = enabled.has('logging');
279
+ if (regularLog) profile.enabled = profile.enabled.filter(stage => stage !== 'logging');
158
280
  // The regular middleware's stores: the same blocks, exemptions, learned keywords and blocked
159
281
  // countries. An older aiwaf-wasm can't use them, and then the adapter keeps its own in dataDir.
160
282
  note('stores', 'carried');
161
283
 
162
284
  const options = {
163
- stores: regularStores({ dynamicTopN: opts.dynamicTopN, exemptionsDb: opts.AIWAF_EXEMPTIONS_DB }),
285
+ stores: regularStores({ dynamicTopN: opts.dynamicTopN, exemptionsDb: opts.AIWAF_EXEMPTIONS_DB, extendedInfo: {
286
+ enabled: opts.AIWAF_CAPTURE_EXTENDED_REQUEST_INFO,
287
+ maxHeaders: opts.AIWAF_EXTENDED_INFO_MAX_HEADERS,
288
+ maxValueLength: opts.AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH
289
+ } }),
164
290
  storesFallback: 'csv',
165
291
  rateFailureMode: opts.AIWAF_RATE_CACHE_FAILURE_MODE,
166
292
  // Resolved as the regular middleware resolves it, with its default trusted proxies.
167
293
  trustedProxies: opts.AIWAF_TRUSTED_PROXIES ?? 'default',
168
- pathRules: opts.AIWAF_PATH_RULES || [],
294
+ pathRules: nativePathRules(opts.AIWAF_PATH_RULES, note),
169
295
  manifestPath: opts.AIWAF_PATH_MANIFEST,
170
296
  injectionRiskMode: opts.AIWAF_INJECTION_RISK_MODE
171
297
  };
298
+ if (options.injectionRiskMode != null) {
299
+ const mode = String(options.injectionRiskMode).trim().toLowerCase();
300
+ if (['block', 'log', 'off'].includes(mode)) options.injectionRiskMode = mode;
301
+ else {
302
+ delete options.injectionRiskMode;
303
+ note('AIWAF_INJECTION_RISK_MODE', 'not carried', 'It must be block, log or off, so the native default applies.');
304
+ }
305
+ }
306
+ if (profile.enabled.includes('geo_block')) {
307
+ // Countries come from where the regular geo check finds them: its geoResolver, which the
308
+ // request waits for, or else the MMDB database, then the x-country-code header.
309
+ options.countryLookup = require('./geoBlocker').createCountryLookup(opts, options.trustedProxies, rawOpts.geoResolver);
310
+ if (typeof rawOpts.geoResolver === 'function') note('geoResolver', 'carried');
311
+ }
172
312
  // The regular UUID check matches one segment under uuidRoutePrefix, and asks uuidResolver.
173
313
  const uuidPrefix = rawOpts.uuidRoutePrefix || '/user';
174
314
  profile.uuid_prefix = `${String(uuidPrefix).replace(/\/+$/, '')}/`;
@@ -188,15 +328,17 @@ function nativeOptionsFromSettings(rawOpts = {}) {
188
328
  note('cache', 'not carried', 'Shared native rate limits need a node-redis or ioredis client, so rate limits are counted in each worker.');
189
329
  }
190
330
  if (opts.AIWAF_RATE_CACHE_FAILURE_MODE !== 'closed') note('AIWAF_RATE_CACHE_FAILURE_MODE', 'carried');
191
- const model = settingsModel(opts);
192
- if (model.kind === 'wasm') {
193
- options.modelFile = model.file;
194
- note('AIWAF_MODEL_PATH', 'carried');
195
- } else if (model.kind === 'js' || model.kind === 'unreadable') {
196
- note('AIWAF_MODEL_PATH', 'not carried', `${model.file} is in an older model format the native pipeline can't load. Retrain with: aiwaf train`);
197
- } else if (model.kind === 'none' && opts.AIWAF_MODEL_PATH) {
198
- note('AIWAF_MODEL_PATH', 'carried', 'No model file exists there yet, so anomaly detection runs without a model, as in the regular middleware.');
331
+ if (regularLog) options.regularLog = { ...opts, AIWAF_MIDDLEWARE_LOGGING: true };
332
+ if (userAgentVerdict) options.userAgentVerdict = userAgentVerdict;
333
+ // Anomalies are checked by the regular anomaly check, after the engine's stages, with the
334
+ // regular model, wherever the app keeps it and in whatever format.
335
+ const regularAnomaly = profile.enabled.includes('ai_anomaly');
336
+ if (regularAnomaly) {
337
+ options.regularAnomaly = opts;
338
+ profile.enabled = profile.enabled.filter(stage => stage !== 'ai_anomaly');
199
339
  }
340
+ // The regular anomaly check loads the model itself; without that stage no model is used.
341
+ if (opts.AIWAF_MODEL_PATH) note('AIWAF_MODEL_PATH', 'carried');
200
342
  for (const [key, reason] of Object.entries(NOT_CARRIED)) {
201
343
  if (!same(opts[key], defaults[key])) note(key, 'not carried', reason);
202
344
  }
@@ -239,4 +381,4 @@ function nativeOptionsFromSettings(rawOpts = {}) {
239
381
  };
240
382
  }
241
383
 
242
- module.exports = { nativeOptionsFromSettings, settingsModel, SHIPPED_MODEL_SHA256 };
384
+ module.exports = { nativeOptionsFromSettings, settingsModel, SHIPPED_MODEL_SHA256, LEGACY_DEFAULTS };
package/lib/pathRules.js CHANGED
@@ -37,11 +37,18 @@ function normalizePaths(items = []) {
37
37
  return (items || []).map(item => normalizePath(item, false));
38
38
  }
39
39
 
40
+ // Patterns come from configuration, so each is compiled once.
41
+ const compiledWildcards = new Map();
40
42
  function wildcardMatch(pathValue, pattern) {
41
- const escaped = String(pattern)
42
- .replace(/[.+?^${}()|[\]\\]/g, '\\$&')
43
- .replace(/\*/g, '.*');
44
- return new RegExp(`^${escaped}$`).test(pathValue);
43
+ const key = String(pattern);
44
+ let regex = compiledWildcards.get(key);
45
+ if (!regex) {
46
+ const escaped = key.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
47
+ regex = new RegExp(`^${escaped}$`);
48
+ if (compiledWildcards.size >= 1024) compiledWildcards.clear();
49
+ compiledWildcards.set(key, regex);
50
+ }
51
+ return regex.test(pathValue);
45
52
  }
46
53
 
47
54
  function isPathExempt(pathValue, exemptPaths = [], { allowWildcards = true, allowPrefix = true } = {}) {
@@ -101,7 +108,25 @@ function isMiddlewareDisabledForPath(path, rules, middlewareName) {
101
108
  return disabled.some(entry => normalizeMiddlewareName(entry) === target);
102
109
  }
103
110
 
111
+ // Path rules and route markers are fixed once the app runs, so a plan is built once per path
112
+ // and markers, for each rules list. Plans are only read, and getOverrides returns copies.
113
+ const planCaches = new WeakMap();
104
114
  function createRoutePlan(path, rules = [], context = {}) {
115
+ if (!Array.isArray(rules)) return buildRoutePlan(path, rules, context);
116
+ const key = [path, rules.length, context.fullyExempt ? 1 : 0, (context.exemptMiddlewares || []).join(','),
117
+ (context.requiredMiddlewares || []).join(',')].join('\u0000');
118
+ let plans = planCaches.get(rules);
119
+ if (!plans) planCaches.set(rules, plans = new Map());
120
+ let plan = plans.get(key);
121
+ if (!plan) {
122
+ plan = buildRoutePlan(path, rules, context);
123
+ if (plans.size >= 4096) plans.delete(plans.keys().next().value);
124
+ plans.set(key, plan);
125
+ }
126
+ return plan;
127
+ }
128
+
129
+ function buildRoutePlan(path, rules = [], context = {}) {
105
130
  const required = new Set((context.requiredMiddlewares || []).map(normalizeMiddlewareName));
106
131
  const exempt = new Set((context.exemptMiddlewares || []).map(normalizeMiddlewareName));
107
132
  const fullyExempt = !!context.fullyExempt;
@@ -96,8 +96,8 @@ module.exports = {
96
96
  }
97
97
  }
98
98
 
99
- const current = rows();
100
- csvStore.appendRow(csvPath, headers, { id: csvStore.nextId(current), ...payload });
99
+ // IDs only increase, so the last row gives the next one without reading the whole log.
100
+ csvStore.appendRow(csvPath, headers, { id: csvStore.nextId(csvStore.readTailRows(csvPath, headers, 1)), ...payload });
101
101
  },
102
102
 
103
103
  async recent(limit = 5000) {
@@ -105,15 +105,15 @@ module.exports = {
105
105
 
106
106
  if (await initialize()) {
107
107
  try {
108
- return db('request_logs').select('*').orderBy('created_at', 'desc').limit(normalizedLimit);
108
+ return await db('request_logs').select('*').orderBy('created_at', 'desc').limit(normalizedLimit);
109
109
  } catch (err) {
110
110
  dbAvailable = false;
111
111
  }
112
112
  }
113
113
 
114
- return rows()
115
- .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
116
- .slice(0, normalizedLimit);
114
+ // The log is appended in time order, so the newest rows are its last lines.
115
+ return csvStore.readTailRows(csvPath, headers, normalizedLimit)
116
+ .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
117
117
  },
118
118
 
119
119
  async geoSummary(limit = 25) {
@@ -121,7 +121,7 @@ module.exports = {
121
121
 
122
122
  if (await initialize()) {
123
123
  try {
124
- return db('request_logs')
124
+ return await db('request_logs')
125
125
  .select('country')
126
126
  .count({ requests: '*' })
127
127
  .sum({ blocked_count: db.raw('CASE WHEN blocked THEN 1 ELSE 0 END') })
@@ -1,3 +1,5 @@
1
+ const { loginPathPrefixes } = require('./honeypotDefaults');
2
+
1
3
  function firstDefined(...values) {
2
4
  for (const value of values) {
3
5
  if (value !== undefined && value !== null) return value;
@@ -76,7 +78,7 @@ function normalizeSettings(rawOpts = {}) {
76
78
  HONEYPOT_FIELD: firstDefined(rawOpts.HONEYPOT_FIELD, rawOpts.honeypotField, legacy.honeypot?.field),
77
79
  AIWAF_MIN_FORM_TIME: toNumber(firstDefined(rawOpts.AIWAF_MIN_FORM_TIME, rawOpts.minFormTime, legacy.honeypot?.minFormTime, process.env.AIWAF_MIN_FORM_TIME), 0),
78
80
  AIWAF_MAX_PAGE_TIME: toNumber(firstDefined(rawOpts.AIWAF_MAX_PAGE_TIME, rawOpts.maxPageTime, legacy.honeypot?.maxPageTime, process.env.AIWAF_MAX_PAGE_TIME), 3600),
79
- AIWAF_LOGIN_PATH_PREFIXES: toArray(firstDefined(rawOpts.AIWAF_LOGIN_PATH_PREFIXES, rawOpts.loginPathPrefixes, legacy.honeypot?.loginPathPrefixes, process.env.AIWAF_LOGIN_PATH_PREFIXES), undefined),
81
+ AIWAF_LOGIN_PATH_PREFIXES: toArray(firstDefined(rawOpts.AIWAF_LOGIN_PATH_PREFIXES, rawOpts.loginPathPrefixes, legacy.honeypot?.loginPathPrefixes, process.env.AIWAF_LOGIN_PATH_PREFIXES), [...loginPathPrefixes]),
80
82
  AIWAF_POST_ONLY_SUFFIXES: toArray(firstDefined(rawOpts.AIWAF_POST_ONLY_SUFFIXES, rawOpts.postOnlySuffixes, legacy.honeypot?.postOnlySuffixes, process.env.AIWAF_POST_ONLY_SUFFIXES), undefined),
81
83
  AIWAF_ALLOWED_METHODS: toArray(firstDefined(rawOpts.AIWAF_ALLOWED_METHODS, rawOpts.allowedMethods, legacy.honeypot?.allowedMethods, process.env.AIWAF_ALLOWED_METHODS), undefined),
82
84
  AIWAF_METHOD_POLICY_ENABLED: toBool(firstDefined(rawOpts.AIWAF_METHOD_POLICY_ENABLED, rawOpts.methodPolicyEnabled, legacy.honeypot?.methodPolicyEnabled, process.env.AIWAF_METHOD_POLICY_ENABLED), false),
@@ -9,10 +9,16 @@ let config = {
9
9
  uuidResolver: null
10
10
  };
11
11
 
12
+ // The prefix is literal text: escaped, and compiled once per prefix.
13
+ let prefixPattern = { prefix: null, regex: null };
12
14
  function extractUuid(req) {
13
15
  if (req?.params?.uuid) return String(req.params.uuid);
14
16
  const path = String(req.path || req.url || '');
15
- const regex = new RegExp(`^${config.prefix}/([^/]+)$`);
17
+ if (prefixPattern.prefix !== config.prefix) {
18
+ const escaped = String(config.prefix).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
19
+ prefixPattern = { prefix: config.prefix, regex: new RegExp(`^${escaped}/([^/]+)$`) };
20
+ }
21
+ const regex = prefixPattern.regex;
16
22
  const match = path.match(regex);
17
23
  return match ? match[1] : null;
18
24
  }