Skip to content

Add tests for frontend module#3581

Merged
arkid15r merged 13 commits intoOWASP:feature/nest-zappa-migrationfrom
rudransh-shrivastava:feature/nest-zappa-migration-frontend-tests
Jan 29, 2026
Merged

Add tests for frontend module#3581
arkid15r merged 13 commits intoOWASP:feature/nest-zappa-migrationfrom
rudransh-shrivastava:feature/nest-zappa-migration-frontend-tests

Conversation

@rudransh-shrivastava
Copy link
Collaborator

@rudransh-shrivastava rudransh-shrivastava commented Jan 26, 2026

Proposed change

Resolves #3546

Add tests for frontend module
Add kms module.
Resolve semgrep scans

Checklist

  • Required: I followed the contributing workflow
  • Required: I verified that my code works as intended and resolves the issue as described
  • Required: I ran make check-test locally: all warnings addressed, tests passed
  • I used AI for code, documentation, tests, or communication related to this PR

@rudransh-shrivastava rudransh-shrivastava linked an issue Jan 26, 2026 that may be closed by this pull request
2 tasks
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 26, 2026

Summary by CodeRabbit

  • New Features

    • Frontend migrated to containerized ECS deployment with image repository and autoscaling.
    • Added a reusable KMS module providing a managed encryption key.
  • Infrastructure Improvements

    • KMS encryption enabled for logs, secrets, state, and flow logs.
    • VPC flow logs and networking/routing enhancements added.
    • Load balancer and listener configuration simplified.
  • Configuration Changes

    • Domain name is now required; URLs always use HTTPS.
    • ECS networking exposes assignment control for public IPs.
  • Tests

    • New plan-based tests added for KMS, ECS, ECR, and frontend resources.

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Introduces a new KMS module and wires its key across multiple modules; refactors the frontend to use ECR/ECS with new task/service and IAM roles; enables KMS encryption for multiple CloudWatch log groups and secrets; adds VPC flow logs and routing resources; simplifies ALB/HTTPS logic; updates staging and CI variable handling; and adds TFTest suites for frontend and KMS.

Changes

Cohort / File(s) Summary
KMS Module (New)
infrastructure/modules/kms/*, infrastructure/modules/kms/tests/kms.tftest.hcl, infrastructure/modules/kms/.terraform.lock.hcl
New KMS module: key, alias, key policy, variables/validation, outputs and TFTest coverage; lockfile added.
Frontend Module Refactor
infrastructure/modules/frontend/main.tf, infrastructure/modules/frontend/variables.tf, infrastructure/modules/frontend/tests/frontend.tftest.hcl, infrastructure/modules/frontend/.terraform.lock.hcl
Replace legacy autoscaling with ECR + ECS task definition/service, new ECR lifecycle policy, new IAM roles/policies, autoscaling target/policy, and add KMS key variable and tests; variable validations added.
ECS / Task Changes
infrastructure/modules/ecs/main.tf, infrastructure/modules/ecs/variables.tf, infrastructure/modules/ecs/modules/task/*
Add kms_key_arn variable and pass it into task modules; make ECR image_tag_mutability MUTABLE; add kms_key_id to task log group.
Database & Cache
infrastructure/modules/database/*, infrastructure/modules/cache/*
Add kms_key_arn variable; SecretsManager secret and cache log groups now reference KMS key; RDS proxy IAM policy updated for kms:Decrypt.
Networking / Flow Logs
infrastructure/modules/networking/main.tf, infrastructure/modules/networking/variables.tf
Add VPC flow logs resources (log group with KMS, role, policy, flow log), internet gateway, explicit route tables, subnet validations, and kms_key_arn variable.
ALB Simplification
infrastructure/modules/alb/main.tf, infrastructure/modules/alb/outputs.tf, infrastructure/modules/alb/variables.tf
Remove enable_https conditional logic and counts; make ACM/listener outputs unconditional and adjust listener references.
Staging Integration & Params
infrastructure/staging/*, infrastructure/modules/parameters/tests/parameters.tftest.hcl
Add module.kms and propagate kms_key_arn to cache, database, ecs, frontend, networking; make domain_name required and produce HTTPS URLs; replace ecs_use_public_subnets with ecs_assign_public_ip; add test variables for CSRF/GraphQL URLs.
CI/CD, Backend, Misc
.github/workflows/run-ci-cd.yaml, backend/zappa_callback.py, infrastructure/backend/main.tf, cspell/custom-dict.txt
Removed CI variable lines for ecs_use_public_subnets; add nosec comment for tarfile.extractall; wire DynamoDB state_lock server_side_encryption.kms_key_arn to module.kms; add spellcheck token.
Tests / TFTest Additions
infrastructure/modules/frontend/tests/*, infrastructure/modules/cache/tests/*, infrastructure/modules/database/tests/*, infrastructure/modules/kms/tests/*
Add/extend TFTest plans asserting frontend, cache, database, and KMS behavior and validate KMS/logging/lifecycle/policy settings.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • OWASP/Nest #3238 — Overlaps frontend Terraform refactor (ECS task/service and related frontend changes).
  • OWASP/Nest #2777 — Related ECS module changes (task wiring, ECR lifecycle/ IAM/task inputs) that align with kms_key_arn and ECR edits.
  • OWASP/Nest #2699 — Related backend/state KMS wiring and DynamoDB server-side encryption changes.

Suggested labels

frontend-tests

Suggested reviewers

  • kasya
  • arkid15r
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning While the PR adds frontend tests as required, it includes additional scope: KMS module creation, networking/database/cache encryption updates, ALB simplification, and ECS refactoring. These go beyond the linked issue #3546 objective. Clarify whether the KMS module and encryption updates are dependencies for the frontend tests, or if they should be split into a separate PR to maintain focused change scope.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add tests for frontend module' directly aligns with the main changeset objective and clearly describes the primary change.
Description check ✅ Passed The PR description mentions adding tests for the frontend module and resolving semgrep scans, which are core changes present in the changeset.
Linked Issues check ✅ Passed The PR resolves #3546 which requires adding tests for the frontend module. The changeset includes infrastructure/modules/frontend/tests/frontend.tftest.hcl with comprehensive test coverage for frontend resources, fulfilling the primary coding requirement.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
infrastructure/modules/frontend/main.tf (1)

14-20: Add KMS encryption to the CloudWatch log group.

The log group is currently unencrypted. Add kms_key_id = var.cloudwatch_log_kms_key_id to the resource and define the corresponding variable. Update the test to verify encryption is applied.

Note: This same pattern applies across other CloudWatch log groups in the infrastructure (networking, cache, ecs/task modules). Consider a coordinated rollout if this is part of a broader encryption initiative.

Suggested change
 resource "aws_cloudwatch_log_group" "frontend" {
   name              = "/aws/ecs/${var.project_name}-${var.environment}-frontend"
   retention_in_days = var.log_retention_in_days
+  kms_key_id        = var.cloudwatch_log_kms_key_id
   tags = merge(var.common_tags, {
     Name = "${var.project_name}-${var.environment}-frontend-logs"
   })
 }
🤖 Fix all issues with AI agents
In `@infrastructure/modules/frontend/main.tf`:
- Around line 22-33: Update the ECR repository resource
aws_ecr_repository.frontend to set image_tag_mutability = "IMMUTABLE" (replacing
"MUTABLE") and update the test named
test_frontend_ecr_repository_image_tag_mutability in
infrastructure/modules/frontend/tests/frontend.tftest.hcl to assert
image_tag_mutability == "IMMUTABLE" so the test reflects the hardened
configuration.

@rudransh-shrivastava
Copy link
Collaborator Author

rudransh-shrivastava commented Jan 26, 2026

It looks semgrep scan fails with some false positives. Some things like having HTTP as a fail over when no domain name is provided were intentional. I'll update the code in a new PR tomorrow.

@rudransh-shrivastava
Copy link
Collaborator Author

rudransh-shrivastava commented Jan 26, 2026

There are some suggestions that are valid and I can incorporate. Like setting up AWS KMS encryption key and not using "ecr:GetAuthorizationToken".

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 26, 2026
@rudransh-shrivastava
Copy link
Collaborator Author

rudransh-shrivastava commented Jan 26, 2026

Hey @arkid15r, some questions related to the semgrep scan:

  1. Do I completely remove the HTTP handling by redirecting traffic to HTTPS? I had added HTTP handling in case someone setting up the infrastructure does not have a domain.
  2. Is it okay for the ECR repository to allow tag mutability? I use the :latest tag to deploy frontend tasks and run backend ECS tasks. As per this conversation with coderabbit, it looks like making it IMMUTABLE might reduce some deployment steps. I'll need to try it to know for sure.

@rudransh-shrivastava rudransh-shrivastava marked this pull request as ready for review January 26, 2026 19:54
@arkid15r
Copy link
Collaborator

arkid15r commented Jan 26, 2026

  1. Do I completely remove the HTTP handling by redirecting traffic to HTTPS? I had added HTTP handling in case someone setting up the infrastructure does not have a domain.

Yes if possible. We use http->https redirect for current Nginx based solution AFAIR.

  1. Is it okay for the ECR repository to allow tag mutability? I use the :latest tag to deploy frontend tasks and run backend ECS tasks. As per this conversation with coderabbit, it looks like making it IMMUTABLE might reduce some deployment steps. I'll need to try it to know for sure.

Feel free to suppress it while leaving a TODO.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
infrastructure/modules/ecs/modules/task/main.tf (1)

12-19: Add validation for kms_key_arn variable and consider making it optional.

KMS encryption for CloudWatch logs is a good security improvement. However, the kms_key_arn variable (defined in variables.tf:60-63) lacks ARN format validation and has no default value, making it a required parameter with no fallback to AWS-managed encryption.

Consider either:

  1. Adding validation to enforce ARN format (e.g., validation { condition = ... }), or
  2. Making it optional with a default = null to allow fallback to AWS-managed keys when KMS is not required

This would improve robustness and flexibility of the module.

infrastructure/modules/alb/main.tf (1)

130-142: Add ACM certificate validation dependency to prevent apply failures.

The HTTPS listener references a newly created ACM certificate without waiting for it to reach ISSUED status. AWS ALBs reject PENDING_VALIDATION certificates—the first apply will fail with a validation error, requiring manual DNS validation and a second apply. Either add aws_acm_certificate_validation to wait for issuance before creating the listener, or document that a two-phase deployment workflow is required (create cert → complete DNS validation externally → re-apply).

🤖 Fix all issues with AI agents
In `@infrastructure/modules/alb/outputs.tf`:
- Around line 36-43: The output description for https_listener_arn is stale — it
says "(null if HTTPS disabled)" but nginx now always creates HTTPS; update the
description for the output "https_listener_arn" (value
aws_lb_listener.https.arn) to remove the null caveat and reflect that the ARN is
always provided (e.g., "The ARN of the HTTPS listener.").

In `@infrastructure/modules/database/main.tf`:
- Around line 63-67: The RDS proxy cannot decrypt the secret stored in
aws_secretsmanager_secret.db_credentials because its IAM policy only includes
secretsmanager:GetSecretValue; update the IAM policy or role attached to the RDS
proxy (the policy/resource that grants the proxy access, e.g.,
aws_iam_policy.rds_proxy_policy or aws_iam_role.rds_proxy_role) to also allow
"kms:Decrypt" on the CMK used by var.kms_key_arn (or the aws_kms_key resource if
defined), ensuring the policy includes kms:Decrypt with the correct resource ARN
so the proxy can decrypt the secret.
🧹 Nitpick comments (2)
infrastructure/modules/networking/variables.tf (1)

58-61: Add light validation for kms_key_arn to fail fast.
A minimal check helps catch empty or malformed values before they reach resource configuration.

Suggested validation
 variable "kms_key_arn" {
   description = "The ARN of the KMS key."
   type        = string
+
+  validation {
+    condition     = can(regex("^arn:", var.kms_key_arn))
+    error_message = "kms_key_arn must be a valid KMS key ARN."
+  }
 }
infrastructure/modules/database/main.tf (1)

45-45: Consider documenting or restoring configurability for log exports.
Hard-coding the exports removes the previous knob; if intentional, a short note in module docs helps prevent surprises.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 27, 2026
@codecov
Copy link

codecov bot commented Jan 27, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (feature/nest-zappa-migration@3399007). Learn more about missing BASE report.

Additional details and impacted files

Impacted file tree graph

@@                       Coverage Diff                       @@
##             feature/nest-zappa-migration    #3581   +/-   ##
===============================================================
  Coverage                                ?   85.50%           
===============================================================
  Files                                   ?      463           
  Lines                                   ?    14271           
  Branches                                ?     1900           
===============================================================
  Hits                                    ?    12202           
  Misses                                  ?     1689           
  Partials                                ?      380           
Flag Coverage Δ
backend 84.49% <ø> (?)
frontend 88.27% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 3399007...5df7ec7. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 27, 2026
@rudransh-shrivastava
Copy link
Collaborator Author

rudransh-shrivastava commented Jan 27, 2026

Hey @arkid15r , I've resolved the semgrep scans.
Since the backend dynamodb_table now has a KMS key, the table needs to be recreated.

You can either: back up the current state > recreate the backend > initialize with the new backend > push the backed-up state. Commands to push and pull state:

terraform state pull > terraform.tfstate.backup
terraform state push terraform.tfstate.backup

Or just recreate the backend directly if it has no existing state.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@infrastructure/backend/main.tf`:
- Around line 91-94: The KMS key used by module.kms (referenced as
module.kms.key_arn) needs a policy statement allowing the DynamoDB service
principal to use the key; update the KMS key policy attached to your KMS
resource (e.g., the aws_kms_key or aws_kms_key_policy for the key created in the
kms module) to add a Statement that grants Principal service
"dynamodb.amazonaws.com" the actions "kms:Decrypt", "kms:Encrypt",
"kms:GenerateDataKey*" and "kms:Describe*" on the key resource (or "*" if the
policy is scoped broadly); add any necessary Conditions (e.g., SourceArn) if you
want to restrict to the specific DynamoDB table, then reapply Terraform so
module.kms.key_arn can be used by the encrypted DynamoDB table.

In `@infrastructure/staging/main.tf`:
- Around line 143-160: Add a validation block to the variable "domain_name"
declaration to reject empty strings; specifically add a validation that checks
length(var.domain_name) > 0 and provides a clear error_message (e.g.,
"domain_name must not be empty."), since main.tf interpolates domain_name into
allowed_origins, nextauth_url, server_csrf_url, server_graphql_url and
allowed_hosts and empty values would produce invalid URLs.
🧹 Nitpick comments (1)
infrastructure/modules/database/main.tf (1)

45-45: Hardcoded log exports remove configurability.

The enabled_cloudwatch_logs_exports is now hardcoded to ["postgresql", "upgrade"] instead of using a variable. This reduces flexibility for environments that may need different log types (e.g., adding "error" logs).

Consider if this is intentional or if the variable should be retained for flexibility.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 27, 2026
@rudransh-shrivastava rudransh-shrivastava force-pushed the feature/nest-zappa-migration-frontend-tests branch from d70e384 to ec6e4e5 Compare January 28, 2026 13:49
@github-actions github-actions bot removed the makefile label Jan 28, 2026
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@infrastructure/modules/networking/modules/nacl/tests/nacl.tftest.hcl`:
- Around line 47-63: The test error messages are inconsistent with the assert
conditions in run "test_private_nacl_associations_count" and run
"test_public_nacl_associations_count": the asserts check
length(aws_network_acl_association.private) == 2 and
length(aws_network_acl_association.public) == 2 but the error_message texts say
"should have 3 subnet associations." Update the error_message strings to match
the expected count of 2 (e.g., "Private NACL should have 2 subnet associations."
and "Public NACL should have 2 subnet associations.") or, if the correct
expectation is 3, change the assert conditions to == 3 for
aws_network_acl_association.private and aws_network_acl_association.public so
the condition and message agree.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@infrastructure/modules/frontend/tests/frontend.tftest.hcl`:
- Around line 1-15: The test fixture declares aws_region = "us-east-2" but
target_group_arn embeds "us-east-1", causing inconsistent region data; update
the value of target_group_arn in the variables block so its region matches
aws_region (change the ARN region segment from us-east-1 to us-east-2) or
alternatively set aws_region to "us-east-1" so both match; edit the variables
entry named target_group_arn to reflect the chosen region consistently with
aws_region.
🧹 Nitpick comments (2)
infrastructure/modules/cache/tests/cache.tftest.hcl (1)

4-4: Add assertions that log groups use the provided KMS key.
You added kms_key_arn, but the test suite never asserts it’s applied. This could let a misconfiguration slip through.

✅ Suggested test additions
 run "test_log_groups_created" {
   command = plan

   assert {
     condition     = aws_cloudwatch_log_group.engine_log.retention_in_days == var.log_retention_in_days
     error_message = "Engine log group must be created with correct retention."
   }
 
+  assert {
+    condition     = aws_cloudwatch_log_group.engine_log.kms_key_id == var.kms_key_arn
+    error_message = "Engine log group must be encrypted with the provided KMS key."
+  }
+
   assert {
     condition     = aws_cloudwatch_log_group.slow_log.retention_in_days == var.log_retention_in_days
     error_message = "Slow log group must be created with correct retention."
   }
+
+  assert {
+    condition     = aws_cloudwatch_log_group.slow_log.kms_key_id == var.kms_key_arn
+    error_message = "Slow log group must be encrypted with the provided KMS key."
+  }
 }

Also applies to: 82-93

infrastructure/modules/frontend/tests/frontend.tftest.hcl (1)

53-60: Consider parameterizing image tag mutability.

Hard-coding "MUTABLE" in the test makes it harder to harden later (e.g., to "IMMUTABLE"). If the module can support a toggle, this test could assert against a variable and/or add a second scenario.

@sonarqubecloud
Copy link

@rudransh-shrivastava rudransh-shrivastava marked this pull request as ready for review January 28, 2026 15:12
Copy link
Collaborator

@arkid15r arkid15r left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work 👍

DOMAIN_NAME: ${{ vars.DOMAIN_NAME }}
ECS_USE_FARGATE_SPOT: true
ECS_USE_PUBLIC_SUBNETS: false
ENVIRONMENT: "staging"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These should be '

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will update in the testing CI/CD PR.

temp_path = Path(temp_dir)
new_archive_path = temp_path / "new.tar.gz"

# nosemgrep: trailofbits.python.tarfile-extractall-traversal.tarfile-extractall-traversal # noqa: ERA001, E501
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest using NOSEMGREP for consistency w/ Sonar.

@arkid15r arkid15r merged commit 0e67f96 into OWASP:feature/nest-zappa-migration Jan 29, 2026
37 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Feb 17, 2026
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add tests for frontend module

2 participants