Skip to content
Draft
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
*.log text encoding=utf-8
datasets/**/*.json filter=lfs diff=lfs merge=lfs -text
datasets/**/*.log filter=lfs diff=lfs merge=lfs -text
datasets_old/**/*.log filter=lfs diff=lfs merge=lfs -text
datasets/**/*.ndjson filter=lfs diff=lfs merge=lfs -text
datasets/**/*.csv filter=lfs diff=lfs merge=lfs -text
76 changes: 76 additions & 0 deletions .github/workflows/validate-paths.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
name: Validate Dataset Paths

on:
pull_request:
branches: [master, main]
types: [opened, synchronize, reopened]
paths:
- 'datasets/**/*.yml'
- 'datasets/**/*.yaml'
- 'bin/validate_dataset_paths.py'
- 'bin/validate_security_content_references.py'
- '.github/workflows/validate-paths.yml'
push:
branches: [master, main]
paths:
- 'datasets/**/*.yml'
- 'datasets/**/*.yaml'
- 'bin/validate_dataset_paths.py'
- 'bin/validate_security_content_references.py'
- '.github/workflows/validate-paths.yml'

permissions:
contents: read

jobs:
validate-dataset-paths:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
lfs: 'false'

- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: '3.12'

- name: Install YAML dependency
run: python -m pip install pyyaml

- name: Check dataset file references
run: python bin/validate_dataset_paths.py

validate-security-content-references:
runs-on: ubuntu-latest

steps:
- name: Checkout Attack Data repository
uses: actions/checkout@v6
with:
lfs: 'false'

- name: Checkout Security Content detections
uses: actions/checkout@v6
with:
repository: splunk/security_content
ref: develop
path: security_content
fetch-depth: 1
sparse-checkout: detections
sparse-checkout-cone-mode: true

- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: '3.12'

- name: Install YAML dependency
run: python -m pip install pyyaml

- name: Check Security Content test data references
run: >-
python bin/validate_security_content_references.py
--security-content-dir security_content/detections
42 changes: 0 additions & 42 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ on:
permissions:
contents: read
issues: write
pull-requests: write

jobs:
validate-attack-data:
Expand Down Expand Up @@ -52,47 +51,6 @@ jobs:
env:
PYTHONPATH: ${{ github.workspace }}/bin

# PR-specific success/failure handling
- name: Comment PR on validation failure
if: failure() && github.event_name == 'pull_request'
uses: actions/github-script@v9
with:
script: |
const { owner, repo, number } = context.issue;

const body = `❌ **Attack Data Validation Failed**

The YAML files in this PR do not pass validation. Please check the workflow logs for detailed error messages and fix the issues before merging.

[View workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})`;

await github.rest.issues.createComment({
owner,
repo,
issue_number: number,
body: body
});

- name: Comment PR on validation success
if: success() && github.event_name == 'pull_request'
uses: actions/github-script@v9
with:
script: |
const { owner, repo, number } = context.issue;

const body = `✅ **Attack Data Validation Passed**

All YAML files in this PR have been successfully validated against the schema.

Ready for review and merge! 🚀`;

await github.rest.issues.createComment({
owner,
repo,
issue_number: number,
body: body
});

# Push-specific failure handling (create issue)
- name: Create issue on validation failure (Push)
if: failure() && github.event_name == 'push'
Expand Down
1 change: 1 addition & 0 deletions bin/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ def find_yaml_files(input_dir: Path) -> List[Path]:
yaml_files = [
f for f in yaml_files
if not f.name.startswith('TEMPLATE') and 'old' not in f.name.lower()
and f.name.lower() not in {'replay.yml', 'replay.yaml'}
]

return sorted(yaml_files)
Expand Down
171 changes: 171 additions & 0 deletions bin/validate_dataset_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Check that file paths in dataset YAML files exist in this repository."""

from __future__ import annotations

import sys
from dataclasses import dataclass
from pathlib import Path, PureWindowsPath
from typing import Any

import yaml


REPOSITORY_ROOT = Path(__file__).resolve().parent.parent
DATASETS_DIRECTORY = REPOSITORY_ROOT / "datasets"


@dataclass(frozen=True)
class Finding:
location: str
referenced_path: str
issue: str


def find_path_values(value: Any):
"""Yield every value stored under a ``path`` key in a YAML structure."""
if isinstance(value, dict):
for key, child in value.items():
if key == "path":
yield child
else:
yield from find_path_values(child)
elif isinstance(value, list):
for child in value:
yield from find_path_values(child)


def resolve_reference(reference: str, yaml_file: Path) -> Path:
"""Resolve repository-rooted and YAML-relative dataset paths."""
if PureWindowsPath(reference).is_absolute():
raise ValueError("Windows absolute paths are not repository paths")

# Dataset descriptors conventionally use /datasets/...; the leading slash
# is repository-rooted, not an operating-system filesystem path.
normalized = reference.replace("\\", "/")
if normalized.startswith("/datasets/"):
candidate = REPOSITORY_ROOT / normalized.lstrip("/")
elif normalized.startswith("datasets/"):
candidate = REPOSITORY_ROOT / normalized
elif normalized.startswith("/"):
candidate = REPOSITORY_ROOT / normalized.lstrip("/")
else:
candidate = yaml_file.parent / normalized

root = REPOSITORY_ROOT.resolve()
resolved = candidate.resolve()
if not resolved.is_relative_to(root):
raise ValueError("path resolves outside the repository")
return resolved


def inspect_yaml_files() -> tuple[int, int, list[Finding]]:
yaml_files = sorted(
yaml_file
for yaml_file in [
*DATASETS_DIRECTORY.rglob("*.yml"),
*DATASETS_DIRECTORY.rglob("*.yaml"),
]
if not yaml_file.name.lower().startswith("template")
)
reference_count = 0
findings: list[Finding] = []
referenced_files: set[Path] = set()

for yaml_file in yaml_files:
relative_yaml = yaml_file.relative_to(REPOSITORY_ROOT).as_posix()
try:
with yaml_file.open(encoding="utf-8") as stream:
document = yaml.safe_load(stream)
except (OSError, UnicodeError, yaml.YAMLError) as error:
message = " ".join(str(error).splitlines())
findings.append(Finding(relative_yaml, "—", f"could not read YAML: {message}"))
continue

if not isinstance(document, dict):
continue

references_in_yaml: dict[Path, str] = {}
for value in find_path_values(document):
reference_count += 1
if not isinstance(value, str) or not value.strip():
findings.append(Finding(relative_yaml, repr(value), "path must be a non-empty string"))
continue

try:
target = resolve_reference(value.strip(), yaml_file)
except ValueError as error:
findings.append(Finding(relative_yaml, value, str(error)))
continue

if target in references_in_yaml:
findings.append(
Finding(
relative_yaml,
value,
f"duplicate reference (already listed as {references_in_yaml[target]})",
)
)
else:
references_in_yaml[target] = value

if not target.is_file():
findings.append(Finding(relative_yaml, value, "file does not exist"))
else:
referenced_files.add(target)

yaml_read_errors = any(item.issue.startswith("could not read YAML:") for item in findings)
if not yaml_read_errors:
data_files = {
path.resolve()
for path in DATASETS_DIRECTORY.rglob("*")
if path.is_file()
and path.suffix.lower() not in {".yml", ".yaml"}
and path.name != ".gitkeep"
}
unreferenced_files = sorted(data_files - referenced_files)
for path in unreferenced_files:
findings.append(
Finding(
"—",
path.relative_to(REPOSITORY_ROOT).as_posix(),
"file is not referenced by any YAML path",
)
)

return len(yaml_files), reference_count, findings


def print_findings(findings: list[Finding]) -> None:
headers = ("Descriptor / file", "Referenced path", "Issue")
rows = [(item.location, item.referenced_path, item.issue) for item in findings]
if not rows:
rows = [("—", "—", "No path issues found")]
widths = [max(len(headers[index]), *(len(row[index]) for row in rows)) for index in range(3)]

def format_row(row: tuple[str, str, str]) -> str:
return " " + " | ".join(value.ljust(widths[index]) for index, value in enumerate(row))

print(format_row(headers))
print(" " + "--".join("-" * width for width in widths))
for row in rows:
print(format_row(row))


def main() -> int:
_, _, findings = inspect_yaml_files()
if findings:
print(
"This table lists invalid or duplicate YAML paths and files under "
"datasets that no YAML path references."
)
print_findings(findings)
return 1

print("This table shows whether any dataset path issues were found.")
print_findings(findings)
return 0


if __name__ == "__main__":
sys.exit(main())
Loading
Loading