def test_query_basealert_invalid_criteria_values(): tests = [ {"method": "set_categories", "arg": ["DOUBLE_DARE"]}, {"method": "set_device_ids", "arg": ["Bogus"]}, {"method": "set_device_names", "arg": [42]}, {"method": "set_device_os", "arg": ["TI994A"]}, {"method": "set_device_os_versions", "arg": [8808]}, {"method": "set_device_username", "arg": [-1]}, {"method": "set_alert_ids", "arg": [9001]}, {"method": "set_legacy_alert_ids", "arg": [9001]}, {"method": "set_policy_ids", "arg": ["Bogus"]}, {"method": "set_policy_names", "arg": [323]}, {"method": "set_process_names", "arg": [7071]}, {"method": "set_process_sha256", "arg": [123456789]}, {"method": "set_reputations", "arg": ["MICROSOFT_FUDWARE"]}, {"method": "set_tags", "arg": [-1]}, {"method": "set_target_priorities", "arg": ["DOGWASH"]}, {"method": "set_threat_ids", "arg": [4096]}, {"method": "set_types", "arg": ["ERBOSOFT"]}, {"method": "set_workflows", "arg": ["IN_LIMBO"]}, ] api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) query = api.select(BaseAlert) for t in tests: meth = getattr(query, t["method"], None) with pytest.raises(ApiError): meth(t["arg"])
def test_query_device_do_update_policy(monkeypatch): _was_called = False def _update_policy(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == { "action_type": "UPDATE_POLICY", "search": { "query": "foobar", "criteria": {}, "exclusions": {} }, "options": { "policy_id": 8675309 } } _was_called = True return StubResponse(None, 204) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, POST=_update_policy) api.select(Device).where("foobar").update_policy(8675309) assert _was_called
def test_alerts_bulk_dismiss_vmware(monkeypatch): """Test dismissing a batch of VMware alerts.""" _was_called = False def _do_dismiss(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/alerts/cbanalytics/workflow/_criteria" assert body == { "query": "Blort", "state": "DISMISSED", "remediation_state": "Fixed", "comment": "Yessir", "criteria": { "device_name": ["HAL9000"] } } _was_called = True return StubResponse({"request_id": "497ABX"}) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, POST=_do_dismiss) q = api.select(CBAnalyticsAlert).where("Blort").set_device_names( ["HAL9000"]) reqid = q.dismiss("Fixed", "Yessir") assert _was_called assert reqid == "497ABX"
def test_query_device_do_update_sensor_version(monkeypatch): _was_called = False def _update_sensor_version(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == { "action_type": "UPDATE_SENSOR_VERSION", "search": { "query": "foobar", "criteria": {}, "exclusions": {} }, "options": { "sensor_version": { "RHEL": "2.3.4.5" } } } _was_called = True return StubResponse(None, 204) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, POST=_update_sensor_version) api.select(Device).where("foobar").update_sensor_version( {"RHEL": "2.3.4.5"}) assert _was_called
def test_query_basealert_facets(monkeypatch): _was_called = False def _run_facet_query(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/alerts/_facet" assert body["query"] == "Blort" t = body["criteria"] assert t["workflow"] == ["OPEN"] t = body["terms"] assert t["rows"] == 0 assert t["fields"] == ["REPUTATION", "STATUS"] _was_called = True return StubResponse({"results": [{"field": {}, "values": [{"id": "reputation", "name": "reputationX", "total": 4}]}, {"field": {}, "values": [{"id": "status", "name": "statusX", "total": 9}]}]}) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, POST=_run_facet_query) query = api.select(BaseAlert).where("Blort").set_workflows(["OPEN"]) f = query.facets(["REPUTATION", "STATUS"]) assert _was_called assert f == [{"field": {}, "values": [{"id": "reputation", "name": "reputationX", "total": 4}]}, {"field": {}, "values": [{"id": "status", "name": "statusX", "total": 9}]}]
def test_query_device_invalid_sort_direction(): api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) with pytest.raises(ApiError): api.select(Device).sort_by("policy_name", "BOGUS")
def test_query_device_download(monkeypatch): _was_called = False def _run_download(url, query_params, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/devices/_search/download" assert query_params == { "status": "ALL", "ad_group_id": "14,25", "policy_id": "8675309", "target_priority": "HIGH", "query_string": "foobar", "sort_field": "name", "sort_order": "DESC" } _was_called = True return "123456789,123456789,123456789" api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, RAW_GET=_run_download) rc = api.select(Device).where("foobar").set_ad_group_ids([14, 25]).set_policy_ids([8675309]) \ .set_status(["ALL"]).set_target_priorities(["HIGH"]).sort_by("name", "DESC").download() assert _was_called assert rc == "123456789,123456789,123456789"
def test_device_update_sensor_version(monkeypatch): _was_called = False def _call_update_sensor_version(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == { "action_type": "UPDATE_SENSOR_VERSION", "device_id": [6023], "options": { "sensor_version": { "RHEL": "2.3.4.5" } } } _was_called = True return StubResponse(None, 204) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, POST=_call_update_sensor_version) api.device_update_sensor_version([6023], {"RHEL": "2.3.4.5"}) assert _was_called
def test_query_device_invalid_criteria_values(): tests = [{ "method": "set_ad_group_ids", "arg": ["Bogus"] }, { "method": "set_policy_ids", "arg": ["Bogus"] }, { "method": "set_os", "arg": ["COMMODORE_64"] }, { "method": "set_status", "arg": ["Bogus"] }, { "method": "set_target_priorities", "arg": ["Bogus"] }, { "method": "set_exclude_sensor_versions", "arg": [12703] }] api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) query = api.select(Device) for t in tests: meth = getattr(query, t["method"], None) with pytest.raises(ApiError): meth(t["arg"])
def test_query_watchlistalert_facets(monkeypatch): """Test a watchlist alert facet query.""" _was_called = False def _run_facet_query(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/alerts/watchlist/_facet" assert body == { "query": "Blort", "criteria": { "workflow": ["OPEN"] }, "terms": { "rows": 0, "fields": ["REPUTATION", "STATUS"] }, "rows": 100 } _was_called = True return StubResponse({ "results": [{ "field": {}, "values": [{ "id": "reputation", "name": "reputationX", "total": 4 }] }, { "field": {}, "values": [{ "id": "status", "name": "statusX", "total": 9 }] }] }) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, POST=_run_facet_query) query = api.select(WatchlistAlert).where("Blort").set_workflows(["OPEN"]) f = query.facets(["REPUTATION", "STATUS"]) assert _was_called assert f == [{ "field": {}, "values": [{ "id": "reputation", "name": "reputationX", "total": 4 }] }, { "field": {}, "values": [{ "id": "status", "name": "statusX", "total": 9 }] }]
def test_audit_remediation_history_with_everything(monkeypatch): """Test a query of run history with all possible options.""" _was_called = False def _run_query(url, body, **kwargs): nonlocal _was_called assert url == "/livequery/v1/orgs/Z100/runs/_search" assert body == {"query": "xyzzy", "sort": [{"field": "id", "order": "ASC"}], "start": 0} _was_called = True return StubResponse({"org_key": "Z100", "num_found": 3, "results": [{"org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg"}, {"org_key": "Z100", "name": "Aoxomoxoa", "id": "cdefghi"}, {"org_key": "Z100", "name": "Read_Me", "id": "efghijk"}]}) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, POST=_run_query) query = api.audit_remediation_history("xyzzy").sort_by("id") assert isinstance(query, RunHistoryQuery) count = 0 for item in query.all(): assert item.org_key == "Z100" if item.id == "abcdefg": assert item.name == "FoobieBletch" elif item.id == "cdefghi": assert item.name == "Aoxomoxoa" elif item.id == "efghijk": assert item.name == "Read_Me" else: pytest.fail("Unknown item ID: %s" % item.id) count = count + 1 assert _was_called assert count == 3
def test_load_workflow(monkeypatch): """Test loading a workflow status.""" _was_called = False def _get_workflow(url, parms=None, default=None): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/workflow/status/497ABX" _was_called = True return { "errors": [], "failed_ids": [], "id": "497ABX", "num_hits": 0, "num_success": 0, "status": "QUEUED", "workflow": { "state": "DISMISSED", "remediation": "Fixed", "comment": "Yessir", "changed_by": "Robocop", "last_update_time": "2019-10-31T16:03:13.951Z" } } api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, GET=_get_workflow) workflow = api.select(WorkflowStatus, "497ABX") assert _was_called assert workflow.id_ == "497ABX"
def test_query_device_do_quarantine(monkeypatch): _was_called = False def _quarantine(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == { "action_type": "QUARANTINE", "search": { "query": "foobar", "criteria": {}, "exclusions": {} }, "options": { "toggle": "ON" } } _was_called = True return StubResponse(None, 204) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, POST=_quarantine) api.select(Device).where("foobar").quarantine(True) assert _was_called
def test_alerts_bulk_threat_error(monkeypatch): """Test error raise from bulk threat update status""" api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) with pytest.raises(ApiError): api.bulk_threat_dismiss([123], "Fixed", "Yessir")
def test_query_devicecontrolalert_invalid_criteria_values(method, arg): """Test invalid values being supplied to DeviceControl alert queries.""" api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) query = api.select(DeviceControlAlert) meth = getattr(query, method, None) with pytest.raises(ApiError): meth(arg)
def test_query_basealert_invalid_create_time_combinations(): api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) with pytest.raises(ApiError): api.select(BaseAlert).set_create_time() with pytest.raises(ApiError): api.select(BaseAlert).set_create_time(start="2019-09-30T12:34:56", end="2019-10-01T12:00:12", range="-3w") with pytest.raises(ApiError): api.select(BaseAlert).set_create_time(start="2019-09-30T12:34:56", range="-3w") with pytest.raises(ApiError): api.select(BaseAlert).set_create_time(end="2019-10-01T12:00:12", range="-3w")
def test_simple_query(monkeypatch): """Test SimpleQuery methods using a FeedQuery for API calls""" _was_called = False def _get_results(url, **kwargs): nonlocal _was_called assert url == "/threathunter/feedmgr/v2/orgs/WNEX/feeds" _was_called = True return { "results": [{ "name": "My Feed", "owner": "WNEX", "provider_url": "https://exampleprovider.com", "summary": "this is the summary", "category": "this is the category", "source_label": None, "access": "public", "id": "my_feed_id" }] } api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="WNEX", ssl_verify=True) patch_cbapi(monkeypatch, api, GET=_get_results) feed = api.select(Feed).where(include_public=True) assert isinstance(feed, SimpleQuery) assert isinstance(feed, FeedQuery) results = feed.results assert isinstance(results, list) assert isinstance(results[0], Feed) assert results[0].id == "my_feed_id" assert results[0].name == "My Feed" assert _was_called simpleQuery = SimpleQuery(Feed, api) assert simpleQuery._doc_class == Feed assert str( simpleQuery._urlobject) == "/threathunter/feedmgr/v2/orgs/{}/feeds" assert isinstance(simpleQuery, SimpleQuery) assert simpleQuery._cb == api assert simpleQuery._results == [] assert simpleQuery._query == {} clonedSimple = simpleQuery._clone() assert clonedSimple._cb == simpleQuery._cb assert clonedSimple._results == simpleQuery._results assert clonedSimple._query == simpleQuery._query
def test_Device_lr_session(monkeypatch): """Test the call to set up a Live Response session for a device.""" def _get_session(url, parms=None, default=None): assert url == "/appservices/v6/orgs/Z100/devices/6023" return {"id": 6023} api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) sked = StubScheduler(6023) api._lr_scheduler = sked patch_cbc_sdk_api(monkeypatch, api, GET=_get_session) dev = Device(api, 6023, {"id": 6023}) sess = dev.lr_session() assert sess["itworks"] assert sked.was_called
def test_run_stop(monkeypatch): """Test stopping a running query.""" _was_called = False def _execute_stop(url, body, **kwargs): nonlocal _was_called assert url == "/livequery/v1/orgs/Z100/runs/abcdefg/status" assert body == {"status": "CANCELLED"} _was_called = True return StubResponse({ "org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg", "status": "CANCELLED" }) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, PUT=_execute_stop) run = Run( api, "abcdefg", { "org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg", "status": "ACTIVE" }) rc = run.stop() assert _was_called assert rc assert run.org_key == "Z100" assert run.name == "FoobieBletch" assert run.id == "abcdefg" assert run.status == "CANCELLED"
def test_run_stop_failed(monkeypatch): """Test the failure to stop a running query.""" _was_called = False def _execute_stop(url, body, **kwargs): nonlocal _was_called assert url == "/livequery/v1/orgs/Z100/runs/abcdefg/status" assert body == {"status": "CANCELLED"} _was_called = True return StubResponse( {"error_message": "The query is not presently running."}, 409) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, PUT=_execute_stop) run = Run( api, "abcdefg", { "org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg", "status": "CANCELLED" }) rc = run.stop() assert _was_called assert not rc
def test_simple_get(monkeypatch): _was_called = False def _get_run(url, parms=None, default=None): nonlocal _was_called assert url == "/livequery/v1/orgs/Z100/runs/abcdefg" _was_called = True return {"org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg"} api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, GET=_get_run) run = api.select(Run, "abcdefg") assert _was_called assert run.org_key == "Z100" assert run.name == "FoobieBletch" assert run.id == "abcdefg"
def test_Device_bypass(monkeypatch): _was_called = False def _get_device(url, parms=None, default=None): assert url == "/appservices/v6/orgs/Z100/devices/6023" return {"id": 6023} def _bypass(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == { "action_type": "BYPASS", "device_id": [6023], "options": { "toggle": "OFF" } } _was_called = True return StubResponse(None, 204) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, GET=_get_device, POST=_bypass) dev = Device(api, 6023, {"id": 6023}) dev.bypass(False) assert _was_called
def test_Device_update_policy(monkeypatch): _was_called = False def _get_device(url, parms=None, default=None): assert url == "/appservices/v6/orgs/Z100/devices/6023" return {"id": 6023} def _update_policy(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == { "action_type": "UPDATE_POLICY", "device_id": [6023], "options": { "policy_id": 8675309 } } _was_called = True return StubResponse(None, 204) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, GET=_get_device, POST=_update_policy) dev = Device(api, 6023, {"id": 6023}) dev.update_policy(8675309) assert _was_called
def test_Device_background_scan(monkeypatch): """Test the call to set the background scan status for a device.""" _was_called = False def _get_device(url, parms=None, default=None): assert url == "/appservices/v6/orgs/Z100/devices/6023" return {"id": 6023} def _background_scan(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == { "action_type": "BACKGROUND_SCAN", "device_id": [6023], "options": { "toggle": "ON" } } _was_called = True return StubResponse(None, 204) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, GET=_get_device, POST=_background_scan) dev = Device(api, 6023, {"id": 6023}) dev.background_scan(True) assert _was_called
def test_Device_update_sensor_version(monkeypatch): """Test the call to update the sensor version for a device.""" _was_called = False def _get_device(url, parms=None, default=None): assert url == "/appservices/v6/orgs/Z100/devices/6023" return {"id": 6023} def _update_sensor_version(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == { "action_type": "UPDATE_SENSOR_VERSION", "device_id": [6023], "options": { "sensor_version": { "RHEL": "2.3.4.5" } } } _was_called = True return StubResponse(None, 204) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, GET=_get_device, POST=_update_sensor_version) dev = Device(api, 6023, {"id": 6023}) dev.update_sensor_version({"RHEL": "2.3.4.5"}) assert _was_called
def test_Device_uninstall_sensor(monkeypatch): """Test the call to uninstall the sensor for a device.""" _was_called = False def _get_device(url, parms=None, default=None): assert url == "/appservices/v6/orgs/Z100/devices/6023" return {"id": 6023} def _uninstall_sensor(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == {"action_type": "UNINSTALL_SENSOR", "device_id": [6023]} _was_called = True return StubResponse(None, 204) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, GET=_get_device, POST=_uninstall_sensor) dev = Device(api, 6023, {"id": 6023}) dev.uninstall_sensor() assert _was_called
def test_run_delete_failed(monkeypatch): """Test a failure in the attempt to delete a query.""" _was_called = False def _execute_delete(url): nonlocal _was_called assert url == "/livequery/v1/orgs/Z100/runs/abcdefg" _was_called = True return StubResponse(None, 403) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, DELETE=_execute_delete) run = Run( api, "abcdefg", { "org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg", "status": "ACTIVE" }) rc = run.delete() assert _was_called assert not rc assert not run._is_deleted
def test_run_refresh(monkeypatch): """Test refreshing a query view.""" _was_called = False def _get_run(url, parms=None, default=None): nonlocal _was_called assert url == "/livequery/v1/orgs/Z100/runs/abcdefg" _was_called = True return { "org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg", "status": "COMPLETE" } api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbc_sdk_api(monkeypatch, api, GET=_get_run) run = Run( api, "abcdefg", { "org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg", "status": "ACTIVE" }) rc = run.refresh() assert _was_called assert rc assert run.org_key == "Z100" assert run.name == "FoobieBletch" assert run.id == "abcdefg" assert run.status == "COMPLETE"
def test_alerts_bulk_undismiss_threat(monkeypatch): _was_called = False def _do_update(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/threat/workflow/_criteria" assert body == {"threat_id": ["B0RG", "F3R3NG1"], "state": "OPEN", "remediation_state": "Fixed", "comment": "NoSir"} _was_called = True return StubResponse({"request_id": "497ABX"}) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, POST=_do_update) reqid = api.bulk_threat_update(["B0RG", "F3R3NG1"], "Fixed", "NoSir") assert _was_called assert reqid == "497ABX"
def test_run_delete(monkeypatch): _was_called = False def _execute_delete(url): nonlocal _was_called assert url == "/livequery/v1/orgs/Z100/runs/abcdefg" if _was_called: pytest.fail("_execute_delete should not be called twice!") _was_called = True return StubResponse(None) api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True) patch_cbapi(monkeypatch, api, DELETE=_execute_delete) run = Run( api, "abcdefg", { "org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg", "status": "ACTIVE" }) rc = run.delete() assert _was_called assert rc assert run._is_deleted # Now ensure that certain operations that don't make sense on a deleted object raise ApiError with pytest.raises(ApiError): run.refresh() with pytest.raises(ApiError): run.stop() # And make sure that deleting a deleted object returns True immediately rc = run.delete() assert rc