Skip to content

OCPBUGS-85473: fix: escape regex variable values in regex matcher contexts#1010

Open
jgbernalp wants to merge 1 commit into
openshift:mainfrom
jgbernalp:escape-variables-for-regex-context
Open

OCPBUGS-85473: fix: escape regex variable values in regex matcher contexts#1010
jgbernalp wants to merge 1 commit into
openshift:mainfrom
jgbernalp:escape-variables-for-regex-context

Conversation

@jgbernalp

@jgbernalp jgbernalp commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

This PR moves the evaluateVariableTemplate into its own utility file and adds tests for the regex escape bug.

Summary by CodeRabbit

  • Refactor

    • Reorganized variable templating utilities into a shared module for improved code maintainability and reusability.
  • Tests

    • Added comprehensive test coverage for variable template evaluation, including substitution and escaping scenarios.

@openshift-ci-robot openshift-ci-robot added jira/severity-moderate Referenced Jira bug's severity is moderate for the branch this PR is targeting. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. labels Jun 23, 2026
@openshift-ci-robot

Copy link
Copy Markdown

@jgbernalp: This pull request references Jira Issue OCPBUGS-85473, which is invalid:

  • expected the bug to target the "5.0.0" version, but no target version was set

Comment /jira refresh to re-evaluate validity if changes to the Jira bug are made, or edit the title of this pull request to link to a different bug.

The bug has been updated to refer to the pull request using the external bug tracker.

Details

In response to this:

This PR moves the evaluateVariableTemplate into its own utility file and adds tests for the regex escape bug.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@openshift-ci-robot openshift-ci-robot added the jira/invalid-bug Indicates that a referenced Jira bug is invalid for the branch this PR is targeting. label Jun 23, 2026
@jgbernalp jgbernalp requested a review from etmurasaki June 23, 2026 08:12
@jgbernalp

Copy link
Copy Markdown
Contributor Author

/jira refresh

@openshift-ci-robot openshift-ci-robot added the jira/valid-bug Indicates that a referenced Jira bug is valid for the branch this PR is targeting. label Jun 23, 2026
@openshift-ci-robot

Copy link
Copy Markdown

@jgbernalp: This pull request references Jira Issue OCPBUGS-85473, which is valid.

3 validation(s) were run on this bug
  • bug is open, matching expected state (open)
  • bug target version (5.0.0) matches configured target version for branch (5.0.0)
  • bug is in the state POST, which is one of the valid states (NEW, ASSIGNED, POST)
Details

In response to this:

/jira refresh

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@openshift-ci-robot openshift-ci-robot removed the jira/invalid-bug Indicates that a referenced Jira bug is invalid for the branch this PR is targeting. label Jun 23, 2026
@openshift-ci openshift-ci Bot requested review from PeterYurkovich and zhuje June 23, 2026 08:16
@openshift-ci

openshift-ci Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: jgbernalp

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-ci openshift-ci Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Jun 23, 2026
@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown

Walkthrough

Extracts evaluateVariableTemplate and the Variable type from legacy-variable-dropdowns.tsx into a new variable-utils.ts module. The original file now re-exports both from ./variable-utils and introduces a local VariableDropdownProps type. A new variable-utils.spec.ts test suite validates substitution, PromQL regex escaping, ALL-option handling, interval variables, and edge cases.

Changes

Variable Utils Extraction

