Skip to content

Forbid unknown attributes for request payload#479

Merged
tisnik merged 2 commits intolightspeed-core:mainfrom
tisnik:forbid-unknown-attributes-for-request-payload
Sep 2, 2025
Merged

Forbid unknown attributes for request payload#479
tisnik merged 2 commits intolightspeed-core:mainfrom
tisnik:forbid-unknown-attributes-for-request-payload

Conversation

@tisnik
Copy link
Contributor

@tisnik tisnik commented Sep 2, 2025

Description

Forbid unknown attributes for request payload

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement

Summary by CodeRabbit

  • Bug Fixes

    • Stricter request validation: unknown fields are now rejected for attachments, feedback creation, and feedback status updates.
    • Improved UUID validation: gracefully handles missing values and provides clearer error messages for invalid IDs.
  • Documentation

    • OpenAPI updated to disallow additional properties for Attachment, FeedbackRequest, and FeedbackStatusUpdateRequest schemas, aligning docs with runtime validation.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 2, 2025

Walkthrough

Added strict validation to three request models by forbidding unknown fields and adjusting a UUID validator to accept None. Mirrored these constraints in OpenAPI by setting additionalProperties: false for corresponding schemas.

Changes

Cohort / File(s) Change Summary
OpenAPI schema constraints
docs/openapi.json
Added "additionalProperties": false to Attachment, FeedbackRequest, and FeedbackStatusUpdateRequest component schemas.
Request model validation
src/models/requests.py
Set model_config extra="forbid" on Attachment, FeedbackRequest, FeedbackStatusUpdateRequest; updated FeedbackRequest.check_uuid to accept str | None and skip validation on None; minor comment text tweak.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant API as API Endpoint
  participant Model as Pydantic Model
  participant Validator as Field Validators

  Client->>API: POST FeedbackRequest
  API->>Model: Instantiate with payload
  Model->>Model: Enforce extra="forbid"
  alt Unknown fields present
    Model-->>API: ValidationError (extra fields)
    API-->>Client: 422 Unprocessable Entity
  else Fields known
    Model->>Validator: check_uuid(value)
    alt value is None
      Note right of Validator: Skip UUID check
      Validator-->>Model: OK
    else Invalid UUID
      Validator-->>Model: Raise error (quoted value)
      Model-->>API: ValidationError
      API-->>Client: 422 Unprocessable Entity
    end
    Model-->>API: Valid model
    API-->>Client: 200/201 Success
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I tightened my fields with a hop and a wiggle,
No extras allowed—strict as a burrow’s niggle.
UUIDs may nap as None, that’s fine,
But fake IDs? I thump the review line.
Docs aligned, schemas neat—
Carrots counted, changes complete. 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/openapi.json (1)

1369-1473: Add upgrade note and negative test for forbidden extra fields

Confirmed additionalProperties=false on Attachment, FeedbackRequest, and FeedbackStatusUpdateRequest in docs/openapi.json; this is a breaking change. Add an upgrade note to the release notes and a test asserting that sending an extra property on FeedbackRequest yields HTTP 422.

🧹 Nitpick comments (7)
docs/openapi.json (1)

1410-1415: Add minLength: 1 for user_feedback to match docs.

Your code comment states “1-4096”, but schema only has maxLength. Consider enforcing minLength=1 via model Field (then regenerate OpenAPI).

src/models/requests.py (6)

16-17: Nit: fix grammar in user-facing docs.

“can be send” → “can be sent”.

-    """Model representing an attachment that can be send from the UI as part of query.
+    """Model representing an attachment that can be sent from the UI as part of a query.

288-294: Enforce 1–4096 length as documented.

Currently only max_length=4096; allow empty strings. Add min_length=1.

-    user_feedback: Optional[str] = Field(
-        default=None,
-        max_length=4096,
+    user_feedback: Optional[str] = Field(
+        default=None,
+        min_length=1,
+        max_length=4096,
         description="Feedback on the LLM response.",
         examples=["I'm not satisfied with the response because it is too vague."],
     )

341-345: Unify UUID error message style with QueryRequest.

QueryRequest quotes the value in the error; this one doesn’t. Quote here for consistency and clearer logs.

-        if not suid.check_suid(value):
-            raise ValueError(f"Improper conversation ID {value}")
+        if not suid.check_suid(value):
+            raise ValueError(f"Improper conversation ID '{value}'")

393-399: Fix example class name in docstring.

Example shows FeedbackRequest inside FeedbackStatusUpdateRequest docs.

-        feedback_request = FeedbackRequest(
+        feedback_request = FeedbackStatusUpdateRequest(
             status=false
         )

34-45: Optional: cap attachment size to prevent abuse.

Consider a reasonable max_length on content (e.g., 1_000_000 chars) to avoid large inlined payloads.

-    content: str = Field(
+    content: str = Field(
+        max_length=1_000_000,
         description="The actual attachment content",
         examples=["warning: quota exceeded"],
     )

241-337: Add tests for “extra fields not permitted” errors.

Recommend unit tests for Attachment, FeedbackRequest, and FeedbackStatusUpdateRequest ensuring extra keys raise ValidationError, plus FastAPI route tests that return 422.

I can draft minimal pytest cases if helpful.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between fca5947 and c103186.

📒 Files selected for processing (2)
  • docs/openapi.json (3 hunks)
  • src/models/requests.py (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build-pr
  • GitHub Check: e2e_tests
🔇 Additional comments (7)
docs/openapi.json (3)

821-822: OpenAPI: Attachment now disallows unknown fields (good).

This aligns the spec with Pydantic extra="forbid" and prevents silent acceptance of typos in payloads.


1448-1449: OpenAPI: FeedbackRequest now disallows unknown fields (good).

Spec matches runtime validation and reduces client error ambiguity.


1519-1521: OpenAPI: FeedbackStatusUpdateRequest now disallows unknown fields (good).

Consistent with model_config and expected 422 behavior on extra keys.

src/models/requests.py (4)

49-49: Runtime enforcement: extra="forbid" on Attachment (good).

Prevents stray keys inside attachments; matches the OpenAPI change.


308-308: Runtime enforcement: extra="forbid" on FeedbackRequest (good).

This closes a common source of payload typos.


407-409: Runtime enforcement: extra="forbid" on FeedbackStatusUpdateRequest (good).

Makes status updates strict and predictable.


1-413: Strictness enforced on all Request models All *Request classes (QueryRequest, FeedbackRequest, FeedbackStatusUpdateRequest) define model_config.extra='forbid', so no request payload model accepts extra fields.

@tisnik
Copy link
Contributor Author

tisnik commented Sep 2, 2025

@CodeRabbit generate unit tests

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 2, 2025

An unexpected error occurred during Unit Test Generation.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 2, 2025

✅ Actions performed

Unit Test Generation started...

@tisnik tisnik merged commit 2e39274 into lightspeed-core:main Sep 2, 2025
19 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