Repository navigation
fix(security): fixes from the security scan - #188
Prajna1999 wants to merge 2 commits into
Conversation
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>
|
Important Review skippedAuto reviews are limited based on label configuration. 🏷️ Required labels (at least one): 1
Please check the settings in the CodeRabbit UI or the
|
…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>
There was a problem hiding this comment.
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. Theexcept Exceptionhandler at guardrails.py:389 logsexcwithexc_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 rawexcfrom 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 thatexcto 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 includedata. 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
exceptionand the validator fails, so guard.validate(data) at guardrails.py:362 raises. The handler at guardrails.py:389-394 then logsexcwithexc_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.
| 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) |
There was a problem hiding this comment.
🟡 (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.
| # "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) | ||
| ] |
There was a problem hiding this comment.
🟡 (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.
Summary
Fixes for findings from a full-repo security scan. Two commits.
logs/app.log, Sentry Logs)guardrails.executionlog lines record character counts instead of textapi/routes/guardrails.pyllm_callablecould be a URL:huggingface/https://hostsent the prompt andHF_TOKENto that hostgpt-…oropenai/gpt-…); anything else is a 422config/base_validator_config.pyand the four LLM validator configs{query:>4000000000}allocated gigabytes{query}/{answer}fieldsvalidators/answer_relevance_custom_llm.pynsfw_textloaded a model on every requestconfig/nsfw_text_safety_validator_config.pyinput/outputcapped at 50,000 characters,validatorsat 20; inlinebanned_wordsshare the stored-list limitsschemas/guardrail_config.py,config/ban_list_safety_validator_config.pycontent_safetymodel cache bounded to 4validators/content_safety.pymainbranchpushevent from this repository.github/workflows/deploy-staging.ymlReview notes
MAX_TEXT_CHARSandMAX_VALIDATORS.pipelinefunction, becauseNSFWTexthas no way to accept a loaded model.Not in this PR
model_name(model swapping is a documented feature).Testing
--noconftest); the local Postgres was down, so DB-backed tests were not run locally.test_validate_with_guard_exceptionfails in that mode onmainas well, so it is unrelated.🤖 Generated with Claude Code