Layer / File(s) Summary
variable-utils.ts: Variable type, interval detection, and evaluateVariableTemplate
web/src/components/dashboards/legacy/variable-utils.ts
Adds module constants, exports Variable type and isIntervalVariable, implements escapeIfRegexContext for PromQL =~/!~ detection, and implements evaluateVariableTemplate with range injection, interval computation, loading guards, ALL-option widening, namespace substitution, and regex-context escaping.
legacy-variable-dropdowns.tsx: import reorganization and re-exports
web/src/components/dashboards/legacy/legacy-variable-dropdowns.tsx
Removes standalone lodash-es import, consolidates imports, deletes the locally defined Variable type and evaluateVariableTemplate implementation, re-exports both from ./variable-utils, and introduces a local VariableDropdownProps type.
variable-utils.spec.ts: evaluateVariableTemplate test suite
web/src/components/dashboards/legacy/variable-utils.spec.ts
Adds a Jest suite with a makeVariables helper covering: basic and multi-variable substitution, IPv6 bracket and dot escaping in regex vs. exact contexts, ALL-option expansion, $__interval in range selectors, empty template and loading-variable edge cases, namespace override, and combined ALL + regex-escape expressions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 14 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (14 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: extracting variable templating utilities into a separate module and fixing regex variable escaping in regex matcher contexts, which is the core objective of addressing OCPBUGS-85473.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Stable And Deterministic Test Names ✅ Passed This PR contains only Jest tests (TypeScript/JavaScript), not Ginkgo tests (Go). The custom check for "Stable and Deterministic Test Names" applies to Ginkgo tests, not Jest tests.
Test Structure And Quality ✅ Passed Custom check for Ginkgo tests is not applicable to this PR. The PR adds Jest tests for a TypeScript web component utility, not Go Ginkgo tests. Check is inapplicable to codebase context.
Microshift Test Compatibility ✅ Passed No Ginkgo e2e tests are present in this PR. Changes are limited to TypeScript/React components and Jest unit tests, which are outside the scope of the MicroShift test compatibility check.
Single Node Openshift (Sno) Test Compatibility ✅ Passed This PR does not add any Ginkgo e2e tests. It contains only TypeScript frontend code (legacy-variable-dropdowns.tsx) and Jest unit tests (variable-utils.spec.ts), which are not subject to the SNO c...
Topology-Aware Scheduling Compatibility ✅ Passed PR contains only frontend UI component changes (dashboard variable templating utilities) with no deployment manifests, operator code, controllers, or scheduling constraints.
Ote Binary Stdout Contract ✅ Passed This PR contains TypeScript/React web components and tests. The OTE Binary Stdout Contract check applies only to Go test binaries with process-level code; this is not applicable here.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed No Ginkgo e2e tests added; PR contains only TypeScript React components and Jest unit tests for dashboard variable utilities, not Kubernetes e2e tests.
No-Weak-Crypto ✅ Passed PR introduces no weak cryptography, custom crypto implementations, or non-constant-time secret comparisons. Changes are purely variable templating and PromQL query escaping.
Container-Privileges ✅ Passed Check is not applicable: PR contains only TypeScript/React source code files, not container/K8s manifests.
No-Sensitive-Data-In-Logs ✅ Passed The PR adds no logging statements that expose sensitive data. The new utility file (variable-utils.ts) and test file contain no console, logger, or error logging that could expose passwords, tokens...

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

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

@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown

Walkthrough

evaluateVariableTemplate and the Variable type are extracted from legacy-variable-dropdowns.tsx into a new variable-utils.ts module alongside isIntervalVariable and escapeIfRegexContext. The dropdowns file is updated to re-export from the new module. A new spec file adds comprehensive tests for evaluateVariableTemplate.

Changes

Variable Utils Extraction

Layer / File(s) Summary
variable-utils.ts: type, escaping, and template evaluation
web/src/components/dashboards/legacy/variable-utils.ts
Defines Variable type, isIntervalVariable predicate, escapeIfRegexContext (applies regex escaping only for =~/!~ operators), and evaluateVariableTemplate (builds auxiliary timespan/interval vars, substitutes $<name> with loading/all/namespace special-casing).
legacy-variable-dropdowns.tsx: re-export from variable-utils
web/src/components/dashboards/legacy/legacy-variable-dropdowns.tsx
Reorganizes imports to source evaluateVariableTemplate and isIntervalVariable from ./variable-utils; removes the in-file Variable type declaration and evaluateVariableTemplate implementation; re-exports both from the new module.
variable-utils.spec.ts: evaluateVariableTemplate test suite
web/src/components/dashboards/legacy/variable-utils.spec.ts
Adds makeVariables helper and tests covering literal substitution, multi-variable replacement, IPv6 bracket and dot escaping per matcher context (=~/!~ vs. =/!=), ALL-option .+ behavior, interval variable interpolation, undefined for empty/loading inputs, and composite PromQL expression output.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 15
✅ Passed checks (15 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: extracting and fixing regex variable escaping logic in matcher contexts.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Stable And Deterministic Test Names ✅ Passed This PR does not contain Ginkgo tests. It adds Jest tests (variable-utils.spec.ts) with static, descriptive test names containing no dynamic values, generated IDs, or timestamps. The check is not a...
Test Structure And Quality ✅ Passed The custom check is for Ginkgo (Go testing framework), but this PR contains Jest/Jasmine tests in TypeScript. No Ginkgo tests are present in the PR, making the check inapplicable.
Microshift Test Compatibility ✅ Passed This PR contains only TypeScript/React components and Jest unit tests—no Ginkgo e2e tests. The custom check applies only to new Ginkgo e2e tests, so it is not applicable.
Single Node Openshift (Sno) Test Compatibility ✅ Passed This PR does not add any Ginkgo e2e tests; it adds Jest unit tests for a TypeScript utility module. The custom check specifically targets Ginkgo Go tests and is not applicable.
Topology-Aware Scheduling Compatibility ✅ Passed PR modifies only React/TypeScript UI components and utility files with no deployment manifests, operator code, controllers, or scheduling constraints.
Ote Binary Stdout Contract ✅ Passed The OTE Binary Stdout Contract check applies to Go test code using Ginkgo/OTE framework. This PR only modifies TypeScript/React frontend code in web/src/components/dashboards/legacy/ and does not i...
Ipv6 And Disconnected Network Test Compatibility ✅ Passed PR contains no Ginkgo e2e tests—only TypeScript/React components and Jest unit tests. Check is not applicable to web frontend code.
No-Weak-Crypto ✅ Passed No weak cryptography detected. The PR refactors dashboard variable utilities and adds tests for regex escaping; it contains no cryptographic code, libraries, or insecure comparisons.
Container-Privileges ✅ Passed This PR contains only TypeScript/React frontend code with no container, Docker, or Kubernetes manifest files. The container-privileges check is not applicable.
No-Sensitive-Data-In-Logs ✅ Passed No logging statements expose passwords, tokens, API keys, PII, session IDs, hostnames, or customer data. Console.error calls log generic errors or operational Prometheus queries without sensitive i...

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

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

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
web/src/components/dashboards/legacy/variable-utils.ts (2)

44-47: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Return type should be string | undefined.

The function returns undefined (lines 46, 72) but is annotated : string, so callers can't see the nullable contract from the type.

♻️ Proposed change
   timespan: number,
   namespace: string,
-): string => {
+): string | undefined => {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/dashboards/legacy/variable-utils.ts` around lines 44 - 47,
The function in variable-utils.ts has a return type annotation of : string but
it actually returns undefined in multiple places (line 46 shown in the diff, and
line 72 mentioned in the comment). Update the function signature's return type
annotation from : string to : string | undefined to correctly reflect that the
function can return either a string or undefined, ensuring callers can see the
nullable contract from the type signature.

68-69: 🩺 Stability & Availability | 🔵 Trivial

Escape regex metacharacters in variable names for robustness.

The key k in new RegExp(\\$${k}`, 'g')should be escaped using_.escapeRegExp(k)to handle edge cases where dashboard variable names contain regex metacharacters like., *, +, etc. While hardcoded interval variables and built-in variables are safe, user-defined variable names from variablesparameter are derived from dashboard templating configuration and could theoretically include special characters. Without escaping, a variable namedtest.varwould incorrectly match$test+ any character +var` instead of the literal pattern.

const re = new RegExp(`\\$${_.escapeRegExp(k)}`, 'g');
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/dashboards/legacy/variable-utils.ts` around lines 68 - 69,
The regular expression pattern in the _.each loop is not escaping the variable
name key, which could cause issues if dashboard variable names contain regex
metacharacters like dots or asterisks. In the line where new RegExp is
constructed with the template string containing the key k, wrap k with
_.escapeRegExp() to properly escape any regex special characters before
inserting it into the pattern. This ensures that variable names like "test.var"
are treated as literal strings rather than regex patterns.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/src/components/dashboards/legacy/variable-utils.ts`:
- Around line 77-79: The condition at line 77 uses `v.name === 'namespace'` but
the Variable type does not have a name property; instead, `k` represents the
variable key in the _.each loop starting at line 68. Replace the check `v.name
=== 'namespace'` with `k === 'namespace'` to correctly identify when processing
the namespace variable. Additionally, the function return type is declared as
`string` on line 38 but the function can implicitly return `undefined` (at lines
46 and 72), so update the return type annotation to `string | undefined` to
match the actual return behavior.

---

Nitpick comments:
In `@web/src/components/dashboards/legacy/variable-utils.ts`:
- Around line 44-47: The function in variable-utils.ts has a return type
annotation of : string but it actually returns undefined in multiple places
(line 46 shown in the diff, and line 72 mentioned in the comment). Update the
function signature's return type annotation from : string to : string |
undefined to correctly reflect that the function can return either a string or
undefined, ensuring callers can see the nullable contract from the type
signature.
- Around line 68-69: The regular expression pattern in the _.each loop is not
escaping the variable name key, which could cause issues if dashboard variable
names contain regex metacharacters like dots or asterisks. In the line where new
RegExp is constructed with the template string containing the key k, wrap k with
_.escapeRegExp() to properly escape any regex special characters before
inserting it into the pattern. This ensures that variable names like "test.var"
are treated as literal strings rather than regex patterns.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: 006e25af-dfa0-4b45-a46d-abd4b071aa91

📥 Commits

Reviewing files that changed from the base of the PR and between d01a05c and 70eeed4.

📒 Files selected for processing (3)
  • web/src/components/dashboards/legacy/legacy-variable-dropdowns.tsx
  • web/src/components/dashboards/legacy/variable-utils.spec.ts
  • web/src/components/dashboards/legacy/variable-utils.ts

Comment thread web/src/components/dashboards/legacy/variable-utils.ts Outdated

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
web/src/components/dashboards/legacy/variable-utils.spec.ts (1)

23-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a regression test for overlapping variable names ($job vs $job_name).

Current suite is thorough, but this edge case is still untested and directly protects substitution correctness.

🧪 Proposed test addition
 describe('evaluateVariableTemplate', () => {
+  it('does not partially replace overlapping variable names', () => {
+    const vars = makeVariables({
+      job: { value: 'short' },
+      job_name: { value: 'long' },
+    });
+    expect(
+      evaluateVariableTemplate('metric{a="$job",b="$job_name"}', vars, timespan, ''),
+    ).toBe('metric{a="short",b="long"}');
+  });
+
   it('substitutes multiple variables', () => {

Also applies to: 77-82

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/dashboards/legacy/variable-utils.spec.ts` around lines 23
- 31, Add a new regression test after the existing substitutes multiple
variables test that specifically tests overlapping variable names to ensure
correct substitution behavior. The new test should call makeVariables with
overlapping variable names like job and job_name (or similar names where one is
a prefix of another), then invoke evaluateVariableTemplate with a template
string that uses both variables (for example, a metric with both $job and
$job_name placeholders), and verify the output correctly substitutes each
variable to its own value rather than incorrectly replacing the shorter variable
name within the longer one.
web/src/components/dashboards/legacy/variable-utils.ts (1)

18-20: 📐 Maintainability & Code Quality | 🔵 Trivial

Replace datasource?: any with datasource?: DataSource.

The Variable type should use the DataSource type already defined in types.ts instead of any. This aligns with how similar fields are typed in Panel and TemplateVariable in the same file. All existing usages access the .name property, which is already part of the DataSource structure, so this change improves type safety without requiring code modifications elsewhere.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/dashboards/legacy/variable-utils.ts` around lines 18 - 20,
In the Variable type definition, replace the datasource field type from any to
DataSource to improve type safety and maintain consistency with similar fields
in Panel and TemplateVariable types. Ensure that the DataSource type is imported
from types.ts if it is not already imported, since all existing usages access
the .name property which is part of the DataSource structure and the change
requires no modifications to existing code.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/src/components/dashboards/legacy/variable-utils.ts`:
- Around line 67-69: The RegExp pattern constructed in the loop iterating
through allVariables is too permissive and matches variable name prefixes rather
than complete variable names. For example, when k is "job", the pattern matches
"$job" inside "$job_name", causing unintended substitutions. Modify the RegExp
pattern in the new RegExp call to use word boundaries (or another appropriate
delimiter pattern) to ensure only complete variable names are matched,
preventing overlap corruption when variable names share common prefixes.

---

Nitpick comments:
In `@web/src/components/dashboards/legacy/variable-utils.spec.ts`:
- Around line 23-31: Add a new regression test after the existing substitutes
multiple variables test that specifically tests overlapping variable names to
ensure correct substitution behavior. The new test should call makeVariables
with overlapping variable names like job and job_name (or similar names where
one is a prefix of another), then invoke evaluateVariableTemplate with a
template string that uses both variables (for example, a metric with both $job
and $job_name placeholders), and verify the output correctly substitutes each
variable to its own value rather than incorrectly replacing the shorter variable
name within the longer one.

In `@web/src/components/dashboards/legacy/variable-utils.ts`:
- Around line 18-20: In the Variable type definition, replace the datasource
field type from any to DataSource to improve type safety and maintain
consistency with similar fields in Panel and TemplateVariable types. Ensure that
the DataSource type is imported from types.ts if it is not already imported,
since all existing usages access the .name property which is part of the
DataSource structure and the change requires no modifications to existing code.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: a1e441a2-ac59-4d02-9e8b-7713d07862e9

📥 Commits

Reviewing files that changed from the base of the PR and between d01a05c and 0ab55ec.

📒 Files selected for processing (3)
  • web/src/components/dashboards/legacy/legacy-variable-dropdowns.tsx
  • web/src/components/dashboards/legacy/variable-utils.spec.ts
  • web/src/components/dashboards/legacy/variable-utils.ts

Comment thread web/src/components/dashboards/legacy/variable-utils.ts
@jgbernalp jgbernalp force-pushed the escape-variables-for-regex-context branch from 0ab55ec to 704dc88 Compare June 23, 2026 11:57
@openshift-ci openshift-ci Bot added the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Jun 23, 2026

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
web/src/components/dashboards/legacy/variable-utils.ts (1)

67-69: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Prevent partial placeholder matches and escape variable keys during regex substitution.

The regex pattern at line 68 matches variable name prefixes rather than complete names. For example, when k is "job", the pattern matches $job inside $job_name, causing deterministic query corruption when variable names share prefixes. Additionally, the variable key is interpolated without escaping, which could allow regex special characters in variable names to alter pattern behavior.

🔧 Proposed fix
 _.each(allVariables, (v, k) => {
-  const re = new RegExp(`\\$${k}`, 'g');
+  const escapedKey = _.escapeRegExp(k);
+  const re = new RegExp(`\\$${escapedKey}(?![A-Za-z0-9_])`, 'g');
   if (result.match(re)) {

The negative lookahead (?![A-Za-z0-9_]) ensures only complete variable names are matched, and _.escapeRegExp(k) prevents regex special characters in variable names from altering the pattern.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/dashboards/legacy/variable-utils.ts` around lines 67 - 69,
In the _.each loop that iterates through allVariables, modify the RegExp pattern
creation to add a negative lookahead assertion `(?![A-Za-z0-9_])` after the
variable key placeholder to ensure only complete variable names are matched (not
prefixes). Additionally, wrap the variable key `k` with `_.escapeRegExp(k)`
before interpolating it into the pattern string to prevent regex special
characters in variable names from altering the pattern behavior.
🧹 Nitpick comments (1)
web/src/components/targets-page.tsx (1)

215-227: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider explicit handling for undefined health state.

The component now explicitly accepts health?: 'up' | 'down', making it clear that health can be undefined. However, when health is undefined, the component renders the "Down" state (RedExclamationCircleIcon + "Down" text), which may be semantically misleading—a target with no health data is different from a target that is confirmed down.

While this PR focuses on typing rather than functional changes, consider adding an explicit case for undefined to improve clarity:

-return health === 'up' ? (
+return health === 'up' ? (
   <>
     <GreenCheckCircleIcon /> {t('Up')}
   </>
+) : health === 'down' ? (
+  <>
+    <RedExclamationCircleIcon /> {t('Down')}
+  </>
 ) : (
   <>
-    <RedExclamationCircleIcon /> {t('Down')}
+    <span>{t('Unknown')}</span>
   </>
 );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/targets-page.tsx` around lines 215 - 227, The Health
component currently treats undefined health state the same as the 'down' state
by rendering RedExclamationCircleIcon, which is semantically misleading since no
health data is different from a confirmed down status. Add an explicit
conditional case in the Health component to handle when health is undefined,
rendering an appropriate indicator for the unknown or no-data state instead of
falling through to the down case, while keeping the existing 'up' and 'down'
cases intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/cypress/component/mocks/perses-dashboards.tsx`:
- Line 7: The mock in the panelOptions conditional is calling the extra function
with an unnecessary empty object argument, but the actual function signature in
ShowTimeseries.tsx defines extra as a zero-argument function. Update the call to
panelOptions.extra() on line 7 to remove the empty object argument {} so it
matches the actual function signature and improves consistency with the real
implementation.

---

Duplicate comments:
In `@web/src/components/dashboards/legacy/variable-utils.ts`:
- Around line 67-69: In the _.each loop that iterates through allVariables,
modify the RegExp pattern creation to add a negative lookahead assertion
`(?![A-Za-z0-9_])` after the variable key placeholder to ensure only complete
variable names are matched (not prefixes). Additionally, wrap the variable key
`k` with `_.escapeRegExp(k)` before interpolating it into the pattern string to
prevent regex special characters in variable names from altering the pattern
behavior.

---

Nitpick comments:
In `@web/src/components/targets-page.tsx`:
- Around line 215-227: The Health component currently treats undefined health
state the same as the 'down' state by rendering RedExclamationCircleIcon, which
is semantically misleading since no health data is different from a confirmed
down status. Add an explicit conditional case in the Health component to handle
when health is undefined, rendering an appropriate indicator for the unknown or
no-data state instead of falling through to the down case, while keeping the
existing 'up' and 'down' cases intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: 8c1d8792-378d-4b33-af73-0d505ef33588

📥 Commits

Reviewing files that changed from the base of the PR and between 0ab55ec and 704dc88.

📒 Files selected for processing (27)
  • web/cypress/component/mocks/AddToDashboardButton.tsx
  • web/cypress/component/mocks/OlsToolUIPersesWrapper.tsx
  • web/cypress/component/mocks/perses-dashboards.tsx
  • web/cypress/dummy.tsx
  • web/cypress/support/incidents_prometheus_query_mocks/mock-generators.ts
  • web/cypress/support/incidents_prometheus_query_mocks/prometheus-mocks.ts
  • web/cypress/support/incidents_prometheus_query_mocks/schema/validate-fixtures.ts
  • web/cypress/support/index.ts
  • web/eslint.config.ts
  • web/src/components/alerting/AlertList/AggregateAlertTableRow.tsx
  • web/src/components/alerting/AlertRulesDetailsPage.tsx
  • web/src/components/alerting/AlertUtils.tsx
  • web/src/components/alerting/SilencesUtils.tsx
  • web/src/components/console/console-shared/src/components/empty-state/EmptyBox.tsx
  • web/src/components/console/console-shared/src/components/loading/Loading.tsx
  • web/src/components/dashboards/legacy/dashboard-skeleton-legacy.tsx
  • web/src/components/dashboards/legacy/legacy-dashboard.tsx
  • web/src/components/dashboards/legacy/legacy-variable-dropdowns.tsx
  • web/src/components/dashboards/legacy/variable-utils.spec.ts
  • web/src/components/dashboards/legacy/variable-utils.ts
  • web/src/components/dashboards/perses/dashboard-header.tsx
  • web/src/components/dashboards/shared/dashboard-dropdown.tsx
  • web/src/components/labels.tsx
  • web/src/components/ols-tool-ui/helpers/AddToDashboardButton.tsx
  • web/src/components/ols-tool-ui/helpers/OlsToolUIPersesWrapper.tsx
  • web/src/components/query-browser.tsx
  • web/src/components/targets-page.tsx
💤 Files with no reviewable changes (4)
  • web/cypress/support/index.ts
  • web/cypress/dummy.tsx
  • web/cypress/support/incidents_prometheus_query_mocks/mock-generators.ts
  • web/cypress/support/incidents_prometheus_query_mocks/prometheus-mocks.ts
✅ Files skipped from review due to trivial changes (7)
  • web/cypress/component/mocks/AddToDashboardButton.tsx
  • web/src/components/alerting/AlertRulesDetailsPage.tsx
  • web/src/components/console/console-shared/src/components/loading/Loading.tsx
  • web/src/components/alerting/SilencesUtils.tsx
  • web/src/components/dashboards/legacy/dashboard-skeleton-legacy.tsx
  • web/src/components/query-browser.tsx
  • web/cypress/support/incidents_prometheus_query_mocks/schema/validate-fixtures.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • web/src/components/dashboards/legacy/legacy-variable-dropdowns.tsx
  • web/src/components/dashboards/legacy/variable-utils.spec.ts

Comment thread web/cypress/component/mocks/perses-dashboards.tsx
Signed-off-by: Gabriel Bernal <gbernal@redhat.com>
@jgbernalp jgbernalp force-pushed the escape-variables-for-regex-context branch from 704dc88 to 03bb196 Compare June 23, 2026 16:15
@openshift-ci openshift-ci Bot removed the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Jun 23, 2026

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

🧹 Nitpick comments (1)
web/src/components/dashboards/legacy/variable-utils.ts (1)

18-19: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Replace any on datasource with a safer type.

Using any here drops type-safety in downstream usage. Prefer unknown (with narrowing at use sites) or a concrete union/interface.

Suggested minimal change
 export type Variable = {
   isHidden?: boolean;
   isLoading?: boolean;
   includeAll?: boolean;
   options?: string[];
   query?: string;
   value?: string;
-  // eslint-disable-next-line `@typescript-eslint/no-explicit-any`
-  datasource?: any;
+  datasource?: unknown;
 };

As per coding guidelines, “Avoid using 'any' type; use proper type definitions instead.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/dashboards/legacy/variable-utils.ts` around lines 18 - 19,
The datasource property in the interface/type is currently typed as any, which
eliminates type-safety in downstream code. Replace the any type annotation for
the datasource field with either unknown (and add appropriate type narrowing at
usage sites) or a concrete type definition such as a union of specific data
source types or a defined interface. Remove or adjust the eslint-disable comment
accordingly once the type is properly defined, as it will no longer be
necessary.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@web/src/components/dashboards/legacy/variable-utils.ts`:
- Around line 18-19: The datasource property in the interface/type is currently
typed as any, which eliminates type-safety in downstream code. Replace the any
type annotation for the datasource field with either unknown (and add
appropriate type narrowing at usage sites) or a concrete type definition such as
a union of specific data source types or a defined interface. Remove or adjust
the eslint-disable comment accordingly once the type is properly defined, as it
will no longer be necessary.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: 9f30df09-60bf-401d-b430-c25114ef02c3

📥 Commits

Reviewing files that changed from the base of the PR and between 704dc88 and 03bb196.

📒 Files selected for processing (3)
  • web/src/components/dashboards/legacy/legacy-variable-dropdowns.tsx
  • web/src/components/dashboards/legacy/variable-utils.spec.ts
  • web/src/components/dashboards/legacy/variable-utils.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • web/src/components/dashboards/legacy/variable-utils.spec.ts
  • web/src/components/dashboards/legacy/legacy-variable-dropdowns.tsx

@openshift-ci

openshift-ci Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

@jgbernalp: The following tests failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
ci/prow/images 03bb196 link true /test images
ci/prow/e2e-aws-ovn 03bb196 link true /test e2e-aws-ovn

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. jira/severity-moderate Referenced Jira bug's severity is moderate for the branch this PR is targeting. jira/valid-bug Indicates that a referenced Jira bug is valid for the branch this PR is targeting. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants