Skip to content

fix(security): fixes from the security scan - #188

Open
Prajna1999 wants to merge 2 commits into
mainfrom
fix/security-fixes
Open

Prajna1999 wants to merge 2 commits into
mainfrom
fix/security-fixes

Conversation

@Prajna1999

@Prajna1999 Prajna1999 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes for findings from a full-repo security scan. Two commits.

Finding Fix Where
Raw user text logged before PII redaction (CloudWatch, logs/app.log, Sentry Logs) The three guardrails.execution log lines record character counts instead of text api/routes/guardrails.py
llm_callable could be a URL: huggingface/https://host sent the prompt and HF_TOKEN to that host Only OpenAI model ids are accepted (gpt-… or openai/gpt-…); anything else is a 422 config/base_validator_config.py and the four LLM validator configs
Format-string memory bomb: a template such as {query:>4000000000} allocated gigabytes Prompt templates may contain only bare {query} / {answer} fields validators/answer_relevance_custom_llm.py
nsfw_text loaded a model on every request One pipeline is shared per model name (up to 4) config/nsfw_text_safety_validator_config.py
No request size limits input / output capped at 50,000 characters, validators at 20; inline banned_words share the stored-list limits schemas/guardrail_config.py, config/ban_list_safety_validator_config.py
Request-chosen models cached forever content_safety model cache bounded to 4 validators/content_safety.py
Staging deploy could be triggered by a PR from a fork's main branch The job also requires a push event from this repository .github/workflows/deploy-staging.yml

Review notes

  • The size limits are estimates. Requests over 50,000 characters or 20 validators now get a 422. Check against what kaapi-backend sends; the constants are MAX_TEXT_CHARS and MAX_VALIDATORS.
  • The NSFW fix patches the library's module-level pipeline function, because NSFWText has no way to accept a loaded model.
  • The workflow change is untested; it can only be exercised on GitHub.

Not in this PR

  • Pinning Hugging Face model revisions and fixing the unused image cache path.
  • Windowed scoring so the toxicity classifier sees text past the first 512 tokens.
  • An allowlist for model_name (model swapping is a documented feature).

Testing

  • New tests for each fix.
  • 244 unit tests pass locally with the database fixture disabled (--noconftest); the local Postgres was down, so DB-backed tests were not run locally.
  • test_validate_with_guard_exception fails in that mode on main as well, so it is unrelated.

🤖 Generated with Claude Code

The guardrails.execution logger wrote the first 120 characters of the raw
input, the final output and each validator's before/after values at INFO.
Those lines reach CloudWatch, logs/app.log and Sentry Logs before any PII
redaction runs. Log character counts instead and drop the unused
_strip_for_log helper; the full text stays in request_log/validator_log.

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are limited based on label configuration.

🏷️ Required labels (at least one): 1

  • ready-for-review

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

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:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

…eploy

Fixes from the security scan:

- llm_callable accepts only OpenAI model ids. litellm reads other shapes as
  a provider or URL, so "huggingface/https://host" sent the prompt and
  HF_TOKEN to that host.
- answer_relevance prompt templates may contain only bare {query}/{answer}
  fields. A format spec such as {query:>4000000000} allocated gigabytes.
- nsfw_text shares one pipeline per model instead of loading a model on
  every request.
- GuardrailRequest caps input/output at 50,000 characters and validators
  at 20; inline banned_words share the stored ban list limits.
- content_safety's model cache is bounded to 4 entries.
- The staging deploy only runs for CI runs triggered by a push to this
  repository, not pull_request runs from a fork's "main" branch.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Prajna1999 Prajna1999 changed the title fix(logging): log text lengths instead of user text in execution logs fix(security): fixes from the security scan Nov 30, 2026

@claude claude 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.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🟣 backend/app/api/routes/guardrails.py — Pre-existing, security-relevant: users who set on_fail=exception still get their raw text written to the ERROR log and Sentry after this change. The except Exception handler at guardrails.py:389 logs exc with exc_info=True. Guardrails exception messages embed the failing input, e.g. the NSFW message ending :\n\n- {input}. Fix: log only exception type and request_log_id (or _redact_input(_safe_error_message(exc), data)) and drop raw exc from this line. That closes the last exec-path log site still carrying user text.

    Why this was flagged

    The trigger is a request whose validator config sets on_fail to exception. base_validator_config.py:resolve_on_fail maps that to OnFailAction.EXCEPTION. When the validator fails, guard.validate inside _validate_with_guard (guardrails.py:362) raises. The repo's own test_nsfw_exception_redacts_input (test_validate_with_guard.py:617-618) shows the message is "Validation failed for field with errors: The following sentences in your response were found to be NSFW:\n\n- ". The handler at guardrails.py:389-394 passes that exc to logger.error with exc_info=True, so the raw user text reaches stdout/CloudWatch, logs/app.log and Sentry, and Sentry's local-variable capture can also include data. The response path already strips it through _redact_input (guardrails.py:401), but the log line does not. This PR rewrites the INFO lines at 348 and 365 so user text stays out of logs, yet this sibling site in the same function leaks exactly as on the base branch. PII therefore still reaches the log stores the PR description names.

    Verification: Trigger: a request whose validator config sets on_fail to exception and the validator fails, so guard.validate(data) at guardrails.py:362 raises. The handler at guardrails.py:389-394 then logs exc with exc_info=True, with no redaction. The diff did not change this line. The base branch leaks the same way by the same route, so merging makes nothing worse.

Comment on lines +68 to +72
for _, field, spec, conversion in Formatter().parse(self.prompt_template):
if field is not None and (
spec or conversion or not field.isidentifier()
):
raise KeyError(field)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 (optional) Saved answer-relevance prompts can now pass save-time validation but fail on every guardrail run, with an error that names a placeholder the template already has. The new check rejects any field with a conversion, a format spec or attribute/index access, then raises KeyError(field). The save-time check validate_answer_relevance_prompt (schemas/llm_prompt_config.py:33) still only looks for the literal "{query}" and "{answer}". Fix: reject the same Formatter shapes at save time on both create and update. Also report the real reason, not ANSWER_RELEVANCE_MISSING_PLACEHOLDER_TEMPLATE.

Why this was flagged

I could not list the stored llm_prompt rows from this checkout, so this applies to any tenant prompt saved with validator_name answer_relevance_custom_llm that has a field like {answer!r}, {answer:.2000} or {query.x} next to the literal {query} and {answer}. Example: "Q: {query}\nA: {answer}\nShort: {answer:.500}". On the base branch, str.format accepted these and the validator called the LLM. Now _resolve_validator_configs (routes/guardrails.py:233) copies prompt_config.llm_prompt into prompt_template, and the loop at answer_relevance_custom_llm.py:68-72 raises KeyError('answer'). The run then gets a FailResult saying "Prompt template missing placeholder: 'answer'", even though {answer} is in the template. LLMPromptConfigCreate.validate_answer_relevance_placeholders and the update path at crud/llm_prompt_config.py:119-123 use only the substring test in validate_answer_relevance_prompt. So new templates of this shape are still saved with no error and then fail on every request.

Verification: Trigger: an answer_relevance_custom_llm prompt with {answer!r} or {answer:.500} alongside the literal {query} and {answer}. answer_relevance_custom_llm.py lines 68-72 raise KeyError(field), so every run returns a FailResult. validate_answer_relevance_prompt (schemas/llm_prompt_config.py:33-39) only checks the literal substrings, so such a template still saves. On the base branch, these prompts worked.

Comment on lines +12 to +15
# "huggingface/https://host" POSTs the prompt and HF_TOKEN to that host.
LLMCallable = Annotated[
str, StringConstraints(pattern=r"^(openai/)?[A-Za-z0-9._:-]+$", max_length=100)
]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 (optional) Validator configs saved through the config API before this change may carry a provider-prefixed llm_callable or a ban word over 100 chars. Every guardrail call replaying them now gets a 422. The save path (ValidatorBase, extra="allow") checks neither LLMCallable nor BannedWords, so such configs can also still be saved. Fix: run the same per-type config validation on save that validate_pii_config runs for PII. Also audit or migrate stored configs that fail the new types, while keeping plain OpenAI ids such as gpt-5.6-sol working.

Why this was flagged

This applies only if stored validator configs hold values the new types reject. Examples are llm_callable values like "anthropic/claude-…", "azure/…" or "gemini/…", or inline banned_words entries longer than 100 chars or blank. GuardrailRequest.normalize_validators_from_config_api (backend/app/schemas/guardrail_config.py:79-110) accepts payloads copied from the validator-config endpoints and parses them as ValidatorConfigItem. On base those fields were plain str / List[str], so the requests ran. Now LLMCallable (^(openai/)?[A-Za-z0-9._:-]+$, max_length=100) and BannedWords reject them, and every guardrail request using that config gets a 422. ValidatorCreate (backend/app/schemas/validator_config.py:36-44) only validates PII configs and ValidatorBase uses extra="allow". So the save path neither caught the old values nor blocks new ones, and the failure shows up only at runtime.

Verification: ValidatorBase in backend/app/schemas/validator_config.py uses ConfigDict(extra="allow"). Its only per-type check is validate_pii_config. The runtime now uses LLMCallable (base_validator_config.py:14-16) and BannedWords. On base both fields were plain str / List[str]. Saving such a config still succeeds, but every guardrail call that replays it now gets a 422.

This branch has not been deployed

No deployments
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