Skip to content

Fixed conversion of environment variables to number types with Claude Code 2#154

Open
ryo8000 wants to merge 1 commit intomainfrom
claude-code/env
Open

Fixed conversion of environment variables to number types with Claude Code 2#154
ryo8000 wants to merge 1 commit intomainfrom
claude-code/env

Conversation

@ryo8000
Copy link
Owner

@ryo8000 ryo8000 commented Aug 18, 2025

Summary by CodeRabbit

  • New Features

    • Stricter configuration validation for environment variables with clear, descriptive startup errors on invalid or out-of-range values.
    • Default values applied consistently for timeouts, port, and delays when not provided.
  • Bug Fixes

    • Prevents silent fallback from malformed numeric configuration (e.g., timeouts, port, max delay).
    • Enforces logical ordering between timeouts to avoid misconfigurations.
  • Tests

    • Added comprehensive tests covering invalid numeric inputs and boundary cases for configuration values.

@coderabbitai
Copy link

coderabbitai bot commented Aug 18, 2025

Walkthrough

Introduces parseEnvInteger for integer parsing in env.ts, applies it to timeouts, MAX_DELAY, and PORT with defaults, and adds ordering validations between timeouts. Module now throws on invalid integers or misordered values. Tests added to verify rejection messages for invalid integers and out-of-range values.

Changes

Cohort / File(s) Summary
Env parsing and validation
src/env.ts
Added parseEnvInteger (uses toSafeInteger) for integer env vars; replaced direct Number(...) for HEADERS_TIMEOUT, REQUEST_TIMEOUT, KEEP_ALIVE_TIMEOUT, MAX_DELAY, PORT; added validations: headersTimeout > keepAliveTimeout and requestTimeout > headersTimeout; module can throw on invalid or misordered values.
Unit tests for env errors
tests/ut/env.test.ts
Added tests asserting loadEnv() rejects invalid integer env vars (HEADERS_TIMEOUT, REQUEST_TIMEOUT, KEEP_ALIVE_TIMEOUT, MAX_DELAY, PORT) with exact error messages; includes test for out-of-range PORT.

Sequence Diagram(s)

sequenceDiagram
  participant App
  participant Env as loadEnv()
  participant Parser as parseEnvInteger
  participant Validator as validateOrdering

  App->>Env: initialize config
  Env->>Parser: parse PORT, MAX_DELAY, timeouts
  Parser-->>Env: integers or throw on invalid
  Env->>Validator: check timeout ordering
  Validator-->>Env: ok or throw
  Env-->>App: config or error
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I twitch my ears at ports and time,
Counting ticks in tidy rhyme.
If numbers wobble, I will squeak—
“Invalid!” with a careful squeak.
Now timeouts line up, neat in a row,
A happy hop—onwards we go! 🐇⌛️

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude-code/env

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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @ryo8000, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refactors how environment variables are parsed into number types, introducing a dedicated utility function for robust integer conversion. It enhances error handling by explicitly throwing errors for invalid or unsafe integer inputs, ensuring that environment-dependent configurations are correctly and safely loaded.

Highlights

  • Robust Environment Variable Parsing: A new parseEnvInteger utility function has been introduced to safely convert string-based environment variables into integer types. This function handles default values and integrates toSafeInteger for validation.
  • Enhanced Input Validation: The system now provides explicit error messages when environment variables intended to be integers are malformed (e.g., non-numeric strings, floating-point numbers, or values outside JavaScript's safe integer range).
  • Comprehensive Test Coverage: New unit tests have been added to env.test.ts to cover various invalid scenarios for integer environment variables, ensuring the new validation logic functions as expected.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.


String to number,Safe parse, no silent errors,Code runs true and strong.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@ryo8000 ryo8000 added enhancement New feature or request experiment Experiment labels Aug 18, 2025
@ryo8000 ryo8000 changed the title Fixed conversion of environment variables to number types Fixed conversion of environment variables to number types with Claude Code 2 Aug 18, 2025
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request addresses a flaw in how environment variables are converted to number types. The previous method using Number(process.env['VAR']) || defaultValue would incorrectly handle 0 as a falsy value, causing it to fall back to the default. It also silently used the default for any non-numeric string values. The introduction of the parseEnvInteger helper function is a great improvement. It correctly handles 0, only uses the default value if the variable is undefined, and throws an explicit error for invalid integer values, making the application's configuration loading much more robust and predictable. The accompanying tests are thorough, and I have one suggestion to make them more maintainable.

Comment on lines +84 to +130
it('should throw an error when HEADERS_TIMEOUT is not a valid integer', async () => {
process.env.HEADERS_TIMEOUT = 'invalid';

await expect(loadEnv()).rejects.toThrow(
'Invalid HEADERS_TIMEOUT environment variable: "invalid" is not a valid integer'
);
});

it('should throw an error when REQUEST_TIMEOUT is not a valid integer', async () => {
process.env.REQUEST_TIMEOUT = '1.5';

await expect(loadEnv()).rejects.toThrow(
'Invalid REQUEST_TIMEOUT environment variable: "1.5" is not a valid integer'
);
});

it('should throw an error when KEEP_ALIVE_TIMEOUT is not a valid integer', async () => {
process.env.KEEP_ALIVE_TIMEOUT = '2e10';

await expect(loadEnv()).rejects.toThrow(
'Invalid KEEP_ALIVE_TIMEOUT environment variable: "2e10" is not a valid integer'
);
});

it('should throw an error when MAX_DELAY is not a valid integer', async () => {
process.env.MAX_DELAY = 'abc';

await expect(loadEnv()).rejects.toThrow(
'Invalid MAX_DELAY environment variable: "abc" is not a valid integer'
);
});

it('should throw an error when PORT is not a valid integer', async () => {
process.env.PORT = '8000.0';

await expect(loadEnv()).rejects.toThrow(
'Invalid PORT environment variable: "8000.0" is not a valid integer'
);
});

it('should throw an error when integer is out of safe range', async () => {
process.env.PORT = '9007199254740992';

await expect(loadEnv()).rejects.toThrow(
'Invalid PORT environment variable: "9007199254740992" is not a valid integer'
);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

These tests are great for ensuring invalid values are handled correctly. To improve maintainability and reduce code duplication, you could parameterize these tests using it.each, which you're already using elsewhere in the test suite. This would make the test suite more concise and easier to extend with new invalid cases in the future.

  describe('when an integer environment variable is invalid', () => {
    const testCases = [
      { name: 'not an integer', envVar: 'HEADERS_TIMEOUT', value: 'invalid' },
      { name: 'a float string', envVar: 'REQUEST_TIMEOUT', value: '1.5' },
      { name: 'scientific notation', envVar: 'KEEP_ALIVE_TIMEOUT', value: '2e10' },
      { name: 'a non-numeric string', envVar: 'MAX_DELAY', value: 'abc' },
      { name: 'a float string with .0', envVar: 'PORT', value: '8000.0' },
      { name: 'an out of safe range integer', envVar: 'PORT', value: '9007199254740992' },
    ];

    it.each(testCases)('should throw an error when $envVar is $name ($value)', async ({ envVar, value }) => {
      process.env[envVar] = value;

      await expect(loadEnv()).rejects.toThrow(
        `Invalid ${envVar} environment variable: "${value}" is not a valid integer`
      );
    });
  });

Copy link

@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: 0

🧹 Nitpick comments (5)
src/env.ts (3)

3-13: Harden integer parsing with min/max bounds to prevent negative timeouts and invalid port values

parseEnvInteger is solid. To avoid subtle misconfigurations (e.g., negative timeouts, negative MAX_DELAY disabling delays, or ports outside 0–65535), consider adding optional range validation.

Apply this diff to extend the helper:

-const parseEnvInteger = (envVar: string, defaultValue: number): number => {
+const parseEnvInteger = (
+  envVar: string,
+  defaultValue: number,
+  opts?: { min?: number; max?: number }
+): number => {
   const value = process.env[envVar];
   if (value === undefined) {
     return defaultValue;
   }
   const parsed = toSafeInteger(value);
   if (parsed === undefined) {
     throw new Error(`Invalid ${envVar} environment variable: "${value}" is not a valid integer`);
   }
-  return parsed;
+  if (opts?.min !== undefined && parsed < opts.min) {
+    throw new Error(`Invalid ${envVar} environment variable: ${parsed} must be >= ${opts.min}`);
+  }
+  if (opts?.max !== undefined && parsed > opts.max) {
+    throw new Error(`Invalid ${envVar} environment variable: ${parsed} must be <= ${opts.max}`);
+  }
+  return parsed;
 };

15-17: Clamp timeouts to non-negative values

Negative timeout values can lead to confusing behavior or immediate timeouts. If you adopt range support in parseEnvInteger, pass min: 0 here.

-const headersTimeout = parseEnvInteger('HEADERS_TIMEOUT', 10000);
-const requestTimeout = parseEnvInteger('REQUEST_TIMEOUT', 30000);
-const keepAliveTimeout = parseEnvInteger('KEEP_ALIVE_TIMEOUT', 5000);
+const headersTimeout = parseEnvInteger('HEADERS_TIMEOUT', 10000, { min: 0 });
+const requestTimeout = parseEnvInteger('REQUEST_TIMEOUT', 30000, { min: 0 });
+const keepAliveTimeout = parseEnvInteger('KEEP_ALIVE_TIMEOUT', 5000, { min: 0 });

36-39: Validate MAX_DELAY is non-negative and PORT within [0, 65535]

  • MAX_DELAY < 0 will effectively disable delays due to Math.min(...) yielding a negative actualDelay.
  • PORT outside the valid range or negative can cause server startup failures.
-  maxDelay: parseEnvInteger('MAX_DELAY', 10000),
+  maxDelay: parseEnvInteger('MAX_DELAY', 10000, { min: 0 }),
   nodeEnv: process.env['NODE_ENV'] || 'development',
   origin: process.env['ORIGIN'] || '*',
-  port: parseEnvInteger('PORT', 8000),
+  port: parseEnvInteger('PORT', 8000, { min: 0, max: 65535 }),
tests/ut/env.test.ts (2)

83-130: De-duplicate repetitive “invalid integer” tests with a table-driven pattern

You can compact these into a single parameterized case while keeping explicit assertions.

Example refactor:

it.each([
  { name: 'HEADERS_TIMEOUT', value: 'invalid' },
  { name: 'REQUEST_TIMEOUT', value: '1.5' },
  { name: 'KEEP_ALIVE_TIMEOUT', value: '2e10' },
  { name: 'MAX_DELAY', value: 'abc' },
  { name: 'PORT', value: '8000.0' },
] as const)('should throw when %s is not a valid integer', async ({ name, value }) => {
  process.env[name] = value;
  await expect(loadEnv()).rejects.toThrow(
    `Invalid ${name} environment variable: "${value}" is not a valid integer`
  );
});

83-130: Consider adding range tests (negative and out-of-range port), especially if you enforce min/max

If you adopt min/max in parseEnvInteger:

  • Add tests to ensure negative timeouts and MAX_DELAY are rejected.
  • Add tests to reject PORT < 0 and PORT > 65535 (PORT=0 should still be allowed).

Proposed additional tests:

it('should throw when MAX_DELAY is negative', async () => {
  process.env.MAX_DELAY = '-1';
  await expect(loadEnv()).rejects.toThrow(/MAX_DELAY environment variable: -1 must be >= 0/);
});

it('should throw when HEADERS_TIMEOUT is negative', async () => {
  process.env.HEADERS_TIMEOUT = '-100';
  await expect(loadEnv()).rejects.toThrow(/HEADERS_TIMEOUT environment variable: -100 must be >= 0/);
});

it('should throw when PORT is negative', async () => {
  process.env.PORT = '-1';
  await expect(loadEnv()).rejects.toThrow(/PORT environment variable: -1 must be >= 0/);
});

it('should throw when PORT exceeds 65535', async () => {
  process.env.PORT = '70000';
  await expect(loadEnv()).rejects.toThrow(/PORT environment variable: 70000 must be <= 65535/);
});

it('should allow PORT=0 (ephemeral port)', async () => {
  process.env.PORT = '0';
  expect(await loadEnv()).toEqual(expect.objectContaining({ port: 0 }));
});

I can open a follow-up PR to implement the range checks and add these tests if helpful.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a640e66 and a41e6bd.

📒 Files selected for processing (2)
  • src/env.ts (2 hunks)
  • tests/ut/env.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
tests/ut/env.test.ts (1)
tests/ut/utils/number.test.ts (1)
  • validIntegerTestCases (4-19)
src/env.ts (1)
src/utils/number.ts (1)
  • toSafeInteger (16-28)
🔇 Additional comments (2)
src/env.ts (1)

31-41: Confirm stricter empty-string handling for numeric env vars

In src/env.ts (lines 31–41), parseEnvInteger now treats an empty string ('') as an invalid integer and throws, whereas the previous Number(value) || default approach silently fell back to the default. As a result, setting PORT='' or MAX_DELAY='' (or any other numeric env var) will now crash on import instead of using the default.

Please verify that this fail-fast behavior is intended. If it is:

  • Update documentation or error messages to call out that empty strings are disallowed.
  • Ensure all deployment tooling and CI pipelines won’t inadvertently pass empty strings.

If you’d rather preserve the old fallback for '', consider normalizing value === '' to undefined before calling toSafeInteger.

Affected env vars:

  • Numeric: HEADERS_TIMEOUT, KEEP_ALIVE_TIMEOUT, REQUEST_TIMEOUT, MAX_DELAY, PORT
    – impacts server.ts (app.listen on environment.port) and delay.ts (capped by environment.maxDelay)
  • String: LOG_LEVEL, NODE_ENV, ORIGIN remain unchanged and still default on empty
tests/ut/env.test.ts (1)

83-130: LGTM: strong coverage for invalid integers and safe-range overflow

These tests precisely match the new error messages and guard against common bad inputs (non-integers and out-of-safe-range). Good use of dynamic import + resetModules to isolate env per test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request experiment Experiment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant