Skip to content

Conversation

@tisnik
Copy link
Contributor

@tisnik tisnik commented Aug 13, 2025

Description

LCORE-390: authentication configuration is not optional

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

Related Tickets & Documents

  • Related Issue #LCORE-390

Summary by CodeRabbit

  • New Features
    • Configuration now always includes a default authentication setup, removing the possibility of missing/None authentication. This ensures predictable behavior without manual initialization.
  • Tests
    • Added unit tests validating default authentication values and custom authentication overrides within Configuration.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

Walkthrough

The Configuration model’s authentication field was made non-optional with a default AuthenticationConfiguration. A new unit test validates default and explicit authentication configurations, including module selection, TLS verification flag, and certificate path behavior.

Changes

Cohort / File(s) Summary
Model Configuration Update
src/models/config.py
Changed Configuration.authentication from Optional to non-optional AuthenticationConfiguration with a default instance.
Unit Tests for Configuration Authentication
tests/unit/models/test_config.py
Added test to verify default authentication values and behavior when an explicit AuthenticationConfiguration is provided.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

I twitch my whiskers, configs neat,
No None shall sneak where auth should seat.
TLS checked, a carrot bright,
K8S or NOOP, both set just right.
In burrows of tests, I hop with glee—
Defaults secure, for you and me. 🥕

✨ 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 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: 2

🧹 Nitpick comments (3)
src/models/config.py (2)

108-108: Optional: use default_factory for other nested models to avoid shared instances

For consistency and to avoid any risk of shared defaults, prefer default factories for nested models as well.

Apply these diffs:

-    tls_config: TLSConfiguration = TLSConfiguration()
+    tls_config: TLSConfiguration = Field(default_factory=TLSConfiguration)
-    database: DatabaseConfiguration = DatabaseConfiguration()
+    database: DatabaseConfiguration = Field(default_factory=DatabaseConfiguration)
-    inference: InferenceConfiguration = InferenceConfiguration()
+    inference: InferenceConfiguration = Field(default_factory=InferenceConfiguration)

Note: Ensure Field is imported from pydantic:
from pydantic import BaseModel, model_validator, FilePath, AnyHttpUrl, Field

Also applies to: 293-293, 297-297


241-245: Avoid assert for runtime validation; raise ValueError instead

Using assert for invariant checks can be disabled with Python optimizations and results in AssertionError, not a validation error. Raise a ValueError to match the surrounding validation semantics.

-        assert self.jwk_config is not None, "JWK configuration should not be None"
-        return self.jwk_config
+        if self.jwk_config is None:
+            raise ValueError("JWK configuration should not be None")
+        return self.jwk_config
tests/unit/models/test_config.py (1)

617-663: Add tests to guard against explicit None and shared-default regressions

Two focused tests would harden the change:

  • Assert that explicitly passing authentication=None raises ValidationError.
  • Assert each Configuration gets a unique AuthenticationConfiguration instance (no shared default).

You can add:

def test_configuration_authentication_explicit_none_rejected() -> None:
    from pydantic import ValidationError
    with pytest.raises(ValidationError):
        Configuration(
            name="test_name",
            service=ServiceConfiguration(),
            llama_stack=LlamaStackConfiguration(
                use_as_library_client=True,
                library_client_config_path="tests/configuration/run.yaml",
            ),
            user_data_collection=UserDataCollection(
                feedback_enabled=False, feedback_storage=None
            ),
            authentication=None,  # explicit None should be rejected
        )

def test_configuration_authentication_default_is_per_instance() -> None:
    cfg_a = Configuration(
        name="a",
        service=ServiceConfiguration(),
        llama_stack=LlamaStackConfiguration(
            use_as_library_client=True,
            library_client_config_path="tests/configuration/run.yaml",
        ),
        user_data_collection=UserDataCollection(
            feedback_enabled=False, feedback_storage=None
        ),
    )
    cfg_b = Configuration(
        name="b",
        service=ServiceConfiguration(),
        llama_stack=LlamaStackConfiguration(
            use_as_library_client=True,
            library_client_config_path="tests/configuration/run.yaml",
        ),
        user_data_collection=UserDataCollection(
            feedback_enabled=False, feedback_storage=None
        ),
    )
    # ensure a fresh default per instance
    assert cfg_a.authentication is not cfg_b.authentication
    # mutate one and ensure it doesn't affect the other
    cfg_a.authentication.skip_tls_verification = True
    assert cfg_b.authentication.skip_tls_verification is False

I can open a follow-up PR with these tests if you prefer.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 37f5dec and b834967.

📒 Files selected for processing (2)
  • src/models/config.py (1 hunks)
  • tests/unit/models/test_config.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/unit/models/test_config.py (1)
src/models/config.py (5)
  • Configuration (286-302)
  • ServiceConfiguration (99-119)
  • LlamaStackConfiguration (130-173)
  • UserDataCollection (176-193)
  • AuthenticationConfiguration (210-245)
⏰ 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). (1)
  • GitHub Check: e2e_tests
🔇 Additional comments (1)
tests/unit/models/test_config.py (1)

617-663: LGTM: Solid coverage for default and explicit authentication configuration

The test verifies the non-optional default behavior and preserves explicit settings, including type coercion for FilePath. Looks good.

llama_stack: LlamaStackConfiguration
user_data_collection: UserDataCollection
database: DatabaseConfiguration = DatabaseConfiguration()
mcp_servers: list[ModelContextProtocolServer] = []
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix mutable default list for mcp_servers

mcp_servers uses a mutable default ([]), which will be shared across Configuration instances. Use a default factory to prevent cross-instance leakage.

Apply this diff:

-mcp_servers: list[ModelContextProtocolServer] = []
+mcp_servers: list[ModelContextProtocolServer] = Field(default_factory=list)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
mcp_servers: list[ModelContextProtocolServer] = []
mcp_servers: list[ModelContextProtocolServer] = Field(default_factory=list)
🤖 Prompt for AI Agents
In src/models/config.py around line 294, mcp_servers is defined with a mutable
default list ([]), which will be shared across instances; change the definition
to use a default factory instead (e.g., if this is a dataclass use
field(default_factory=list) from dataclasses, or if this is a Pydantic model use
Field(default_factory=list) from pydantic) so each Configuration instance gets
its own new list; update the import if needed and remove the bare [] default.

authentication: Optional[AuthenticationConfiguration] = (
AuthenticationConfiguration()
)
authentication: AuthenticationConfiguration = AuthenticationConfiguration()
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Avoid shared default instance for authentication; use Field(default_factory=...)

Using a constructed BaseModel instance as a class-level default risks sharing the same instance across all Configuration objects. Prefer a factory to ensure a fresh instance per model.

Apply this diff to the authentication field:

-authentication: AuthenticationConfiguration = AuthenticationConfiguration()
+authentication: AuthenticationConfiguration = Field(default_factory=AuthenticationConfiguration)

Additionally, ensure Field is imported:

# at import line with other pydantic symbols
from pydantic import BaseModel, model_validator, FilePath, AnyHttpUrl, Field

This change aligns the code with the PR’s goal (authentication is not optional) but may uncover existing configs passing authentication: null. Run this to find potential offenders:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Searching YAML for 'authentication: null' or '~' or empty mapping lines"
rg -n --glob '*.yaml' --glob '*.yml' -e $'^\s*authentication\s*:\s*(null|~)\s*$' -e $'^\s*authentication\s*:\s*$' || true

echo "Searching Python for explicit authentication=None"
rg -n --type py -e $'authentication\s*=\s*None' -A 2 || true

Length of output: 634


Use a fresh AuthenticationConfiguration via default_factory

Sharing a single AuthenticationConfiguration() across all Configuration instances risks cross-instance state. Update the field and imports as follows, and adjust your example YAMLs to remove any explicit authentication: entries (which currently parse as null and will now error):

  • In src/models/config.py, replace:

    - authentication: AuthenticationConfiguration = AuthenticationConfiguration()
    + authentication: AuthenticationConfiguration = Field(default_factory=AuthenticationConfiguration)
  • In the same file’s imports, add Field:

    - from pydantic import BaseModel, model_validator, FilePath, AnyHttpUrl
    + from pydantic import BaseModel, model_validator, FilePath, AnyHttpUrl, Field
  • Remove or replace the blank/null authentication: lines in your YAML examples so they don’t explicitly set null:

    • examples/lightspeed-stack.yaml:24
    • examples/lightspeed-stack-lls-external.yaml:26
    • examples/lightspeed-stack-lls-library.yaml:25

    You can either delete those lines (letting the default factory apply) or set them to an empty mapping (authentication: {}) if you need an explicit no-overrides placeholder.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
authentication: AuthenticationConfiguration = AuthenticationConfiguration()
# In src/models/config.py
from pydantic import BaseModel, model_validator, FilePath, AnyHttpUrl, Field
class Configuration(BaseModel):
# …
authentication: AuthenticationConfiguration = Field(default_factory=AuthenticationConfiguration)
# …

@tisnik tisnik merged commit 1bedb31 into lightspeed-core:main Aug 13, 2025
18 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