Skip to content

Add environment variable validation on startup - #23

Merged
AnkanMisra merged 8 commits into
AnkanMisra:mainfrom
ankitadhara28:feature/env-validation
Jan 4, 2026
Merged

AnkanMisra merged 8 commits into
AnkanMisra:mainfrom
ankitadhara28:feature/env-validation

Conversation

@ankitadhara28

@ankitadhara28 ankitadhara28 commented Jan 2, 2026 •

Copy link
Copy Markdown
Contributor

Closes #18

Summary

Adds startup validation for required environment variables to fail fast and provide clear error messages.

Changes

  • Validates required env vars on startup (OPENROUTER_API_KEY)
  • Exits early with a clear, actionable error message if missing
  • Logs safe configuration summary on successful startup
  • Warns about optional env vars and uses defaults

Testing

  • Ran gateway locally with OPENROUTER_API_KEY unset → startup fails with clear error
  • Ran gateway with OPENROUTER_API_KEY set → config validated and gateway starts successfully

Summary by CodeRabbit

  • Chores

    • Added startup configuration validation that checks for a required API key, prints a clear structured error and exits if missing; on success prints confirmation, logs configured values when present, and warns when optional settings are unset so defaults will be used.
  • Tests

    • Added unit tests verifying validation behavior when the required API key is present or absent.

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

Greptile Summary

Added startup validation for OPENROUTER_API_KEY to fail fast with clear error messages before the server starts. The implementation validates required environment variables immediately after loading the .env file, exits with code 1 if validation fails, and prints a helpful configuration summary on successful startup with warnings for missing optional variables.

Changes:

  • Created validateConfig() function that checks for required env vars and returns descriptive errors
  • Added validation call in main() after env loading, before server initialization
  • Prints structured error output directing users to .env.example and README.md on validation failure
  • Logs configuration summary showing PORT, MODEL, VERIFIER_URL, and CHAIN_ID when set
  • Emits [WARN] messages for optional env vars with default values when not set
  • Added unit tests covering both success and failure validation scenarios

Issues Found:

  • Minor indentation inconsistency on line 91 (uses spaces instead of tab)
  • Test isolation: TestValidateConfig_WithRequiredEnv doesn't clean up the env var it sets

Confidence Score: 4/5

  • This PR is safe to merge with minimal risk - implements straightforward validation logic with proper error handling
  • The implementation correctly validates required environment variables on startup and provides clear error messages. The logic is simple and well-tested. The only issues are minor: an indentation inconsistency and a test isolation improvement. Neither affects functionality or introduces bugs.
  • No files require special attention - both issues found are minor style improvements

Important Files Changed

Filename Overview
gateway/main.go Added validateConfig() function and startup validation with warning messages for optional env vars. Minor indentation inconsistency on line 91.
gateway/config_test.go Added unit tests for config validation. Tests don't restore env vars after modification (test isolation issue).

Sequence Diagram

sequenceDiagram
    participant Main as main()
    participant Env as Environment
    participant Validate as validateConfig()
    participant Server as Gin Server
    
    Main->>Env: Load ../.env file
    alt .env file not found
        Env-->>Main: Warning logged
    end
    
    Main->>Validate: validateConfig()
    Validate->>Env: Check OPENROUTER_API_KEY
    
    alt Missing required env var
        Validate-->>Main: Return error
        Main->>Main: Print error message
        Main->>Main: os.Exit(1)
    else All required vars present
        Validate-->>Main: Return nil
        Main->>Main: Print "[OK] Configuration validated"
        Main->>Env: Read optional vars (PORT, MODEL, etc.)
        Main->>Main: Print configured values
        Main->>Env: Check optional vars
        alt Optional var missing
            Main->>Main: Print [WARN] messages
        end
        Main->>Server: Initialize and start Gin server
    end
Loading

@coderabbitai

coderabbitai Bot commented Jan 2, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@AnkanMisra has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 16 minutes and 14 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between ea8368e and 0d1e022.

📒 Files selected for processing (1)
  • .github/workflows/pr-branch-check.yml
📝 Walkthrough

Walkthrough

Adds startup environment validation: validateConfig() in gateway/main.go enforces OPENROUTER_API_KEY, exits with a structured error if missing, warns about optional vars, and logs a compact non-sensitive summary on success. Unit tests for the validator were added.

Changes

Cohort / File(s) Summary
Environment configuration validation
gateway/main.go
Added func validateConfig() error; main() loads .env, calls validateConfig(), prints a structured error block and exits on missing required vars, prints [OK] Configuration validated on success, logs present env values, and emits WARNs for missing optional vars (PORT, MODEL, VERIFIER_URL, CHAIN_ID).
Validation tests
gateway/config_test.go
Added unit tests: TestValidateConfig_MissingRequiredEnv (ensures error when OPENROUTER_API_KEY unset) and TestValidateConfig_WithRequiredEnv (ensures no error when OPENROUTER_API_KEY set). Tests use t.Setenv and assert validateConfig() results.

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I sniff the .env, twitch my nose and pry,

Searching for the key that keeps crashes shy.
I warn, I halt, then cheer when all's right,
I log a hush and guard your startup night. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and clearly summarizes the main change: environment variable validation on startup.
Linked Issues check ✅ Passed The code changes fully implement the validation function, required variable checks, optional variable warnings, error messaging, non-zero exit, config logging, and unit tests as required by #18.
Out of Scope Changes check ✅ Passed All changes are directly related to environment variable validation requirements; no unrelated modifications are present.

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.

@greptile-apps greptile-apps Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Additional Comments (6)

  1. gateway/main.go, line 57-89 (link)

    logic: validateConfig() runs before godotenv.Load(), so env vars from .env won't be loaded yet and validation will fail even with a valid .env file

  2. gateway/main.go, line 80 (link)

    syntax: typo: "sing" should be "using"

  3. gateway/main.go, line 67 (link)

    syntax: missing space in format string - should be " - Port: %s\n", port

  4. gateway/main.go, line 70 (link)

    syntax: missing space in format string - should be " - Model: %s\n", model

  5. gateway/main.go, line 73 (link)

    syntax: missing space in format string - should be " - Verifier: %s\n", verifier

  6. gateway/main.go, line 76 (link)

    syntax: missing space in format string - should be " - Chain ID: %s\n", chainID

1 file reviewed, 6 comments

Edit Code Review Agent Settings | Greptile

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2755bf1 and 6284232.

📒 Files selected for processing (1)
  • gateway/main.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Greptile Review
🔇 Additional comments (1)
gateway/main.go (1)

41-55: LGTM! Well-structured validation function.

The validation logic is clear and extensible. The function correctly checks for required environment variables and provides a clear error message.

Comment thread gateway/main.go Resolved
Comment thread gateway/main.go Resolved
Comment thread gateway/main.go Resolved
@AnkanMisra

Copy link
Copy Markdown
Owner

@ankitadhara28 please in the desciption say which issue are you closing or fixing using closes #issue-number

@AnkanMisra

Copy link
Copy Markdown
Owner

@greptile review this pr

@greptile-apps greptile-apps Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Additional Comments (5)

  1. gateway/main.go, line 63 (link)

    syntax: Incorrect printf formatting - extra space before err.Error() causes malformed output

  2. gateway/main.go, line 69-81 (link)

    syntax: Inconsistent indentation (spaces instead of tabs) and missing spaces in format strings

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

  3. gateway/main.go, line 88 (link)

    syntax: Inconsistent indentation (spaces instead of tabs)

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

  4. gateway/main.go, line 82-90 (link)

    syntax: Missing space after colon in format string (should be "default: 3000")

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

  5. gateway/main.go, line 92 (link)

    style: Extra blank line with trailing whitespace

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

1 file reviewed, 5 comments

Edit Code Review Agent Settings | Greptile

@AnkanMisra AnkanMisra left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Solve the issue that i found and please add unit test cause the issue #18 requires: "Include unit tests for the validation function"

Comment thread gateway/main.go Resolved
Comment thread gateway/main.go Resolved
Comment thread gateway/main.go Resolved
@ankitadhara28

Copy link
Copy Markdown
Contributor Author

Hi @AnkanMisra
I've fixed the indentation (tabs) , spacing in log messages , and ran gofmt as suggested .
All checks are passing now. Please let me know if anything else is needed.
Thanks !

@ankitadhara28

Copy link
Copy Markdown
Contributor Author

This PR adds startup validation for required environment variables .

Closes #18

@AnkanMisra AnkanMisra left a comment •

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

@ankitadhara28 Code Looks Good But you missed 2 details

  1. Unit tests for validateConfig()
  • No test file added
  1. CHAIN_ID warning when unset
  • Currently warns about PORT, MODEL, VERIFIER_URL but not CHAIN_ID

After that ask for a Re-Review from me by up clicking the re-review button so i would get pinged

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 77c8b95 and baa2656.

📒 Files selected for processing (1)
  • gateway/config_test.go

Comment thread gateway/config_test.go Resolved
Comment thread gateway/config_test.go
Comment on lines +18 to +26
func TestValidateConfig_WithRequiredEnv(t *testing.T) {
// Set required environment variables
os.Setenv("OPENROUTER_API_KEY", "test-key")

err := validateConfig()
if err != nil {
t.Fatalf("Expected no error when all required environment variables are set, got: %v", err)
}
} No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add cleanup and consider testing optional variable behavior.

Similar to the previous test, this test modifies global environment state without cleanup. Additionally, according to the PR objectives, validateConfig() should warn about missing optional variables (PORT, MODEL, VERIFIER_URL, CHAIN_ID) and log a config summary on success. Consider adding tests to verify this behavior.

🔎 Recommended fix using `t.Setenv` and optional test coverage

Fix 1: Use t.Setenv for automatic cleanup

 func TestValidateConfig_WithRequiredEnv(t *testing.T) {
 	// Set required environment variables
-	os.Setenv("OPENROUTER_API_KEY", "test-key")
+	t.Setenv("OPENROUTER_API_KEY", "test-key")
 
 	err := validateConfig()
 	if err != nil {
 		t.Fatalf("Expected no error when all required environment variables are set, got: %v", err)
 	}
 }

Fix 2 (optional): Add test coverage for optional variables

Consider adding a test to verify warning behavior when optional variables are missing:

func TestValidateConfig_OptionalVariables(t *testing.T) {
	// Set required env var
	t.Setenv("OPENROUTER_API_KEY", "test-key")
	// Unset optional vars to trigger warnings
	t.Setenv("PORT", "")
	t.Setenv("MODEL", "")
	t.Setenv("VERIFIER_URL", "")
	
	err := validateConfig()
	if err != nil {
		t.Fatalf("Expected no error with optional vars missing, got: %v", err)
	}
	// Note: Verifying log output would require capturing stdout/stderr
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestValidateConfig_WithRequiredEnv(t *testing.T) {
// Set required environment variables
os.Setenv("OPENROUTER_API_KEY", "test-key")
err := validateConfig()
if err != nil {
t.Fatalf("Expected no error when all required environment variables are set, got: %v", err)
}
}
func TestValidateConfig_WithRequiredEnv(t *testing.T) {
// Set required environment variables
t.Setenv("OPENROUTER_API_KEY", "test-key")
err := validateConfig()
if err != nil {
t.Fatalf("Expected no error when all required environment variables are set, got: %v", err)
}
}
🤖 Prompt for AI Agents
In gateway/config_test.go around lines 18 to 26, the test sets a global env var
without cleanup and doesn't cover optional-variable warning behavior; update the
test to use t.Setenv("OPENROUTER_API_KEY", "test-key") so the environment is
restored automatically, and add an additional test (e.g.,
TestValidateConfig_OptionalVariables) that sets only the required
OPENROUTER_API_KEY and explicitly clears PORT, MODEL, VERIFIER_URL, CHAIN_ID
(via t.Setenv to empty) then calls validateConfig() asserting no error and
captures/logs output (or use a log capture helper) to assert warnings for
missing optional vars and that a config summary is logged on success.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
gateway/main.go (1)

91-92: Fix indentation and improve spacing consistency.

Line 91 appears to use spaces for indentation instead of tabs, which is inconsistent with Go conventions and the surrounding code. Additionally, the warning message on line 92 would read better with a space before the parenthesis.

🔎 Suggested formatting fixes
-    if os.Getenv("CHAIN_ID") == "" {
-		fmt.Println("[WARN] CHAIN_ID not set, using default: 8453(base)")
+	if os.Getenv("CHAIN_ID") == "" {
+		fmt.Println("[WARN] CHAIN_ID not set, using default: 8453 (base)")
 	}

After applying this change, please run gofmt -w gateway/main.go to ensure consistent formatting throughout the file.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between baa2656 and 64cd30c.

📒 Files selected for processing (1)
  • gateway/main.go
🔇 Additional comments (3)
gateway/main.go (3)

41-55: LGTM! Clean validation logic.

The validation function correctly checks for required environment variables and returns a clear error message. The design using a slice makes it easy to add more required variables in the future.


56-68: Excellent fail-fast validation!

The validation correctly runs after loading the .env file and provides clear, actionable error messages before exiting with a non-zero status. This addresses the critical ordering issue from previous reviews.


69-81: Configuration summary looks good!

The success logging provides a helpful non-sensitive configuration summary with proper formatting. The conditional printing ensures only set values are displayed.

@AnkanMisra

Copy link
Copy Markdown
Owner

@greptile final review

@greptile-apps greptile-apps Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Additional Comments (2)

  1. gateway/main.go, line 91 (link)

    syntax: inconsistent indentation (4 spaces instead of tab)

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

  2. gateway/config_test.go, line 18-26 (link)

    style: test doesn't clean up env var after setting it, could affect other tests

2 files reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

@ankitadhara28

Copy link
Copy Markdown
Contributor Author

Hi @AnkanMisra ,
I've fixed the unit tests using t.Setenv to avoid environment pollution and all tests are passing now.
Requesting re-review.
Thanks !

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
gateway/config_test.go (1)

14-21: Test cleanup improved; consider expanding coverage for optional variables.

The use of t.Setenv properly addresses the cleanup concern from the previous review.

Per the PR objectives, validateConfig() should warn about missing optional variables (PORT, MODEL, VERIFIER_URL, CHAIN_ID) and log a config summary on success. Consider adding a test that verifies this behavior for more complete coverage of the acceptance criteria.

🔎 Example test for optional variable warnings
func TestValidateConfig_OptionalVariables(t *testing.T) {
	// Set required env var
	t.Setenv("OPENROUTER_API_KEY", "test-key")
	// Explicitly unset optional vars to trigger warnings
	t.Setenv("PORT", "")
	t.Setenv("MODEL", "")
	t.Setenv("VERIFIER_URL", "")
	t.Setenv("CHAIN_ID", "")
	
	err := validateConfig()
	if err != nil {
		t.Fatalf("expected no error with optional vars missing, got: %v", err)
	}
	// Note: Verifying log output requires capturing stdout/stderr
	// or using a testing logger
}
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 64cd30c and 5fbf8b8.

📒 Files selected for processing (1)
  • gateway/config_test.go
🔇 Additional comments (1)
gateway/config_test.go (1)

5-12: Test pollution issue resolved!

The use of t.Setenv properly addresses the previous concern about environment variable cleanup. The test correctly verifies that validateConfig() returns an error when the required environment variable is missing.

@AnkanMisra

Copy link
Copy Markdown
Owner
Screenshot 2026-01-03 at 19 52 39 @ankitadhara28

You are 7 commit behind of the latest main branch please update to the latest changes in main branch

You need to rebase/merge main into his branch to get the OpenAPI files back
Otherwise when this PR merges, it will delete the OpenAPI work from PR #22

@AnkanMisra AnkanMisra left a comment •

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Code LG, update to the latest changes and ill merge it

@AnkanMisra
AnkanMisra merged commit d49dbc0 into AnkanMisra:main Jan 4, 2026
7 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jan 5, 2026
6 tasks done
@AnkanMisra AnkanMisra added level:beginner Small, well-scoped work suitable for newer contributors. and removed Easy labels May 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

level:beginner Small, well-scoped work suitable for newer contributors. SWoC26

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add environment variable validation on startup

2 participants