Skip to content

fix: add validation for empty and blank API keys - #206

Open
anshul23102 wants to merge 1 commit into
gunjanghate:mainfrom
anshul23102:fix/153-api-key-validation
Open

fix: add validation for empty and blank API keys#206
anshul23102 wants to merge 1 commit into
gunjanghate:mainfrom
anshul23102:fix/153-api-key-validation

Conversation

@anshul23102

@anshul23102 anshul23102 commented Jun 12, 2026

Copy link
Copy Markdown

Fixes #153: gg config allows saving empty or blank string spaces as valid API Keys

Summary

This PR adds comprehensive validation to prevent saving empty or whitespace-only API keys in the configuration system. It validates against provider-specific format rules to ensure users can only save valid API keys.

Changes Made

  • Enhanced saveProviderApiKey function to validate against provider-specific formats
  • Added early validation check in config command handler with clear error messages
  • Improved error output with helpful troubleshooting tips
  • Added comprehensive test suite (apiKeyValidation.test.js) covering:
    • Empty string rejection
    • Whitespace-only string rejection
    • Null/undefined rejection
    • Non-string type rejection
    • Valid key acceptance with whitespace trimming
    • Provider-specific validation
    • Maximum length enforcement

Test Plan

  1. Test empty API key rejection: gg config "" --provider gemini
  2. Test whitespace-only rejection: gg config " " --provider gemini
  3. Test valid key acceptance: gg config "AIzaSyValidKey..." --provider gemini
  4. Run test suite: node cli/tests/apiKeyValidation.test.js
  5. Verify error messages guide users on invalid input

All 14 new validation tests pass successfully.

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • API key validation now strictly rejects empty, whitespace-only, and improperly formatted values with clear, actionable error messages
    • Enhanced error messages include detailed troubleshooting guidance and verification steps when API key configuration or validation fails
    • Provider-specific validation ensures API keys meet the exact format requirements for each supported cloud service provider
    • Automatic whitespace trimming during input eliminates accidental spacing and unwanted formatting errors

Add strict validation to prevent saving empty or whitespace-only API keys.
Implement provider-specific format validation using existing validateApiKey rules.
Enhance error messages to guide users when invalid API keys are provided.

Changes:
- Enhanced saveProviderApiKey to validate against provider-specific formats
- Added early validation check in config command handler
- Improved error output with troubleshooting tips
- Added comprehensive test suite for API key validation

Fixes issue gunjanghate#153: API keys cannot be empty or contain only whitespace
@vercel

vercel Bot commented Jun 12, 2026

Copy link
Copy Markdown

@anshul23102 is attempting to deploy a commit to the Gunjan Ghate's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

API key validation is now enforced strictly in the config command. Input is trimmed and validated via validateApiKey; non-string, empty, or whitespace-only values are rejected with provider-specific error messages. Validated keys are stored in keytar and used to encrypt the config.json value, replacing the previous behavior of storing untrimmed input. Enhanced error handling provides troubleshooting guidance for validation failures.

Changes

API Key Validation and Storage

Layer / File(s) Summary
API Key validation and keytar/config storage
cli/commands/config.js
saveProviderApiKey validates input format via validateApiKey, rejects empty/whitespace/non-string values with provider-specific error messages, and stores the validated key in keytar (if available) and config.json encryption instead of the raw trimmed input.
CLI error handling and troubleshooting guidance
cli/commands/config.js
Config command adds explicit guard for whitespace-only apikey strings with clearer "API key cannot be empty…" message and usage guidance. Failure catch block now includes troubleshooting steps to verify the key is non-empty, provider name is correct, and API key format matches expectations.

API Key Validation Test Suite

Layer / File(s) Summary
Test utilities and assertion framework
cli/tests/apiKeyValidation.test.js
Defines lightweight test harness with assert and run helpers that execute test functions, log pass/fail results, and maintain counters for overall summary reporting.
Validation test cases
cli/tests/apiKeyValidation.test.js
Comprehensive test coverage for rejecting empty, whitespace-only, non-string, null, undefined, overly-long, invalid-format, and invalid-character inputs. Validates successful acceptance of correctly-formatted keys for gemini, groq, and openai providers.
Test exit handling and summary reporting
cli/tests/apiKeyValidation.test.js
Process exits with code 1 when any test fails; final summary log reports total passed and failed test counts.

Sequence Diagram

sequenceDiagram
  participant User
  participant ConfigCmd as Config CLI Command
  participant SaveFunc as saveProviderApiKey
  participant Validator as validateApiKey
  participant Keytar
  participant ConfigFile as config.json
  User->>ConfigCmd: Provide API key input
  ConfigCmd->>SaveFunc: Pass raw input + provider
  SaveFunc->>SaveFunc: Trim and check for empty/whitespace
  SaveFunc->>Validator: Validate format for provider
  alt Valid format
    Validator-->>SaveFunc: Validation passed
    SaveFunc->>Keytar: Store validated key with provider account
    SaveFunc->>ConfigFile: Encrypt and persist validated key
    SaveFunc-->>ConfigCmd: Success
  else Invalid format
    Validator-->>SaveFunc: Validation failed
    SaveFunc-->>ConfigCmd: Error with provider-specific message
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

gssoc:approved, level:intermediate

Poem

