Skip to content

Conversation

@will-holley
Copy link
Contributor

@will-holley will-holley commented Jun 5, 2025

Summary by CodeRabbit

  • New Features

    • Added support for fetching and applying plugin severity overrides from cloud providers, with override information included in output metadata.
    • Introduced new utility functions for cloud provider detection and ID extraction.
    • Added a function to extract provider IDs from various provider path formats.
  • Bug Fixes

    • Ensured plugin severity is correctly set from either explicit values or configuration, improving consistency in test case metadata.
  • Tests

    • Enhanced tests to cover cloud provider detection, ID extraction, and severity handling in plugins.
    • Added tests to verify correct propagation and preservation of the severity field in plugin configurations.

@gru-agent
Copy link
Contributor

gru-agent bot commented Jun 5, 2025

TestGru Assignment

Summary

Link CommitId Status Reason
Detail a6012db ✅ Finished

Files

File Pull Request
src/util/cloud.ts 🔴 Closed #4349
src/redteam/commands/generate.ts 🛑 Cancelled (Canceled by Auto Rebase Detail)
src/providers/index.ts 🚫 Skipped (There's no need to update the test code)

Tip

You can @gru-agent and leave your feedback. TestGru will make adjustments based on your input

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

3 files reviewed, no comments
Edit PR Review Bot Settings | Greptile

return provider.label || `custom-function-${idx}`;
}
if ((provider as ProviderOptions).id) {
return (provider as ProviderOptions).id!;
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid using the non-null assertion operator ! when returning provider.id. Since you already check if provider.id exists, replace (provider as ProviderOptions).id! with a safe access or add an invariant to guarantee its presence.

Suggested change
return (provider as ProviderOptions).id!;
return (provider as ProviderOptions).id;

This comment was generated because it violated a code review rule: irule_xyCqADUsMuORnlRY.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @will-holley - I've reviewed your changes - here's some feedback:

  • In getPluginSeverityOverridesFromCloud you’re swallowing the original error context—consider wrapping and re-throwing the HTTP status and response body to preserve diagnostic info.
  • The getProviderIds helper has become quite complex with multiple input types—consider simplifying its branches or adding in-code comments to clarify expected behavior for each case.
  • When applying plugin severity overrides in doGenerateRedteam, overrides that don’t match any loaded plugin are dropped silently—consider logging a warning if an override ID has no corresponding plugin to catch misconfigurations.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@gru-agent
Copy link
Contributor

gru-agent bot commented Jun 5, 2025

TestGru Assignment

Summary

Link CommitId Status Reason
Detail 08f85a5 ✅ Finished

Files

File Pull Request
src/providers/index.ts 🚫 Skipped (There's no need to update the test code)
src/redteam/commands/generate.ts 🔴 Closed #4352
src/util/cloud.ts 🔴 Closed #4349

Tip

You can @gru-agent and leave your feedback. TestGru will make adjustments based on your input

Copy link
Contributor

@sklein12 sklein12 left a comment

Choose a reason for hiding this comment

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

Sorry to be the bearer 🐻 of bad news. We should do this in the cloud in our shared utilities for creating unified configs.

@mldangelo
Copy link
Member

@coderabbitai

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 6, 2025

Tip

For best results, initiate chat on the files or code changes.

@mldangelo, hello! I see you've mentioned me. How can I help you today? If you have any questions about the code, need analysis of specific files, or would like me to review something in particular, just let me know!

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 6, 2025

Walkthrough

The changes introduce new utility functions for cloud provider detection and ID extraction, refactor provider validation logic to use these utilities, and add support for fetching and applying plugin severity overrides from cloud providers during redteam generation. Associated tests are updated to mock the new utilities and provider ID extraction logic.

Changes

Files / Areas Changed Change Summary
src/providers/index.ts Replaced direct prefix checks with isCloudProvider/getCloudDatabaseId utilities; added getProviderIds export.
src/redteam/commands/generate.ts Integrated cloud plugin severity override fetching and application; refactored provider validation and metadata.
src/util/cloud.ts Added isCloudProvider, getCloudDatabaseId, and getPluginSeverityOverridesFromCloud utility functions.
src/redteam/index.ts Modified severity assignment to prefer explicit plugin severity property before fallback to computed severity.
test/providers.test.ts Mocked isCloudProvider and getCloudDatabaseId utilities for cloud provider path testing.
test/redteam/commands/generate.test.ts Added mock for getProviderIds in the providers module mock.
test/redteam/validators.test.ts Added tests verifying preservation and propagation of severity field in plugins and collections.

Poem

🐇 In clouds we hop, with IDs in tow,
Plugins' severities now finely flow.
Overrides fetched from skies so wide,
With helpers by our fluffy side.
Tests all snug, mocks in place,
Our code now leaps with gentle grace! 🌿✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-11T17_32_55_719Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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.

Documentation and Community

  • 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: 3

♻️ Duplicate comments (2)
test/providers.test.ts (1)

35-35: Use the imported constant instead of hardcoding the cloud provider prefix.

As mentioned in a previous review, consider using the CLOUD_PROVIDER_PREFIX constant (already imported on line 5) instead of hardcoding 'promptfoo://provider/' in the cloud utility mocks. This improves consistency and maintainability.

-      .mockImplementation((path: string) => path.startsWith('promptfoo://provider/'));
+      .mockImplementation((path: string) => path.startsWith(CLOUD_PROVIDER_PREFIX));
-      .mockImplementation((path: string) => path.slice('promptfoo://provider/'.length));
+      .mockImplementation((path: string) => path.slice(CLOUD_PROVIDER_PREFIX.length));

Also applies to: 38-38

src/providers/index.ts (1)

264-264: Remove the non-null assertion operator for safer code.

As mentioned in a previous review, avoid using the non-null assertion operator ! when returning provider.id. Since you already check if provider.id exists, this should be safe to remove.

-        return (provider as ProviderOptions).id!;
+        return (provider as ProviderOptions).id;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a55f2fb and 0f9bb05.

📒 Files selected for processing (5)
  • src/providers/index.ts (3 hunks)
  • src/redteam/commands/generate.ts (7 hunks)
  • src/util/cloud.ts (3 hunks)
  • test/providers.test.ts (2 hunks)
  • test/redteam/commands/generate.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/redteam/commands/generate.ts (1)
src/util/cloud.ts (2)
  • isCloudProvider (96-98)
  • getCloudDatabaseId (100-102)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Tusk Tester
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
test/redteam/commands/generate.test.ts (1)

68-68: LGTM! Mock is appropriate for testing redteam generation logic.

The mock for getProviderIds is well-placed and returns test data consistent with other provider mocks in the file. This allows the test to focus on redteam generation behavior rather than provider ID extraction logic.

src/providers/index.ts (2)

11-11: Excellent refactoring to use cloud utility functions.

The replacement of direct prefix checks with isCloudProvider and getCloudDatabaseId utilities improves code organization and maintainability. This encapsulates cloud provider logic in a centralized location.

Also applies to: 33-34, 37-37


250-272: Well-implemented utility function with comprehensive input handling.

The getProviderIds function effectively handles various provider input types and provides a clean interface for extracting provider IDs. The error handling for invalid inputs is appropriate.

src/util/cloud.ts (3)

96-102: Clean and well-encapsulated cloud provider utility functions.

The isCloudProvider and getCloudDatabaseId functions provide a clear interface for cloud provider detection and ID extraction, improving code organization and reusability.


50-53: Good enhancement to provider configuration handling.

The fallback from name to label provides a sensible default when no explicit label is configured, improving user experience.


109-157: Comprehensive implementation of plugin severity overrides feature.

The function includes proper error handling, detailed logging, and robust response parsing. The null return for missing associations provides clear semantics for downstream consumers.

src/redteam/commands/generate.ts (1)

136-138: Good catch switching from const to let.

Re-declaring pluginSeverityOverrides as let unblocks later reassignment and resolves the issue raised in the previous review cycle.

Comment on lines +404 to 406
...(pluginSeverityOverridesId ? { pluginSeverityOverridesId } : {}),
},
};
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

pluginSeverityOverridesId is only persisted in one code path – leads to inconsistent metadata

pluginSeverityOverridesId is written to the YAML when options.output is provided (lines 404-406) but not when:

  1. The user appends (--write, lines 462-468)
  2. Generation defaults to redteam.yaml (lines 506-507)

As a result, downstream tooling cannot reliably rely on this field.

Refactor the metadata construction in both branches to include the override ID, e.g.:

-      metadata: {
+      metadata: {
         ...(existingConfig.metadata || {}),
+        ...(pluginSeverityOverridesId ? { pluginSeverityOverridesId } : {}),
       },

Apply the same patch to the “default redteam.yaml” branch.

Also applies to: 462-468, 506-507

🤖 Prompt for AI Agents
In src/redteam/commands/generate.ts around lines 404-406, 462-468, and 506-507,
the pluginSeverityOverridesId field is only included in the metadata when
options.output is provided, causing inconsistent metadata. Refactor the metadata
construction in all these code paths to consistently include
pluginSeverityOverridesId by merging it into the metadata object wherever it is
created or written, ensuring downstream tools can reliably access this field.

sklein12
sklein12 previously approved these changes Jun 10, 2025
Copy link
Contributor

@sklein12 sklein12 left a comment

Choose a reason for hiding this comment

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

two comments about error messages then it's good to go. Please address those before merging

@use-tusk
Copy link
Contributor

use-tusk bot commented Jun 11, 2025

⏩ No test scenarios generated (5fe5357) View output ↗

View output in GitHub ↗

Tip

New to Tusk? Learn more here.

View check history

Commit Status Output Created (UTC)
0f9bb05 ⏩ Skipped due to new commit on branch Output Jun 6, 2025 7:56PM
e3a70ca ✅ Generated 22 tests - 22 passed Tests Jun 6, 2025 8:14PM
291306a ✅ Generated 22 tests - 22 passed Tests Jun 9, 2025 2:41PM
a0a8362 ✅ Generated 22 tests - 22 passed Tests Jun 9, 2025 8:07PM
a79e6a2 ✅ Generated 22 tests - 22 passed Tests Jun 9, 2025 8:19PM
2658062 ❌ Generated 11 tests - 10 passed, 1 failed Tests Jun 9, 2025 9:25PM
7e98ab4 ⏩ No test scenarios generated Output Jun 10, 2025 3:48PM
7e17969 ⏩ No test scenarios generated Output Jun 10, 2025 9:05PM
13e0cea ⏩ No test scenarios generated Output Jun 10, 2025 9:34PM
8da3a54 ⏩ No test scenarios generated Output Jun 10, 2025 9:35PM
2657d8d ❌ Generated 11 tests - 10 passed, 1 failed Tests Jun 11, 2025 5:26PM
5fe5357 ⏩ No test scenarios generated Output Jun 11, 2025 5:27PM

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

🧹 Nitpick comments (3)
src/util/cloud.ts (1)

120-124: Typo in error message string

formattedErrorMessage reads “Failed to provider from cloud”. Looks like “fetch provider” was intended.

-      const formattedErrorMessage = `Failed to provider from cloud: ${errorMessage}. HTTP Status: ${response.status} -- ${response.statusText}.`;
+      const formattedErrorMessage = `Failed to fetch provider from cloud: ${errorMessage}. HTTP Status: ${response.status} -- ${response.statusText}.`;
src/redteam/index.ts (2)

723-725: Duplicate severity-fallback logic – centralise to avoid drift

Severity resolution here duplicates the logic embedded a few lines below for custom plugins and elsewhere. Consider wrapping this in a helper (e.g. resolveSeverity(plugin)) to keep behaviour consistent and remove repetition.


770-771: Inconsistent nullish/boolean coalescing

Here you use the || operator, whereas the non-custom branch uses ??.
|| will ignore valid falsy severities (should you ever extend the enum) while ?? only checks for null/undefined. Recommend aligning with ?? for consistency.

-            severity:
-              plugin.severity || getPluginSeverity(plugin.id, resolvePluginConfig(plugin.config)),
+            severity:
+              plugin.severity ?? getPluginSeverity(plugin.id, resolvePluginConfig(plugin.config)),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0f9bb05 and 5fe5357.

📒 Files selected for processing (6)
  • src/providers/index.ts (3 hunks)
  • src/redteam/commands/generate.ts (7 hunks)
  • src/redteam/index.ts (2 hunks)
  • src/util/cloud.ts (2 hunks)
  • test/redteam/commands/generate.test.ts (1 hunks)
  • test/redteam/validators.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/providers/index.ts
  • src/redteam/commands/generate.ts
  • test/redteam/commands/generate.test.ts
🧰 Additional context used
📓 Path-based instructions (1)
`src/**`: - This is a CLI tool so errors need to be handled gracefully and logged with lots of information so the user can give us enough data to fix the issue or pass it to the de...

src/**: - This is a CLI tool so errors need to be handled gracefully and logged with lots of information so the user can give us enough data to fix the issue or pass it to the developers.

  • src/redteam/index.ts
  • src/util/cloud.ts
🧬 Code Graph Analysis (2)
test/redteam/validators.test.ts (1)
src/validators/redteam.ts (1)
  • RedteamConfigSchema (165-379)
src/util/cloud.ts (3)
src/constants.ts (1)
  • CLOUD_PROVIDER_PREFIX (45-45)
src/globalConfig/cloud.ts (1)
  • cloudConfig (140-140)
src/logger.ts (1)
  • logger (191-203)
🪛 Biome (1.9.4)
src/util/cloud.ts

[error] 154-154: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

🔇 Additional comments (2)
src/util/cloud.ts (1)

152-158: Quadratic spread on accumulator – switch to direct assignment

Using the spread operator inside reduce recreates the accumulator on every iteration (O(n²)). Construct the object in-place instead.

-        severities: pluginSeveritySet.members.reduce(
-          (acc: Record<Plugin, Severity>, member: { pluginId: Plugin; severity: Severity }) => ({
-            ...acc,
-            [member.pluginId]: member.severity,
-          }),
-          {},
-        ),
+        severities: pluginSeveritySet.members.reduce(
+          (acc: Record<Plugin, Severity>, { pluginId, severity }) => {
+            acc[pluginId] = severity;
+            return acc;
+          },
+          {} as Record<Plugin, Severity>,
+        ),

[ suggest_essential_refactor ]

🧰 Tools
🪛 Biome (1.9.4)

[error] 154-154: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

test/redteam/validators.test.ts (1)

891-950: Tests accurately cover new severity behaviour

The added cases thoroughly verify preservation of severity for direct plugins, mixed presence/absence, and collection expansion – good coverage.

@will-holley will-holley merged commit ec4240a into main Jun 11, 2025
37 checks passed
@will-holley will-holley deleted the feat/plugin-severity-overrides branch June 11, 2025 18:45
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.

5 participants