Skip to content

Class name is rule id #212

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pypanther/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,10 @@ def __init_subclass__(cls, **kwargs):
child.tags.append("Foo")
parent.tags.append("Foo") # not inherited by children of parent
"""
# Set the id to the class name if it's not explicitly set
if "id" not in cls.__dict__ or not cls.__dict__["id"]:
cls.id = cls.__name__

for attr in RULE_ALL_ATTRS:
if attr not in cls.__dict__:
try:
Expand Down
2 changes: 1 addition & 1 deletion pypanther/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def convert_rule(filepath: Path, helpers: Set[str]) -> Optional[str]:
)
value = ast.List(elts=log_type_elts)
if k == "RuleID":
value = ast.Constant(value=v + ID_POSTFIX)
continue

assignments.append(
ast.Assign(
Expand Down
15 changes: 6 additions & 9 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
TRUNCATED_STRING_SUFFIX,
TYPE_RULE,
)
from pydantic import ValidationError

from pypanther.base import RULE_ALL_ATTRS, Rule, RuleModel, panther_managed
from pypanther.cache import data_model_cache
Expand Down Expand Up @@ -353,20 +352,18 @@ def rule(self, event):


class TestValidation:
def test_rule_missing_id(self):
class rule(Rule):
def test_rule_id_is_class_name(self):
"""Test that a rule's id is automatically set to its class name."""

class TestRule(Rule):
default_severity = Severity.INFO
log_types = ["test"]

def rule(self, event):
return False

with pytest.raises(ValidationError) as e:
rule.validate()
errors = e.value.errors()
assert len(errors) == 1
assert errors[0]["loc"] == ("id",)
assert errors[0]["msg"] == "Field required"
# Verify that id is set to the class name
assert TestRule.id == "TestRule"

def test_create_rule_missing_method(self) -> None:
class rule(Rule):
Expand Down