urBackend icon indicating copy to clipboard operation
urBackend copied to clipboard

Prevent internal error details from reaching API clients and add safe Kiroo replay IDs

Open anshul23102 opened this issue 4 months ago • 7 comments

Summary

Unhandled exceptions must not expose internal details to API clients.

The current pattern returns a generic response in some controllers. It does not provide a consistent final error boundary. Express can return a stack trace when an error reaches its default error handler. The application also needs a safe way to correlate a client error with a reproducible Kiroo capture.

Use @kiroo/sdk for request/response replay IDs. Do not use Kiroo as the only production error log. Kiroo captures the request and response. It does not capture the JavaScript stack trace.

Kiroo prerequisite

Release a Kiroo version that meets these requirements before this application uses Kiroo captures in production.

  1. Redact sensitive values in all captured locations:
    • request headers;
    • response headers;
    • request-body fields;
    • response-body fields;
    • URL query parameters.
  2. Preserve recursive, case-insensitive redaction for object keys.
  3. Provide configuration for application-specific redaction:
    • redactKeys;
    • redactHeaders;
    • redactQueryParams;
    • a custom redaction callback, if supported.
  4. Include safe default redaction for credential fields and common personal-data fields.
  5. Sanitize response headers before Kiroo stores them. @kiroo/sdk 0.1.2 stores res.getHeaders() without sanitization.
  6. Document that the Supabase bucket must be private, that capture access must be restricted, and that retention must meet the application's privacy policy.
  7. Document that Kiroo does not capture a JavaScript stack trace. The application must keep stack traces in protected server-side logs.
  8. Update the Kiroo error example. It must not return internal error text such as "Downstream timeout" to a client.
  9. Add tests for nested fields, case variants, query parameters, request headers, and response headers.

@kiroo/sdk 0.1.2 already provides an X-Kiroo-Replay-ID header and captures all responses with status >=400, even when sampleRate is 0.

Application changes

  1. Register a final Express error-handling middleware after all routes.
  2. Log the error, stack trace, HTTP method, route, and Kiroo replay ID to protected server-side logs.
  3. Return a generic 500 response for unexpected errors.
  4. Include the Kiroo replay ID in the generic error response.
  5. Do not return err.message, err.stack, database errors, upstream error payloads, or internal file paths.
  6. Keep Kiroo capture middleware before routes and the final error handler.
  7. Configure sampleRate: 0 if the application must capture only error responses. Kiroo still captures status codes >=400.

Example response shape:

const replayId = res.get("X-Kiroo-Replay-ID");

res.status(500).json({
  success: false,
  message: "Internal server error",
  data: { replayId }
});

Debugging workflow

  1. A client receives a generic error response and replayId.
  2. The operator locates the protected server-side error log by replayId.
  3. The operator uses the replay ID with Kiroo to fetch and replay the sanitized request locally.
  4. The operator uses the protected server-side log for the stack trace.

Acceptance criteria

  • API clients never receive stack traces or unexpected internal error details.
  • The final Express error handler handles errors that reach it.
  • Each error response contains the Kiroo replay ID.
  • Production logs contain the stack trace and the same replay ID.
  • Kiroo captures redact the configured credentials and personal data from bodies, headers, and URL query parameters.
  • Kiroo storage is private and has documented retention and access controls.
  • Tests cover the final error handler and Kiroo redaction behavior.

anshul23102 avatar Jul 31 '26 11:07 anshul23102

@geturbackend Could you please assign this issue to me? I'd like to work on it under GSSoC '26. /assign /claim

anshul23102 avatar Jul 31 '26 11:07 anshul23102

@coderabbitai If this is implemented, then how can i Debug on production??

yash-pouranik avatar Aug 01 '26 13:08 yash-pouranik

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

gh issue view 378 \
  --repo geturbackend/urBackend \
  --json number,title,body,labels,assignees,comments,url \
  --jq '{number, title, body, labels: [.labels[].name], assignees: [.assignees[].login], url, comments: [.comments[] | {author: .author.login, body: .body, createdAt: .createdAt}]}'

Length of output: 2261


@yash-pouranik, keep the error details in server-side logs. Do not return them in the API response.

The centralized error handler should:

  1. Generate or accept a request/correlation ID.
  2. Log the error message, stack trace, route, method, request ID, and safe context to the production log system.
  3. Redact secrets, tokens, passwords, and personal data from logs.
  4. Return only a generic 500 response and the request ID to the client.

Example:

app.use((err, req, res, next) => {
  const requestId = req.id;

  logger.error({
    err,
    requestId,
    method: req.method,
    path: req.originalUrl,
  }, "Unhandled request error");

  res.status(500).json({
    success: false,
    message: "Internal server error",
    requestId,
  });
});

Then, use the requestId to find the matching error in Railway, Render, Docker, or another log aggregator.

The issue's example should not disable production error logging entirely. It should only prevent stack traces and internal details from reaching API clients. A structured logger with protected log access is the recommended production-debugging path.

🐇🔎

You are interacting with an AI system.

coderabbitai[bot] avatar Aug 01 '26 13:08 coderabbitai[bot]

can we utilize kiroo sdk??

as it is already implemented?

@coderabbitai

u can check here - https://kiroo.bitbros.in/

yash-pouranik avatar Aug 01 '26 13:08 yash-pouranik

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- Issue `#378` ---'
gh issue view 378 \
  --repo geturbackend/urBackend \
  --json number,title,body,comments,url \
  --jq '{number,title,body,url,comments:[.comments[]|{author:.author.login,body:.body}]}'

echo '--- Kiroo documentation landing page ---'
curl -fsSL --max-time 20 https://kiroo.bitbros.in/ | head -c 30000
printf '\n'

echo '--- Repository files that reference Kiroo ---'
rg -n -i -C 3 '\bkiroo\b|`@kiroo`|from\s+["'\''][^"'\'']*kiroo|require\(\s*["'\''][^"'\'']*kiroo' . \
  -g '!node_modules' -g '!dist' -g '!build' || true

echo '--- Candidate manifests and error/logging files ---'
fd -HI -t f '^(package\.json|.*(error|logger|logging|exception|handler).*\.(js|ts|mjs|cjs))$' . \
  -E node_modules -E dist -E build | sort

Length of output: 23433


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- apps/public-api/src/app.js structure ---'
ast-grep outline apps/public-api/src/app.js --items all --view expanded || true
echo '--- Kiroo, route, and terminal middleware context: public API ---'
rg -n -C 12 '\bcapture\s*\(|app\.(use|get|post|put|patch|delete)\s*\(|X-Kiroo-Replay-ID|error' \
  apps/public-api/src/app.js

echo '--- apps/dashboard-api/src/app.js structure ---'
ast-grep outline apps/dashboard-api/src/app.js --items all --view expanded || true
echo '--- Kiroo, route, and terminal middleware context: dashboard API ---'
rg -n -C 12 '\bcapture\s*\(|app\.(use|get|post|put|patch|delete)\s*\(|X-Kiroo-Replay-ID|error' \
  apps/dashboard-api/src/app.js

echo '--- userAuth controller candidates ---'
fd -HI -t f -i 'userAuth.controller.js' . -E node_modules -E dist -E build \
  -x sh -c 'echo "--- $1 ---"; ast-grep outline "$1" --items all --view expanded; rg -n -C 8 "catch\s*\(|console\.error|res\.status\(500\)" "$1"' sh {}

echo '--- Kiroo SDK documentation ---'
curl -fsSL --max-time 20 https://kiroo.bitbros.in/docs.html | head -c 60000
printf '\n--- Kiroo repository package/source metadata ---\n'
gh api repos/yash-pouranik/kiroo/contents \
  --jq '.[] | {name,type,path,download_url}' || true

Length of output: 77215


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- Kiroo package workspace map ---'
gh api repos/yash-pouranik/kiroo/contents/packages \
  --jq '.[] | {name,type,path}' || true

echo '--- Files relevant to SDK capture, sampling, and sanitization ---'
gh api repos/yash-pouranik/kiroo/git/trees/main?recursive=1 \
  --jq -r '.tree[] | select(.type == "blob") | .path' \
  | rg -i '(^|/)(sdk|capture|middleware|sanitize|redact|package)\.(js|cjs|mjs|ts)$|packages/.*/(src/)?' \
  | head -n 160

echo '--- Search all Kiroo source blobs for capture configuration ---'
for path in $(gh api repos/yash-pouranik/kiroo/git/trees/main?recursive=1 --jq -r '.tree[] | select(.type == "blob") | .path' | rg '^(packages|src)/.*\.(js|cjs|mjs|ts)$'); do
  content=$(gh api "repos/yash-pouranik/kiroo/contents/$path" --jq '.content' 2>/dev/null | base64 -d 2>/dev/null || true)
  if printf '%s' "$content" | rg -qi 'sampleRate|sanitize|redact|X-Kiroo-Replay-ID|function capture|const capture'; then
    printf '\n--- %s ---\n' "$path"
    printf '%s\n' "$content" | rg -n -i -C 12 'sampleRate|sanitize|redact|X-Kiroo-Replay-ID|function capture|const capture'
  fi
done

Length of output: 1730


🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo='yash-pouranik/kiroo'

echo '--- Kiroo capture package files ---'
gh api "repos/${repo}/git/trees/main?recursive=1" \
  --jq -r '.tree[] | select(.type == "blob") | .path' \
  | rg '^packages/kiroo-capture/'

echo '--- Kiroo capture package metadata ---'
gh api "repos/${repo}/contents/packages/kiroo-capture/package.json" \
  --jq '.content' | base64 -d

echo '--- Kiroo capture source: sampling, response IDs, and sensitive-data handling ---'
gh api "repos/${repo}/git/trees/main?recursive=1" \
  --jq -r '.tree[] | select(.type == "blob") | .path' \
  | rg '^packages/kiroo-capture/.*\.(js|cjs|mjs|ts)$' \
  | while IFS= read -r path; do
      content=$(gh api "repos/${repo}/contents/${path}" --jq '.content' | base64 -d)
      printf '\n--- %s ---\n' "$path"
      printf '%s\n' "$content" | rg -n -i -C 14 \
        'sampleRate|Math\.random|statusCode|status\s*[>=<]|X-Kiroo-Replay-ID|sanitize|redact|authorization|cookie|password|token|capture' \
        || true
    done

Length of output: 1387


🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo='yash-pouranik/kiroo'

echo '--- Kiroo capture package root ---'
gh api -X GET "repos/${repo}/contents/packages/kiroo-capture" \
  --jq '.[] | {name,path,type,download_url}'

echo '--- Kiroo capture package metadata ---'
gh api -X GET "repos/${repo}/contents/packages/kiroo-capture/package.json" \
  --jq '.content' | base64 -d

echo '--- Kiroo capture source files ---'
for directory in \
  'packages/kiroo-capture/src' \
  'packages/kiroo-capture/lib' \
  'packages/kiroo-capture/dist'
do
  files=$(gh api -X GET "repos/${repo}/contents/${directory}" \
    --jq -r '.[]? | select(.type == "file") | .path' 2>/dev/null || true)
  if [ -n "$files" ]; then
    printf '%s\n' "$files"
    while IFS= read -r path; do
      printf '\n--- %s ---\n' "$path"
      gh api -X GET "repos/${repo}/contents/${path}" --jq '.content' \
        | base64 -d \
        | rg -n -i -C 14 \
          'sampleRate|Math\.random|statusCode|status\s*[>=<]|X-Kiroo-Replay-ID|sanitize|redact|authorization|cookie|password|token|capture' \
        || true
    done <<< "$files"
  fi
done

Length of output: 3017


🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo='yash-pouranik/kiroo'
for path in \
  'packages/kiroo-capture/index.js' \
  'packages/kiroo-capture/sanitizer.js' \
  'packages/kiroo-capture/storage.js' \
  'packages/kiroo-capture/README.md'
do
  printf '\n--- %s ---\n' "$path"
  gh api -X GET "repos/${repo}/contents/${path}" --jq '.content' | base64 -d
done

Length of output: 10388


@yash-pouranik, yes. Use the existing Kiroo SDK for this issue.

It is already registered before routes and error handlers in:

  • apps/public-api/src/app.js
  • apps/dashboard-api/src/app.js

The current sampleRate: 0 is correct for this use case. Kiroo captures all responses with status >=400. It does not capture successful responses when sampleRate is 0.

For an unexpected production failure:

  1. The global error handler returns a generic 500 response.
  2. The handler includes the Kiroo replay ID in the response body.
  3. Kiroo stores the sanitized request and response in Supabase.
  4. A maintainer runs kiroo fetch <replay-id>.
  5. A maintainer runs kiroo replay <replay-id> --target http://localhost:<port> and debugs locally.

The error response can use this pattern:

const replayId = res.get("X-Kiroo-Replay-ID");

res.status(500).json({
  success: false,
  data: { replayId },
  message: "Internal server error"
});

Do not return err.message or err.stack for unexpected errors.

One security condition remains. Kiroo 0.1.2 redacts passwords, tokens, authorization headers, cookies, secrets, API keys, and payment fields. It does not redact all personal data by default. For example, an email field can remain in a captured request body. Before enabling production captures, extend the sanitizer or ensure that the stored capture data meets the project privacy policy.

Kiroo captures the request and response. It does not capture the JavaScript stack trace. Keep protected server-side error logs for stack traces, and use the replay ID to reproduce the request locally.

You are interacting with an AI system.

coderabbitai[bot] avatar Aug 01 '26 13:08 coderabbitai[bot]

Please let me know what needs to be updated in kiroo As I only maintains it. Then re edit this issue

@coderabbitai

yash-pouranik avatar Aug 01 '26 13:08 yash-pouranik

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- Issue `#378` ---'
gh issue view 378 \
  --repo geturbackend/urBackend \
  --json number,title,body,labels,url,comments \
  --jq '{number,title,body,labels:[.labels[].name],url,comments:[.comments[]|{author:.author.login,body:.body,createdAt}]}'

repo='yash-pouranik/kiroo'
ref='main'

echo '--- Kiroo capture package metadata ---'
gh api "repos/${repo}/contents/packages/kiroo-capture/package.json?ref=${ref}" \
  --jq '.content' | base64 -d

echo '--- Kiroo capture source files ---'
gh api "repos/${repo}/git/trees/${ref}?recursive=1" \
  --jq -r '.tree[] | select(.type == "blob") | .path' \
  | rg '^packages/kiroo-capture/(index\.js|sanitizer\.js|storage\.js|README\.md)$' \
  | while IFS= read -r path; do
      printf '\n--- %s ---\n' "$path"
      gh api "repos/${repo}/contents/${path}?ref=${ref}" --jq '.content' | base64 -d
    done

Length of output: 24637


🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo='yash-pouranik/kiroo'
ref='main'

echo '--- Kiroo capture package files ---'
gh api "repos/${repo}/git/trees/${ref}" -F recursive=1 \
  --jq -r '.tree[] | select(.type == "blob") | .path' \
  | rg '^packages/kiroo-capture/(index\.js|sanitizer\.js|storage\.js|README\.md)$' \
  | while IFS= read -r path; do
      printf '\n--- %s ---\n' "$path"
      gh api "repos/${repo}/contents/${path}" -F ref="${ref}" \
        --jq '.content' | base64 -d
    done

Length of output: 862


🏁 Script executed:

#!/bin/bash
set -euo pipefail

for path in \
  'packages/kiroo-capture/index.js' \
  'packages/kiroo-capture/sanitizer.js' \
  'packages/kiroo-capture/storage.js' \
  'packages/kiroo-capture/README.md'
do
  printf '\n--- %s ---\n' "$path"
  curl -fsSL --max-time 20 \
    "https://raw.githubusercontent.com/yash-pouranik/kiroo/main/${path}"
done

Length of output: 10386


🏁 Script executed:

#!/bin/bash
set -euo pipefail

body_file="$(mktemp)"
cat > "$body_file" <<'EOF'
## Summary

Unhandled exceptions must not expose internal details to API clients.

The current pattern returns a generic response in some controllers. It does not provide a consistent final error boundary. Express can return a stack trace when an error reaches its default error handler. The application also needs a safe way to correlate a client error with a reproducible Kiroo capture.

Use `@kiroo/sdk` for request/response replay IDs. Do not use Kiroo as the only production error log. Kiroo captures the request and response. It does not capture the JavaScript stack trace.

## Kiroo prerequisite

Release a Kiroo version that meets these requirements before this application uses Kiroo captures in production.

1. Redact sensitive values in **all** captured locations:
   - request headers;
   - response headers;
   - request-body fields;
   - response-body fields;
   - URL query parameters.
2. Preserve recursive, case-insensitive redaction for object keys.
3. Provide configuration for application-specific redaction:
   - `redactKeys`;
   - `redactHeaders`;
   - `redactQueryParams`;
   - a custom redaction callback, if supported.
4. Include safe default redaction for credential fields and common personal-data fields.
5. Sanitize response headers before Kiroo stores them. `@kiroo/sdk` `0.1.2` stores `res.getHeaders()` without sanitization.
6. Document that the Supabase bucket must be private, that capture access must be restricted, and that retention must meet the application's privacy policy.
7. Document that Kiroo does not capture a JavaScript stack trace. The application must keep stack traces in protected server-side logs.
8. Update the Kiroo error example. It must not return internal error text such as `"Downstream timeout"` to a client.
9. Add tests for nested fields, case variants, query parameters, request headers, and response headers.

`@kiroo/sdk` `0.1.2` already provides an `X-Kiroo-Replay-ID` header and captures all responses with status `>=400`, even when `sampleRate` is `0`.

## Application changes

1. Register a final Express error-handling middleware after all routes.
2. Log the error, stack trace, HTTP method, route, and Kiroo replay ID to protected server-side logs.
3. Return a generic `500` response for unexpected errors.
4. Include the Kiroo replay ID in the generic error response.
5. Do not return `err.message`, `err.stack`, database errors, upstream error payloads, or internal file paths.
6. Keep Kiroo capture middleware before routes and the final error handler.
7. Configure `sampleRate: 0` if the application must capture only error responses. Kiroo still captures status codes `>=400`.

Example response shape:

```js
const replayId = res.get("X-Kiroo-Replay-ID");

res.status(500).json({
  success: false,
  message: "Internal server error",
  data: { replayId }
});

Debugging workflow

  1. A client receives a generic error response and replayId.
  2. The operator locates the protected server-side error log by replayId.
  3. The operator uses the replay ID with Kiroo to fetch and replay the sanitized request locally.
  4. The operator uses the protected server-side log for the stack trace.

Acceptance criteria

  • API clients never receive stack traces or unexpected internal error details.
  • The final Express error handler handles errors that reach it.
  • Each error response contains the Kiroo replay ID.
  • Production logs contain the stack trace and the same replay ID.
  • Kiroo captures redact the configured credentials and personal data from bodies, headers, and URL query parameters.
  • Kiroo storage is private and has documented retention and access controls.
  • Tests cover the final error handler and Kiroo redaction behavior. EOF

gh issue edit 378
--repo geturbackend/urBackend
--title "Prevent internal error details from reaching API clients and add safe Kiroo replay IDs"
--body-file "$body_file"

rm -f "$body_file"

gh issue view 378
--repo geturbackend/urBackend
--json title,body,url
--jq '{title,body,url}'


Length of output: 8278

---

</details>

`@yash-pouranik`, I updated [issue `#378`](https://github.com/geturbackend/urBackend/issues/378).

The required Kiroo updates are:

- Redact request headers, response headers, request bodies, response bodies, and URL query parameters.
- Add configurable `redactKeys`, `redactHeaders`, and `redactQueryParams`.
- Support application-specific redaction through a callback, if supported.
- Add safe default redaction for credentials and common personal data.
- Keep recursive and case-insensitive key matching.
- Document private Supabase bucket access and retention requirements.
- State clearly that Kiroo does not capture JavaScript stack traces.
- Replace the documentation error example that returns `"Downstream timeout"` to the client.
- Add redaction tests for nested fields, header variants, response headers, and query parameters.

The issue also now requires protected server-side logs for stack traces. Kiroo provides the replay ID and sanitized request/response capture.

🐇🔒

✏️ Learnings added
Learnt from: yash-pouranik
URL: https://github.com/geturbackend/urBackend/issues/378

Timestamp: 2026-08-01T13:11:08.714Z
Learning: Yash Pouranik maintains the Kiroo SDK. For production use with geturbackend/urBackend, the Kiroo SDK must sanitize request and response headers, request and response bodies, and URL query parameters before capture storage; it must not be used as the only source of JavaScript stack traces.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

coderabbitai[bot] avatar Aug 01 '26 13:08 coderabbitai[bot]