From f1f0082e7c165f148ae95f4deeb2786404797a39 Mon Sep 17 00:00:00 2001 From: Thomas Chopitea Date: Mon, 9 Sep 2024 21:04:34 +0900 Subject: [PATCH] Add max length to tags (#1132) --- core/schemas/tag.py | 4 +++- core/web/apiv2/observables.py | 5 ++++- tests/apiv2/observables.py | 23 +++++++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/core/schemas/tag.py b/core/schemas/tag.py index 7ab270feb..ea48a3b3f 100644 --- a/core/schemas/tag.py +++ b/core/schemas/tag.py @@ -11,6 +11,8 @@ DEFAULT_EXPIRATION = datetime.timedelta(days=30) # Completely arbitrary +MAX_TAG_LENGTH = 50 + def future(): return DEFAULT_EXPIRATION @@ -30,7 +32,7 @@ class Tag(YetiModel, database_arango.ArangoYetiConnector): _collection_name: ClassVar[str] = "tags" _type_filter: ClassVar[str | None] = None - name: str + name: str = Field(max_length=MAX_TAG_LENGTH) count: int = 0 created: datetime.datetime = Field(default_factory=now) default_expiration: datetime.timedelta = DEFAULT_EXPIRATION diff --git a/core/web/apiv2/observables.py b/core/web/apiv2/observables.py index 88e5dc652..896127bf8 100644 --- a/core/web/apiv2/observables.py +++ b/core/web/apiv2/observables.py @@ -5,6 +5,7 @@ from core.schemas import graph from core.schemas.observable import TYPE_MAPPING, Observable, ObservableType +from core.schemas.tag import MAX_TAG_LENGTH ObservableTypes = () @@ -25,8 +26,10 @@ class TagRequestMixin(BaseModel): @classmethod def validate_tags(cls, value) -> list[str]: for tag in value: - if not tag: + if not tag or not tag.strip(): raise ValueError("Tags cannot be empty") + if len(tag) > MAX_TAG_LENGTH: + raise ValueError(f"Tag {tag} exceeds max length ({MAX_TAG_LENGTH})") return value diff --git a/tests/apiv2/observables.py b/tests/apiv2/observables.py index 412b77cc1..53f69964c 100644 --- a/tests/apiv2/observables.py +++ b/tests/apiv2/observables.py @@ -220,6 +220,29 @@ def test_create_observable_empty_tags(self): data["detail"][0]["msg"], "Value error, Tags cannot be empty", data ) + response = client.post( + "/api/v2/observables/", + json={"value": "toto.com", "type": "hostname", "tags": [" "]}, + ) + data = response.json() + self.assertEqual(response.status_code, 422, data) + self.assertEqual( + data["detail"][0]["msg"], "Value error, Tags cannot be empty", data + ) + + def test_create_observable_toolong_tag(self): + response = client.post( + "/api/v2/observables/", + json={"value": "toto.com", "type": "hostname", "tags": ["tag1", "a" * 200]}, + ) + data = response.json() + self.assertEqual(response.status_code, 422, data) + self.assertEqual( + data["detail"][0]["msg"], + f"Value error, Tag {'a'*200} exceeds max length (50)", + data, + ) + def test_create_extended_observable(self): response = client.post( "/api/v2/observables/extended",