Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(dsl): Forbid empty environment variables #17035

Closed
wants to merge 1 commit into from

Conversation

AndesKrrrrrrrrrrr
Copy link
Member

@AndesKrrrrrrrrrrr AndesKrrrrrrrrrrr commented Nov 26, 2024

When an application uses env.required() to get a defined environment config variable, it will break at runtime.

We recently started removing empty ('') environment variables, making them unset. This causes applications like the one above to fail if the value it sets is empty, not missing.

To prevent empty required config, and avoid missing (empty?) environment variables, let's make empty environment variables be forbidden.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error handling for filtering properties in objects to prevent empty strings from being ignored.
    • New checks ensure that empty string properties trigger errors unless they are part of an allowed set.
  • New Features

    • Improved type safety in the filtering function with updated parameter and return types.

Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Walkthrough

The changes in this pull request involve significant modifications to the function that filters properties in an object. The function removeEmptyStringProperties has been renamed to verifiablyNonEmptyProperties, with enhanced error handling for empty string properties. The function now uses unknown for its parameter and return types, improving type safety. The filtering mechanism has been updated to create a new array of entries that excludes empty strings, ensuring that empty properties are not ignored. The call to this function in writeYamlFile has also been updated accordingly.

Changes

File Path Change Summary
infra/src/cli/generate-chart-values.ts Renamed removeEmptyStringProperties to verifiablyNonEmptyProperties, updated logic for error handling, changed parameter and return types from any to unknown, and modified filtering mechanism to enhance robustness. Updated call in writeYamlFile.

Suggested labels

automerge

Suggested reviewers

  • peturgq

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@datadog-island-is
Copy link

Datadog Report

All test runs e582643 🔗

68 Total Test Services: 0 Failed, 62 Passed
🔻 Test Sessions change in coverage: 5 decreased, 195 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
air-discount-scheme-backend 0 0 0 63 0 27.95s N/A Link
air-discount-scheme-web 0 0 0 2 0 7.82s N/A Link
api 0 0 0 4 0 2.79s N/A Link
api-domains-air-discount-scheme 0 0 0 6 0 19.11s N/A Link
api-domains-assets 0 0 0 3 0 12.14s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 10.41s N/A Link
api-domains-communications 0 0 0 5 0 29.66s N/A Link
api-domains-criminal-record 0 0 0 5 0 8.31s 1 no change Link
api-domains-driving-license 0 0 0 23 0 26.61s N/A Link
api-domains-education 0 0 0 8 0 18.28s N/A Link

🔻 Code Coverage Decreases vs Default Branch (5)

  • services-auth-delegation-api - jest 50.38% (-0.04%) - Details
  • services-university-gateway - jest 45.11% (-0.03%) - Details
  • services-user-profile - jest 49.05% (-0.02%) - Details
  • license-api - jest 33.92% (-0.02%) - Details
  • application-template-api-modules - jest 30.16% (-0.01%) - Details

@AndesKrrrrrrrrrrr AndesKrrrrrrrrrrr marked this pull request as ready for review November 27, 2024 14:08
@AndesKrrrrrrrrrrr AndesKrrrrrrrrrrr requested a review from a team as a code owner November 27, 2024 14:08
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

🧹 Outside diff range and nitpick comments (2)
infra/src/cli/generate-chart-values.ts (2)

27-27: Consider improving documentation and naming for NON_EMPTYABLE_PROPERTIES

The constant's purpose and the rationale for allowing specific properties to be empty should be documented. Consider renaming to something more descriptive like ALLOWED_EMPTY_ENV_VARS.

+// Properties that are explicitly allowed to have empty values.
+// SERVERSIDE_FEATURES_ON: Empty value indicates all features are disabled
-const NON_EMPTYABLE_PROPERTIES = new Set(['SERVERSIDE_FEATURES_ON'])
+const ALLOWED_EMPTY_ENV_VARS = new Set(['SERVERSIDE_FEATURES_ON'])

44-44: Improve error handling in writeYamlFile

Consider wrapping the verifiablyNonEmptyProperties call with try-catch to provide more context about which file failed validation.

-  const filteredContent = verifiablyNonEmptyProperties(content)
+  try {
+    const filteredContent = verifiablyNonEmptyProperties(content)
+  } catch (error) {
+    throw new Error(`Failed to validate content for ${filePath}: ${error.message}`)
+  }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ca7fe1a and 82c562e.

📒 Files selected for processing (1)
  • infra/src/cli/generate-chart-values.ts (1 hunks)
🔇 Additional comments (1)
infra/src/cli/generate-chart-values.ts (1)

27-44: Verify the impact of forbidding empty environment variables

Let's ensure this change doesn't break existing configurations and identify any potential empty environment variables.

Comment on lines +28 to +40
const verifiablyNonEmptyProperties = (obj: unknown): unknown => {
if (typeof obj !== 'object' || obj === null) return obj

if (Array.isArray(obj)) {
return obj.map(removeEmptyStringProperties)
return obj.map(verifiablyNonEmptyProperties)
}

return Object.fromEntries(
Object.entries(obj)
.filter(
([key, value]) => value !== '' || NON_EMPTYABLE_PROPERTIES.has(key),
) // Filter out empty strings
.map(([key, value]) => [key, removeEmptyStringProperties(value)]), // Recursively apply to nested objects
)
const stripped = Object.entries(obj)
.filter(([key, value]) => value !== '' || NON_EMPTYABLE_PROPERTIES.has(key)) // Filter out empty strings
.map(([key, value]) => [key, verifiablyNonEmptyProperties(value)]) // Recursively apply to nested objects
if (new Set(Object.keys(obj)) !== new Set(Object.fromEntries(stripped)))
throw new Error('Empty properties not allowed')
return stripped
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling and type safety

The function implementation has several areas for improvement:

  1. The error message should include the property name(s) that were empty
  2. The Set comparison logic could be simplified
  3. Consider using a more specific return type
-const verifiablyNonEmptyProperties = (obj: unknown): unknown => {
+interface JsonValue {
+  [key: string]: JsonValue | string | number | boolean | null | JsonValue[];
+}
+
+const verifiablyNonEmptyProperties = (obj: unknown): JsonValue => {
   if (typeof obj !== 'object' || obj === null) return obj

   if (Array.isArray(obj)) {
     return obj.map(verifiablyNonEmptyProperties)
   }

+  const emptyProps: string[] = []
   const stripped = Object.entries(obj)
-    .filter(([key, value]) => value !== '' || NON_EMPTYABLE_PROPERTIES.has(key))
+    .filter(([key, value]) => {
+      if (value === '' && !ALLOWED_EMPTY_ENV_VARS.has(key)) {
+        emptyProps.push(key)
+        return false
+      }
+      return true
+    })
     .map(([key, value]) => [key, verifiablyNonEmptyProperties(value)])
-  if (new Set(Object.keys(obj)) !== new Set(Object.fromEntries(stripped)))
-    throw new Error('Empty properties not allowed')
+  
+  if (emptyProps.length > 0) {
+    throw new Error(`Empty values not allowed for properties: ${emptyProps.join(', ')}`)
+  }
   return stripped
 }

Committable suggestion skipped: line range outside the PR's diff.

Copy link

codecov bot commented Nov 27, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 35.58%. Comparing base (ca7fe1a) to head (82c562e).
Report is 21 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #17035   +/-   ##
=======================================
  Coverage   35.58%   35.58%           
=======================================
  Files        6933     6933           
  Lines      146745   146745           
  Branches    41714    41714           
=======================================
  Hits        52226    52226           
  Misses      94519    94519           
Flag Coverage Δ
judicial-system-backend 55.58% <ø> (ø)

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 ca7fe1a...82c562e. Read the comment docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant