fakecloud-wafv2 0.20.1

AWS WAF v2 implementation for FakeCloud
Documentation
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! `Wafv2Service` `rule_groups` family — extracted from service.rs by audit-2026-05-19.

use super::*;

impl Wafv2Service {
    pub(super) fn create_rule_group(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let name = require_str_len(&body, "Name", 1, 128)?;
        let scope = require_scope(&body)?;
        let capacity = body
            .get("Capacity")
            .and_then(Value::as_i64)
            .ok_or_else(|| invalid_param("Capacity is required"))?;
        let visibility_config = body
            .get("VisibilityConfig")
            .cloned()
            .ok_or_else(|| invalid_param("VisibilityConfig is required"))?;
        let rules = body
            .get("Rules")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();
        let description = body
            .get("Description")
            .and_then(Value::as_str)
            .map(str::to_owned);
        let custom_response_bodies = parse_custom_response_bodies(body.get("CustomResponseBodies"));
        let available_labels = body
            .get("AvailableLabels")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();
        let consumed_labels = body
            .get("ConsumedLabels")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();
        let tags = parse_tags(body.get("Tags"))?;

        let used = compute_capacity(&rules);
        if used > capacity {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "WAFLimitsExceededException",
                format!("Rules consume {used} WCU but capacity is {capacity}"),
            ));
        }

        let key = (scope.clone(), name.clone());
        let mut state = self.state.write();
        let account = account_mut(&mut state, &req.account_id);
        if account.rule_groups.contains_key(&key) {
            return Err(already_exists(&format!("RuleGroup {name} already exists")));
        }
        let id = synth_uuid();
        let arn = synth_arn(
            &req.account_id,
            &req.region,
            &scope,
            "rulegroup",
            &name,
            &id,
        );
        let lock_token = synth_uuid();
        let label_namespace = format!("awswaf:{}:rulegroup:{name}:", req.account_id);
        let summary =
            rule_group_summary_json(&id, &name, &arn, description.as_deref(), &lock_token);
        let rg = RuleGroup {
            id,
            name,
            arn: arn.clone(),
            scope: scope.clone(),
            capacity,
            description,
            rules,
            visibility_config,
            lock_token,
            label_namespace,
            custom_response_bodies,
            available_labels,
            consumed_labels,
            created_time: Utc::now(),
        };
        account.rule_groups.insert(key, rg);
        if !tags.is_empty() {
            account.tags.insert(arn, tags);
        }
        Ok(AwsResponse::ok_json(json!({ "Summary": summary })))
    }

    pub(super) fn get_rule_group(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let arn_in = body.get("ARN").and_then(Value::as_str).map(str::to_owned);
        let state = self.state.read();
        let account = state
            .accounts
            .get(&req.account_id)
            .ok_or_else(|| not_found("RuleGroup"))?;
        let rg = if let Some(arn) = arn_in.as_deref() {
            account
                .rule_groups
                .values()
                .find(|r| r.arn == arn)
                .ok_or_else(|| not_found("RuleGroup"))?
        } else {
            let name = require_str(&body, "Name")?;
            let scope = require_scope(&body)?;
            account
                .rule_groups
                .get(&(scope, name))
                .ok_or_else(|| not_found("RuleGroup"))?
        };
        Ok(AwsResponse::ok_json(json!({
            "RuleGroup": rule_group_detail_json(rg),
            "LockToken": rg.lock_token,
        })))
    }

    pub(super) fn list_rule_groups(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let scope = require_scope(&body)?;
        validate_opt_limit(&body)?;
        validate_opt_next_marker(&body)?;
        let limit = body.get("Limit").and_then(Value::as_u64).unwrap_or(100) as usize;
        let next_marker = body
            .get("NextMarker")
            .and_then(Value::as_str)
            .map(str::to_owned);
        let state = self.state.read();
        let mut all: Vec<RuleGroup> = state
            .accounts
            .get(&req.account_id)
            .map(|a| {
                a.rule_groups
                    .values()
                    .filter(|x| x.scope == scope)
                    .cloned()
                    .collect()
            })
            .unwrap_or_default();
        all.sort_by(|a, b| a.name.cmp(&b.name));
        let (page, next) = paginate(&all, next_marker.as_deref(), limit);
        let summaries: Vec<Value> = page
            .iter()
            .map(|r| {
                rule_group_summary_json(
                    &r.id,
                    &r.name,
                    &r.arn,
                    r.description.as_deref(),
                    &r.lock_token,
                )
            })
            .collect();
        let mut response = json!({ "RuleGroups": summaries });
        if let Some(t) = next {
            response
                .as_object_mut()
                .unwrap()
                .insert("NextMarker".to_string(), Value::String(t));
        }
        Ok(AwsResponse::ok_json(response))
    }

    pub(super) fn update_rule_group(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let name = require_str(&body, "Name")?;
        let scope = require_scope(&body)?;
        let id_in = require_str(&body, "Id")?;
        let lock_token_in = require_str(&body, "LockToken")?;
        let visibility_config = body
            .get("VisibilityConfig")
            .cloned()
            .ok_or_else(|| invalid_param("VisibilityConfig is required"))?;
        let rules = body
            .get("Rules")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();
        let description = body
            .get("Description")
            .and_then(Value::as_str)
            .map(str::to_owned);
        let mut state = self.state.write();
        let account = account_mut(&mut state, &req.account_id);
        let rg = account
            .rule_groups
            .get_mut(&(scope, name.clone()))
            .ok_or_else(|| not_found("RuleGroup"))?;
        if rg.id != id_in {
            return Err(invalid_param("Id does not match the named RuleGroup"));
        }
        if rg.lock_token != lock_token_in {
            return Err(stale_lock_token());
        }
        let used = compute_capacity(&rules);
        if used > rg.capacity {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "WAFLimitsExceededException",
                format!("Rules consume {used} WCU but capacity is {}", rg.capacity),
            ));
        }
        rg.visibility_config = visibility_config;
        rg.rules = rules;
        rg.description = description;
        if let Some(b) = body.get("CustomResponseBodies") {
            rg.custom_response_bodies = parse_custom_response_bodies(Some(b));
        }
        rg.lock_token = synth_uuid();
        Ok(AwsResponse::ok_json(
            json!({ "NextLockToken": rg.lock_token }),
        ))
    }

    pub(super) fn delete_rule_group(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let name = require_str(&body, "Name")?;
        let scope = require_scope(&body)?;
        let id_in = require_str(&body, "Id")?;
        let lock_token_in = require_str(&body, "LockToken")?;
        let mut state = self.state.write();
        let account = account_mut(&mut state, &req.account_id);
        let key = (scope, name);
        let rg = account
            .rule_groups
            .get(&key)
            .ok_or_else(|| not_found("RuleGroup"))?;
        if rg.id != id_in {
            return Err(invalid_param("Id does not match the named RuleGroup"));
        }
        if rg.lock_token != lock_token_in {
            return Err(stale_lock_token());
        }
        let arn = rg.arn.clone();
        // Reject if any web ACL still references the rule group.
        let referenced = account.web_acls.values().any(|acl| {
            acl.rules.iter().any(|rule| {
                rule.get("Statement")
                    .and_then(|s| s.get("RuleGroupReferenceStatement"))
                    .and_then(|s| s.get("ARN"))
                    .and_then(Value::as_str)
                    == Some(arn.as_str())
            })
        });
        if referenced {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "WAFAssociatedItemException",
                "RuleGroup is referenced by one or more WebACLs",
            ));
        }
        account.rule_groups.remove(&key);
        account.tags.remove(&arn);
        account.permission_policies.remove(&arn);
        Ok(AwsResponse::ok_json(json!({})))
    }

    pub(super) fn describe_all_managed_products(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let _scope = require_scope(&body)?;
        Ok(AwsResponse::ok_json(json!({
            "ManagedProducts": managed_products(),
        })))
    }

    pub(super) fn describe_managed_products_by_vendor(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let vendor = require_str_len(&body, "VendorName", 1, 128)?;
        let _scope = require_scope(&body)?;
        let products: Vec<Value> = managed_products()
            .into_iter()
            .filter(|p| p.get("VendorName").and_then(Value::as_str) == Some(vendor.as_str()))
            .collect();
        Ok(AwsResponse::ok_json(json!({
            "ManagedProducts": products,
        })))
    }

    pub(super) fn describe_managed_rule_group(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let vendor = require_str_len(&body, "VendorName", 1, 128)?;
        let name = require_str_len(&body, "Name", 1, 128)?;
        let _scope = require_scope(&body)?;
        let version =
            opt_str_len(&body, "VersionName", 1, 64)?.unwrap_or_else(|| "Version_1.0".to_string());
        Ok(AwsResponse::ok_json(json!({
            "VersionName": version,
            "SnsTopicArn": Arn::new("sns", "us-east-1", "", &format!("{vendor}-{name}-notifications")).to_string(),
            "Capacity": 50,
            "Rules": managed_rule_summaries(&vendor, &name),
            "LabelNamespace": format!("awswaf:managed:{vendor}:{name}:"),
            "AvailableLabels": [],
            "ConsumedLabels": [],
        })))
    }

    pub(super) fn get_managed_rule_set(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let name = require_str_len(&body, "Name", 1, 128)?;
        let id = require_str_len(&body, "Id", 1, 36)?;
        let _scope = require_scope(&body)?;
        Ok(AwsResponse::ok_json(json!({
            "ManagedRuleSet": {
                "Name": name,
                "Id": id,
                "ARN": Arn::new("wafv2", &req.region, &req.account_id, &format!("managedruleset/{name}/{id}")).to_string(),
                "Description": format!("Managed rule set {name}"),
                "PublishedVersions": {
                    "Version_1.0": {
                        "AssociatedRuleGroupArn": Arn::new("wafv2", &req.region, "aws", &format!("managedrulegroup/{name}")).to_string(),
                        "Capacity": 50,
                        "ForecastedLifetime": 90,
                        "PublishTimestamp": Utc::now().timestamp() as f64,
                        "LastUpdateTimestamp": Utc::now().timestamp() as f64,
                        "ExpiryTimestamp": (Utc::now() + chrono::Duration::days(365)).timestamp() as f64,
                    }
                },
                "RecommendedVersion": "Version_1.0",
                "LabelNamespace": format!("awswaf:managed::{name}:"),
            },
            "LockToken": synth_uuid(),
        })))
    }

    pub(super) fn list_available_managed_rule_groups(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let _scope = require_scope(&body)?;
        validate_opt_limit(&body)?;
        validate_opt_next_marker(&body)?;
        Ok(AwsResponse::ok_json(json!({
            "ManagedRuleGroups": [
                {
                    "VendorName": "AWS",
                    "Name": "AWSManagedRulesCommonRuleSet",
                    "VersioningSupported": true,
                    "Description": "OWASP Top 10 baseline rules",
                },
                {
                    "VendorName": "AWS",
                    "Name": "AWSManagedRulesKnownBadInputsRuleSet",
                    "VersioningSupported": true,
                    "Description": "Block request patterns associated with known exploits",
                },
                {
                    "VendorName": "AWS",
                    "Name": "AWSManagedRulesSQLiRuleSet",
                    "VersioningSupported": true,
                    "Description": "SQL injection patterns",
                },
            ],
        })))
    }

    pub(super) fn list_available_managed_rule_group_versions(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let _vendor = require_str_len(&body, "VendorName", 1, 128)?;
        let name = require_str_len(&body, "Name", 1, 128)?;
        let scope = require_scope(&body)?;
        validate_opt_limit(&body)?;
        validate_opt_next_marker(&body)?;

        // Return the versions actually published via
        // PutManagedRuleSetVersions for this (scope, name) if any exist;
        // otherwise fall back to the documented AWS-vendor sample set.
        let state = self.state.read();
        if let Some(set) = state
            .accounts
            .get(&req.account_id)
            .and_then(|a| a.managed_rule_sets.get(&(scope.clone(), name.clone())))
        {
            let versions: Vec<Value> = set
                .published_versions
                .iter()
                .map(|v| json!({"Name": v, "LastUpdateTimestamp": set.created_time.timestamp() as f64}))
                .collect();
            let current = set
                .recommended_version
                .clone()
                .or_else(|| set.published_versions.last().cloned());
            return Ok(AwsResponse::ok_json(json!({
                "Versions": versions,
                "CurrentDefaultVersion": current,
            })));
        }

        Ok(AwsResponse::ok_json(json!({
            "Versions": [
                {"Name": "Version_1.0", "LastUpdateTimestamp": Utc::now().timestamp() as f64},
                {"Name": "Version_2.0", "LastUpdateTimestamp": Utc::now().timestamp() as f64},
            ],
            "CurrentDefaultVersion": "Version_2.0",
        })))
    }

    pub(super) fn list_managed_rule_sets(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let scope = require_scope(&body)?;
        validate_opt_limit(&body)?;
        validate_opt_next_marker(&body)?;

        // Return the managed rule sets this account has published for the
        // requested scope (via PutManagedRuleSetVersions).
        let state = self.state.read();
        let sets: Vec<Value> = state
            .accounts
            .get(&req.account_id)
            .map(|a| {
                a.managed_rule_sets
                    .values()
                    .filter(|s| s.scope == scope)
                    .map(|s| {
                        json!({
                            "Name": s.name,
                            "Id": s.id,
                            "Description": s.description,
                            "LockToken": s.lock_token,
                            "LabelNamespace": s.label_namespace,
                        })
                    })
                    .collect()
            })
            .unwrap_or_default();
        Ok(AwsResponse::ok_json(json!({ "ManagedRuleSets": sets })))
    }

    pub(super) fn put_managed_rule_set_versions(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let name = require_str(&body, "Name")?;
        fakecloud_core::validation::validate_string_length("Name", &name, 1, 128)?;
        let id = require_str(&body, "Id")?;
        fakecloud_core::validation::validate_string_length("Id", &id, 1, 36)?;
        let lock_token = require_str(&body, "LockToken")?;
        fakecloud_core::validation::validate_string_length("LockToken", &lock_token, 1, 36)?;
        let scope = require_scope(&body)?;
        let recommended_version = match body.get("RecommendedVersion").and_then(Value::as_str) {
            Some(v) => {
                fakecloud_core::validation::validate_string_length("RecommendedVersion", v, 1, 64)?;
                Some(v.to_string())
            }
            None => None,
        };

        // Collect the version names being published (VersionsToPublish is a
        // map of version-name -> {AssociatedRuleGroupArn, ForecastedLifetime}).
        let mut published: Vec<String> = body
            .get("VersionsToPublish")
            .and_then(Value::as_object)
            .map(|m| m.keys().cloned().collect())
            .unwrap_or_default();
        published.sort();

        let next_lock_token = synth_uuid();
        let mut state = self.state.write();
        let account = account_mut(&mut state, &req.account_id);
        let key = (scope.clone(), name.clone());
        let entry =
            account
                .managed_rule_sets
                .entry(key)
                .or_insert_with(|| crate::state::ManagedRuleSet {
                    id: id.clone(),
                    name: name.clone(),
                    scope: scope.clone(),
                    description: None,
                    lock_token: next_lock_token.clone(),
                    label_namespace: format!("awswaf:managed:{name}"),
                    recommended_version: None,
                    published_versions: Vec::new(),
                    created_time: Utc::now(),
                });
        for v in published {
            if !entry.published_versions.contains(&v) {
                entry.published_versions.push(v);
            }
        }
        if recommended_version.is_some() {
            entry.recommended_version = recommended_version;
        }
        entry.lock_token = next_lock_token.clone();

        Ok(AwsResponse::ok_json(json!({
            "NextLockToken": next_lock_token,
        })))
    }

    pub(super) fn update_managed_rule_set_version_expiry_date(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let name = require_str(&body, "Name")?;
        fakecloud_core::validation::validate_string_length("Name", &name, 1, 128)?;
        let id = require_str(&body, "Id")?;
        fakecloud_core::validation::validate_string_length("Id", &id, 1, 36)?;
        let lock_token = require_str(&body, "LockToken")?;
        fakecloud_core::validation::validate_string_length("LockToken", &lock_token, 1, 36)?;
        let _scope = require_scope(&body)?;
        let version_to_expire = require_str(&body, "VersionToExpire")?;
        fakecloud_core::validation::validate_string_length(
            "VersionToExpire",
            &version_to_expire,
            1,
            64,
        )?;
        let expiry_timestamp = body
            .get("ExpiryTimestamp")
            .and_then(Value::as_f64)
            .ok_or_else(|| invalid_param("ExpiryTimestamp is required"))?;
        Ok(AwsResponse::ok_json(json!({
            "ExpiringVersion": version_to_expire,
            "ExpiryTimestamp": expiry_timestamp,
            "NextLockToken": synth_uuid(),
        })))
    }

    pub(super) fn delete_firewall_manager_rule_groups(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let body = req.json_body();
        let acl_arn = require_str(&body, "WebACLArn")?;
        let lock_token = require_str(&body, "WebACLLockToken")?;
        let mut state = self.state.write();
        let account = account_mut(&mut state, &req.account_id);
        let acl = account
            .web_acls
            .values_mut()
            .find(|a| a.arn == acl_arn)
            .ok_or_else(|| not_found("WebACL"))?;
        if acl.lock_token != lock_token {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "WAFOptimisticLockException",
                "Lock token stale; refetch the WebACL and retry",
            ));
        }
        acl.pre_process_firewall_manager_rule_groups.clear();
        acl.post_process_firewall_manager_rule_groups.clear();
        acl.lock_token = synth_uuid();
        Ok(AwsResponse::ok_json(json!({
            "NextWebACLLockToken": acl.lock_token,
        })))
    }
}