Skip to content

Potential fix for code scanning alert no. 1: Clear-text logging of sensitive information#9

Merged
CheFu-code merged 1 commit into
mainfrom
alert-autofix-1
Jun 3, 2026
Merged

Potential fix for code scanning alert no. 1: Clear-text logging of sensitive information#9
CheFu-code merged 1 commit into
mainfrom
alert-autofix-1

Conversation

@CheFu-code

@CheFu-code CheFu-code commented Jun 3, 2026

Copy link
Copy Markdown
Owner

Potential fix for https://github.com/CheFu-code/CheFu-Academy-SDK/security/code-scanning/1

The correct fix is to stop logging raw request payloads and instead log a sanitized/redacted version. Keep functionality (debug observability) while preventing sensitive disclosure by masking known secret keys recursively (for nested objects), and avoiding unsafe serialization of unknown values.

Best single fix in src/client.ts:

  • Add a small redaction helper that traverses objects/arrays and replaces values for sensitive keys (e.g., password, token, authToken, apiKey, authorization, secret, etc.) with "[REDACTED]".
  • Update logRequest to log the sanitized payload instead of raw data.
  • Keep existing debug flag behavior and method/url logging unchanged.

This preserves existing SDK behavior (still logs requests in debug mode) while removing clear-text sensitive leakage.

Suggested fixes powered by Copilot Autofix. Review carefully before merging.

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Debug logging now redacts sensitive fields from request payloads to prevent exposure of sensitive information when SDK debugging is enabled.

…nsitive information

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Jun 3, 2026

Copy link
Copy Markdown

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 84ec72ea-4a8a-47eb-b18b-3bf7d7be646d

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch alert-autofix-1

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

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
src/client.ts (3)

166-184: ⚖️ Poor tradeoff

Consider circular reference protection.

The recursive implementation could stack overflow if the request payload contains circular references. While typical API request data is JSON-serializable and won't have circular references, a developer could accidentally pass a non-serializable object with circular structures to a request method.

🛡️ Suggested protection against circular references
-private redactSensitiveData(value: unknown): unknown {
+private redactSensitiveData(value: unknown, seen = new WeakSet<object>()): unknown {
     if (Array.isArray(value)) {
+        if (seen.has(value)) return '[CIRCULAR]';
+        seen.add(value);
-        return value.map((item) => this.redactSensitiveData(item));
+        return value.map((item) => this.redactSensitiveData(item, seen));
     }

     if (value && typeof value === 'object') {
+        if (seen.has(value)) return '[CIRCULAR]';
+        seen.add(value);
         const redacted: Record<string, unknown> = {};
         for (const [key, nestedValue] of Object.entries(
             value as Record<string, unknown>,
         )) {
             redacted[key] = this.isSensitiveKey(key)
                 ? '[REDACTED]'
-                : this.redactSensitiveData(nestedValue);
+                : this.redactSensitiveData(nestedValue, seen);
         }
         return redacted;
     }

     return value;
 }

Alternatively, document the assumption that request data must be JSON-serializable:

+/**
+ * Recursively redacts sensitive fields from request data.
+ * `@param` value - Request payload (must be JSON-serializable, no circular refs)
+ * `@returns` Redacted copy with sensitive values replaced by '[REDACTED]'
+ */
 private redactSensitiveData(value: unknown): unknown {
🤖 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 `@src/client.ts` around lines 166 - 184, redactSensitiveData currently recurses
without guarding against circular references; update redactSensitiveData to
accept (or create internally) a WeakSet named seen and add each object/array
when first visited, skip or return a placeholder like '[CIRCULAR]' if an object
is already in seen, and ensure arrays and nested objects use the same seen set
when recursing; reference the redactSensitiveData function and isSensitiveKey to
locate where to add the WeakSet tracking and circular-return behavior.

188-188: 💤 Low value

Simplify undefined handling for consistency.

Converting undefined to an empty string changes the debug output when no request body is present. It would be clearer to either log undefined as-is or not log the data parameter at all for GET/DELETE requests.

♻️ Suggested simplification

Option 1: Pass through undefined (simpler)

-const safeData = data === undefined ? '' : this.redactSensitiveData(data);
+const safeData = data !== undefined ? this.redactSensitiveData(data) : undefined;
 // eslint-disable-next-line no-console
 console.log(`[CheFu SDK] ${method.toUpperCase()} ${url}`, safeData);

Option 2: Omit data parameter when undefined (cleaner output)

-const safeData = data === undefined ? '' : this.redactSensitiveData(data);
-// eslint-disable-next-line no-console
-console.log(`[CheFu SDK] ${method.toUpperCase()} ${url}`, safeData);
+// eslint-disable-next-line no-console
+if (data !== undefined) {
+    const safeData = this.redactSensitiveData(data);
+    console.log(`[CheFu SDK] ${method.toUpperCase()} ${url}`, safeData);
+} else {
+    console.log(`[CheFu SDK] ${method.toUpperCase()} ${url}`);
+}
🤖 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 `@src/client.ts` at line 188, The current assignment for safeData converts
undefined to an empty string which alters debug output; change the logic in
src/client.ts so safeData preserves undefined instead of turning it into '' by
only calling redactSensitiveData when data is defined (e.g., set safeData to
undefined when data is undefined, otherwise to this.redactSensitiveData(data));
update any subsequent logging or usage that expects the previous '' behavior to
handle undefined accordingly.

150-164: 🏗️ Heavy lift

Sensitive-key detection already covers current SDK payload fields; optional hardening for future naming variants

  • isSensitiveKey() lowercases the key name, so SDK field names like password, apiKey, authToken, idToken, and refreshToken map to entries in the list (and /auth/login request payload uses password).
  • Codebase search shows no usage of snake_case / hyphenated variants like access_token, api_key, or client_secret in request payloads, so the initially flagged gap doesn’t appear for current code paths.
  • Consider expanding matching (e.g., _/- normalization and/or token/secret substring/pattern coverage) to avoid future false negatives if payload field naming changes.
🤖 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 `@src/client.ts` around lines 150 - 164, The isSensitiveKey function currently
lowercases the key but only matches exact names; update isSensitiveKey to
normalize separators (replace '_' and '-' with '' or ' ') and then check both
exact names and substring/patterns (e.g., contains 'token', 'secret', 'key',
'pwd', 'pass') to catch variants like access_token, api-key, client_secret or
authToken; locate and modify the isSensitiveKey method to perform the
normalization and expanded matching while keeping the existing explicit list for
exact matches.
🤖 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.

Nitpick comments:
In `@src/client.ts`:
- Around line 166-184: redactSensitiveData currently recurses without guarding
against circular references; update redactSensitiveData to accept (or create
internally) a WeakSet named seen and add each object/array when first visited,
skip or return a placeholder like '[CIRCULAR]' if an object is already in seen,
and ensure arrays and nested objects use the same seen set when recursing;
reference the redactSensitiveData function and isSensitiveKey to locate where to
add the WeakSet tracking and circular-return behavior.
- Line 188: The current assignment for safeData converts undefined to an empty
string which alters debug output; change the logic in src/client.ts so safeData
preserves undefined instead of turning it into '' by only calling
redactSensitiveData when data is defined (e.g., set safeData to undefined when
data is undefined, otherwise to this.redactSensitiveData(data)); update any
subsequent logging or usage that expects the previous '' behavior to handle
undefined accordingly.
- Around line 150-164: The isSensitiveKey function currently lowercases the key
but only matches exact names; update isSensitiveKey to normalize separators
(replace '_' and '-' with '' or ' ') and then check both exact names and
substring/patterns (e.g., contains 'token', 'secret', 'key', 'pwd', 'pass') to
catch variants like access_token, api-key, client_secret or authToken; locate
and modify the isSensitiveKey method to perform the normalization and expanded
matching while keeping the existing explicit list for exact matches.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 269b7153-7a9d-4ef6-b876-d3ad878f527d

📥 Commits

Reviewing files that changed from the base of the PR and between 12d791b and 559e10e.

📒 Files selected for processing (1)
  • src/client.ts

@CheFu-code CheFu-code marked this pull request as ready for review June 3, 2026 22:00
@CheFu-code CheFu-code merged commit e72a2f1 into main Jun 3, 2026
4 of 5 checks passed
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