From ebf6513445c54553199c8dcb7c8beefdf73bb707 Mon Sep 17 00:00:00 2001 From: Greg Back Date: Tue, 17 Jan 2017 14:46:00 -0800 Subject: [PATCH] Check for valid IDs and types on indicators. --- stix2/__init__.py | 8 +++++++- stix2/test/test_stix2.py | 27 ++++++++++++++++++++++----- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/stix2/__init__.py b/stix2/__init__.py index 678374a..4a3420e 100644 --- a/stix2/__init__.py +++ b/stix2/__init__.py @@ -31,10 +31,16 @@ class Indicator: labels=None, pattern=None, valid_from=None): now = datetime.now(tz=pytz.UTC) + if type != 'indicator': + raise ValueError("Indicators must have type='indicator'.") self.type = type + if not id: - id = "indicator--" + str(uuid.uuid4()) + id = 'indicator--' + str(uuid.uuid4()) + if not id.startswith('indicator--'): + raise ValueError("Indicator id values must begin with 'indicator--'.") self.id = id + self.created = created or now self.modified = modified or now self.labels = labels diff --git a/stix2/test/test_stix2.py b/stix2/test/test_stix2.py index c2d6271..59dd820 100644 --- a/stix2/test/test_stix2.py +++ b/stix2/test/test_stix2.py @@ -51,12 +51,15 @@ def test_indicator_with_all_required_fields(): assert str(indicator) == EXPECTED -def test_indicator_autogenerated_fields(): - indicator = stix2.Indicator( - labels=['malicious-activity'], - pattern="[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", - ) +# Minimum required args for an indicator +KWARGS = dict( + labels=['malicious-activity'], + pattern="[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", +) + +def test_indicator_autogenerated_fields(): + indicator = stix2.Indicator(**KWARGS) assert indicator.type == 'indicator' assert indicator.id.startswith('indicator--') assert indicator.created is not None @@ -64,3 +67,17 @@ def test_indicator_autogenerated_fields(): assert indicator.labels == ['malicious-activity'] assert indicator.pattern == "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']" assert indicator.valid_from is not None + + +def test_indicator_type_must_be_indicator(): + with pytest.raises(ValueError) as excinfo: + indicator = stix2.Indicator(type='xxx') + + assert "Indicators must have type='indicator'." in str(excinfo) + + +def test_indicator_id_must_start_with_indicator(): + with pytest.raises(ValueError) as excinfo: + indicator = stix2.Indicator(id='my-prefix--') + + assert "Indicator id values must begin with 'indicator--'." in str(excinfo)