Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions src/tasks/managed/check_labels/check_labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,16 @@ def derive_name_from_url(url: str) -> str:
def get_label_value(component: dict[str, Any], label_name: str) -> str | None:
"""Extract a label value from a component's metadata labels list.

Return ``None`` when the label is absent or has no value.
Return ``None`` when the label key is absent from the metadata. Return
an empty string when the label is present but its value is empty or
whitespace-only, so callers can distinguish an unset label from one
that was set to an empty value.
"""
labels = component.get("metadata", {}).get("labels") or []
for label in labels:
if label.get("name") == label_name:
val = label.get("value")
if val is not None and str(val).strip():
return str(val)
return str(val).strip() if val is not None else ""

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

2. Whitespace bypasses label validation 🐞 Bug ≡ Correctness

get_label_value strips surrounding whitespace from every non-empty label before validation, so a
stored name or cpe value such as " expected " incorrectly matches "expected". This allows
malformed image metadata to pass enforce-mode validation.
Agent Prompt
## Issue description
`get_label_value` must distinguish missing and empty labels without altering non-empty values. Its new unconditional `strip()` causes labels containing surrounding whitespace to pass exact-equality validation.

## Issue Context
Return `""` when a value is empty or whitespace-only, but return the original string representation when it contains non-whitespace characters. Add tests proving whitespace-padded `name` and `cpe` labels fail or warn rather than matching normalized expected values.

## Fix Focus Areas
- src/tasks/managed/check_labels/check_labels.py[46-59]
- src/tasks/managed/check_labels/tests/test_check_labels.py[90-120]
- src/tasks/managed/check_labels/tests/test_check_labels.py[144-260]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

return None


Expand Down Expand Up @@ -122,13 +124,23 @@ def _check_cpe_label(component: dict[str, Any], cpe_data: str, enforce: bool) ->
comp_name = component["name"]
cpe_label = get_label_value(component, "cpe")

if not cpe_label:
if cpe_label is None:
logger.info(
"Component '%s' is missing the 'cpe' label. Skipping enforcement.",
comp_name,
)
return

if not cpe_label:
msg = (
f"Component '{comp_name}' 'cpe' label is set to an empty value. "
f"Expected the value '{cpe_data}'."
)
if enforce:
raise LabelValidationError(msg)
logger.warning(msg)
return

if cpe_label != cpe_data:
msg = (
f"Component '{comp_name}' 'cpe' label ('{cpe_label}') does not "
Expand Down
65 changes: 65 additions & 0 deletions src/tasks/managed/check_labels/tests/test_check_labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,18 @@ def test_get_label_value_no_labels_key() -> None:
assert check_labels.get_label_value(comp, "name") is None


def test_get_label_value_present_but_empty() -> None:
"""Return an empty string when the label is present with an empty value."""
comp = _make_component(labels=[_name_label("")])
assert check_labels.get_label_value(comp, "name") == ""


def test_get_label_value_present_but_whitespace() -> None:
"""Return an empty string when the label value is whitespace-only."""
comp = _make_component(labels=[_name_label(" ")])
assert check_labels.get_label_value(comp, "name") == ""


# --- is_image_media_type ---


Expand Down Expand Up @@ -195,6 +207,59 @@ def test_no_cpe_label_skips(tmp_path: Path, caplog: pytest.LogCaptureFixture) ->
assert "missing the 'cpe' label" in caplog.text


def test_empty_cpe_label_enforce(tmp_path: Path) -> None:
"""Fail when the CPE label is present but set to an empty string."""
Comment on lines +210 to +211

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

1. Unit tests not co-located 📘 Rule violation ▣ Testability

The new check_labels unit tests are placed in a nested tests/ directory rather than alongside
check_labels.py. This violates the required test placement for source files outside utils/.
Agent Prompt
## Issue description
The newly added unit tests are under a nested `tests/` directory instead of being co-located with `check_labels.py`.

## Issue Context
PR Compliance ID 909 requires unit tests for source files outside `utils/` to reside in the same directory as their source file. Move or consolidate the tests into a co-located test module while preserving pytest discovery and imports.

## Fix Focus Areas
- src/tasks/managed/check_labels/tests/test_check_labels.py[111-260]
- src/tasks/managed/check_labels/check_labels.py[46-58]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

snap = tmp_path / "snapshot.json"
data = tmp_path / "data.json"
_write_snapshot(
snap,
[
_make_component(
labels=[
_name_label("openshift-gitops-1/gitops-rhel8-operator"),
_cpe_label(""),
],
repositories=[
{
"rh-registry-repo": "registry.redhat.io/openshift-gitops-1"
"/gitops-rhel8-operator"
}
],
)
],
)
_write_data(data)
with pytest.raises(check_labels.LabelValidationError, match="empty value"):
check_labels._check_labels(snap, data, enforce=True)


def test_empty_cpe_label_warn(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
"""Warn but succeed when the CPE label is empty and enforce is False."""
snap = tmp_path / "snapshot.json"
data = tmp_path / "data.json"
_write_snapshot(
snap,
[
_make_component(
labels=[
_name_label("openshift-gitops-1/gitops-rhel8-operator"),
_cpe_label(""),
],
repositories=[
{
"rh-registry-repo": "registry.redhat.io/openshift-gitops-1"
"/gitops-rhel8-operator"
}
],
)
],
)
_write_data(data)
with caplog.at_level(logging.WARNING, logger="release"):
check_labels._check_labels(snap, data, enforce=False)
assert "'cpe' label is set to an empty value" in caplog.text


# --- check_labels (name label failures) ---


Expand Down
Loading