A rabbit checks each API key with care,
No empty spaces lurking in there—
Trim and validate before you save,
Keep those credentials strong and brave!
🐰✨🔐

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding validation for empty and blank API keys, which directly matches the primary objective of preventing invalid API key persistence.
Description check ✅ Passed The description covers the main objectives, summarizes changes made, includes a test plan with specific commands, and provides testing outcomes. While some template sections are incomplete, the core content is comprehensive and addresses the issue adequately.
Linked Issues check ✅ Passed The code changes fully address issue #153 requirements: trimming whitespace-only/empty inputs, validating against provider-specific formats, preventing invalid values from persisting, and including clear error messages.
Out of Scope Changes check ✅ Passed All changes in config.js and the new test file are directly scoped to the API key validation requirements. No unrelated modifications or scope creep detected.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install timed out. The project may have too many dependencies for the sandbox.


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.

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cli/commands/config.js`:
- Around line 585-594: The catch block that logs "Failed to save configuration."
currently falls through to the trailing process.exit(0), causing a success exit
code on failure; inside that catch block (the one that prints troubleshooting
tips) add a process.exit(1) after logging so the CLI returns a non‑zero exit
code on error and does not reach the final process.exit(0), ensuring failures
are signaled to callers.

In `@cli/tests/apiKeyValidation.test.js`:
- Around line 91-95: The summary log is placed after process.exit(1) so it never
prints on failure; move the console.log that prints `${passed} passed, ${failed}
failed` to before the conditional exit (or at least call it before invoking
process.exit) so the summary is always emitted when failed > 0; update the block
around the variables passed/failed and the process.exit(1) call accordingly to
log first then exit.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2093604e-cbc1-42f4-92d8-84262306d0a2

📥 Commits

Reviewing files that changed from the base of the PR and between a2983d4 and 6dec2a1.

📒 Files selected for processing (2)
  • cli/commands/config.js
  • cli/tests/apiKeyValidation.test.js

Comment thread cli/commands/config.js
Comment on lines 585 to 594
} catch (err) {
console.error(chalk.red('Failed to save configuration.'));
console.error(chalk.yellow(err.message));
console.log(chalk.gray(''));
console.log(chalk.cyan('Troubleshooting tips:'));
console.log(chalk.gray(' 1. Ensure your API key is not empty or only whitespace'));
console.log(chalk.gray(' 2. Check that you are using the correct provider name'));
console.log(chalk.gray(' 3. Verify your API key format matches the expected pattern'));
}
process.exit(0);

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 | 🟡 Minor | ⚡ Quick win

Add process.exit(1) in the catch block to signal failure.

The catch block now correctly outputs troubleshooting tips, but the control flow falls through to process.exit(0) at line 594, causing the CLI to exit with a success code even when validation fails. This can mislead scripts or CI pipelines that check exit codes.

Proposed fix
             console.log(chalk.gray('  1. Ensure your API key is not empty or only whitespace'));
             console.log(chalk.gray('  2. Check that you are using the correct provider name'));
             console.log(chalk.gray('  3. Verify your API key format matches the expected pattern'));
+            process.exit(1);
         }
-        process.exit(0);
     });
📝 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
} catch (err) {
console.error(chalk.red('Failed to save configuration.'));
console.error(chalk.yellow(err.message));
console.log(chalk.gray(''));
console.log(chalk.cyan('Troubleshooting tips:'));
console.log(chalk.gray(' 1. Ensure your API key is not empty or only whitespace'));
console.log(chalk.gray(' 2. Check that you are using the correct provider name'));
console.log(chalk.gray(' 3. Verify your API key format matches the expected pattern'));
}
process.exit(0);
} catch (err) {
console.error(chalk.red('Failed to save configuration.'));
console.error(chalk.yellow(err.message));
console.log(chalk.gray(''));
console.log(chalk.cyan('Troubleshooting tips:'));
console.log(chalk.gray(' 1. Ensure your API key is not empty or only whitespace'));
console.log(chalk.gray(' 2. Check that you are using the correct provider name'));
console.log(chalk.gray(' 3. Verify your API key format matches the expected pattern'));
process.exit(1);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/commands/config.js` around lines 585 - 594, The catch block that logs
"Failed to save configuration." currently falls through to the trailing
process.exit(0), causing a success exit code on failure; inside that catch block
(the one that prints troubleshooting tips) add a process.exit(1) after logging
so the CLI returns a non‑zero exit code on error and does not reach the final
process.exit(0), ensuring failures are signaled to callers.

Comment on lines +91 to +95
if (failed > 0) {
process.exit(1);
}

console.log(`\n${passed} passed, ${failed} failed`);

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 | 🟡 Minor | ⚡ Quick win

Move summary log before exit to ensure it prints on failure.

When tests fail, process.exit(1) on line 92 terminates immediately, so line 95 never executes and the summary is not printed. Users lose visibility into the total passed/failed counts when failures occur.

📊 Proposed fix to show summary before exit
+console.log(`\n${passed} passed, ${failed} failed`);
+
 if (failed > 0) {
     process.exit(1);
 }

-console.log(`\n${passed} passed, ${failed} failed`);
📝 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
if (failed > 0) {
process.exit(1);
}
console.log(`\n${passed} passed, ${failed} failed`);
console.log(`\n${passed} passed, ${failed} failed`);
if (failed > 0) {
process.exit(1);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/tests/apiKeyValidation.test.js` around lines 91 - 95, The summary log is
placed after process.exit(1) so it never prints on failure; move the console.log
that prints `${passed} passed, ${failed} failed` to before the conditional exit
(or at least call it before invoking process.exit) so the summary is always
emitted when failed > 0; update the block around the variables passed/failed and
the process.exit(1) call accordingly to log first then exit.

@gunjanghate

Copy link
Copy Markdown
Owner

@anshul23102 add demo/screenshots of working

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.

bug: gg config allows saving empty or blank string spaces as valid API Keys

2 participants