Skip to content

Commit 9e636f6

Browse files
author
Juliya Smith
authored
Chore/remove error handling (#132)
1 parent 2e5d375 commit 9e636f6

14 files changed

Lines changed: 181 additions & 270 deletions

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
"c42eventextractor==0.4.0",
3737
"keyring==18.0.1",
3838
"keyrings.alt==3.2.0",
39-
"py42>=1.7.0",
39+
"py42>=1.8.1",
4040
],
4141
extras_require={
4242
"dev": [

src/code42cli/cmds/alert_rules.py

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,13 @@
22

33
import click
44
from click import echo
5-
from py42.exceptions import Py42InternalServerError
65
from py42.util import format_json
76

87
from code42cli import PRODUCT_NAME
98
from code42cli.bulk import generate_template_cmd_factory
109
from code42cli.bulk import run_bulk_process
1110
from code42cli.cmds.shared import get_user_id
1211
from code42cli.errors import Code42CLIError
13-
from code42cli.errors import InvalidRuleTypeError
1412
from code42cli.file_readers import read_csv_arg
1513
from code42cli.options import format_option
1614
from code42cli.options import OrderedGroup
@@ -152,23 +150,15 @@ def handle_row(rule_id, username):
152150
def _add_user(sdk, rule_id, username):
153151
user_id = get_user_id(sdk, username)
154152
rules = _get_rule_metadata(sdk, rule_id)
155-
try:
156-
if rules:
157-
sdk.alerts.rules.add_user(rule_id, user_id)
158-
except Py42InternalServerError:
159-
_check_if_system_rule(rules)
160-
raise
153+
if rules:
154+
sdk.alerts.rules.add_user(rule_id, user_id)
161155

162156

163157
def _remove_user(sdk, rule_id, username):
164158
user_id = get_user_id(sdk, username)
165159
rules = _get_rule_metadata(sdk, rule_id)
166-
try:
167-
if rules:
168-
sdk.alerts.rules.remove_user(rule_id, user_id)
169-
except Py42InternalServerError:
170-
_check_if_system_rule(rules)
171-
raise
160+
if rules:
161+
sdk.alerts.rules.remove_user(rule_id, user_id)
172162

173163

174164
def _get_all_rules_metadata(sdk):
@@ -185,18 +175,13 @@ def _get_rule_metadata(sdk, rule_id):
185175

186176

187177
def _handle_rules_results(rules, rule_id=None):
188-
id_msg = "with RuleId {} ".format(rule_id) if rule_id else ""
189-
msg = "No alert rules {}found.".format(id_msg)
190178
if not rules:
179+
id_msg = "with RuleId {} ".format(rule_id) if rule_id else ""
180+
msg = "No alert rules {}found.".format(id_msg)
191181
echo(msg)
192182
return rules
193183

194184

195-
def _check_if_system_rule(rules):
196-
if rules and rules[0]["isSystem"]:
197-
raise InvalidRuleTypeError(rules[0]["observerRuleId"], rules[0]["ruleSource"])
198-
199-
200185
def _get_rule_type_func(sdk, rule_type):
201186
if rule_type == AlertRuleTypes.EXFILTRATION:
202187
return sdk.alerts.rules.exfiltration.get

src/code42cli/cmds/departing_employee.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
import click
2-
from py42.exceptions import Py42BadRequestError
32

43
from code42cli.bulk import generate_template_cmd_factory
54
from code42cli.bulk import run_bulk_process
6-
from code42cli.cmds.detectionlists import try_handle_user_already_added_error
75
from code42cli.cmds.detectionlists import update_user
86
from code42cli.cmds.detectionlists.options import cloud_alias_option
97
from code42cli.cmds.detectionlists.options import notes_option
@@ -124,12 +122,8 @@ def handle_row(username):
124122

125123
def _add_departing_employee(sdk, username, cloud_alias, departure_date, notes):
126124
user_id = get_user_id(sdk, username)
127-
try:
128-
sdk.detectionlists.departing_employee.add(user_id, departure_date)
129-
update_user(sdk, username, cloud_alias=cloud_alias, notes=notes)
130-
except Py42BadRequestError as err:
131-
try_handle_user_already_added_error(err, username, "departing-employee list")
132-
raise
125+
sdk.detectionlists.departing_employee.add(user_id, departure_date)
126+
update_user(sdk, username, cloud_alias=cloud_alias, notes=notes)
133127

134128

135129
def _remove_departing_employee(sdk, username):

src/code42cli/cmds/detectionlists/__init__.py

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from code42cli.cmds.shared import get_user_id
2-
from code42cli.errors import UserAlreadyAddedError
32

43

54
def update_user(sdk, username, cloud_alias=None, risk_tag=None, notes=None):
@@ -33,18 +32,6 @@ def remove_risk_tags(sdk, username, risk_tag):
3332
sdk.detectionlists.remove_user_risk_tags(user_id, risk_tag)
3433

3534

36-
def try_handle_user_already_added_error(
37-
bad_request_err, username_tried_adding, list_name
38-
):
39-
if _error_is_user_already_added(bad_request_err.response.text):
40-
raise UserAlreadyAddedError(username_tried_adding, list_name)
41-
return False
42-
43-
44-
def _error_is_user_already_added(bad_request_error_text):
45-
return "User already on list" in bad_request_error_text
46-
47-
4835
def handle_list_args(list_arg):
4936
"""Converts str args to a list. Useful for `bulk` commands which don't use click's argument
5037
parsing but instead pass in values from files, such as in the form "item1 item2"."""

src/code42cli/cmds/high_risk_employee.py

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import click
22
from py42.clients.detectionlists import RiskTags
3-
from py42.exceptions import Py42BadRequestError
43

54
from code42cli.bulk import generate_template_cmd_factory
65
from code42cli.bulk import run_bulk_process
76
from code42cli.cmds.detectionlists import add_risk_tags as _add_risk_tags
87
from code42cli.cmds.detectionlists import handle_list_args
98
from code42cli.cmds.detectionlists import remove_risk_tags as _remove_risk_tags
10-
from code42cli.cmds.detectionlists import try_handle_user_already_added_error
119
from code42cli.cmds.detectionlists import update_user
1210
from code42cli.cmds.detectionlists.options import cloud_alias_option
1311
from code42cli.cmds.detectionlists.options import notes_option
@@ -174,15 +172,8 @@ def handle_row(username, tag):
174172
def _add_high_risk_employee(sdk, username, cloud_alias, risk_tag, notes):
175173
risk_tag = handle_list_args(risk_tag)
176174
user_id = get_user_id(sdk, username)
177-
178-
try:
179-
sdk.detectionlists.high_risk_employee.add(user_id)
180-
update_user(
181-
sdk, username, cloud_alias=cloud_alias, risk_tag=risk_tag, notes=notes
182-
)
183-
except Py42BadRequestError as err:
184-
try_handle_user_already_added_error(err, username, "high risk employees list")
185-
raise
175+
sdk.detectionlists.high_risk_employee.add(user_id)
176+
update_user(sdk, username, cloud_alias=cloud_alias, risk_tag=risk_tag, notes=notes)
186177

187178

188179
def _remove_high_risk_employee(sdk, username):

src/code42cli/cmds/legal_hold.py

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,10 @@
55

66
import click
77
from click import echo
8-
from py42.exceptions import Py42BadRequestError
9-
from py42.exceptions import Py42ForbiddenError
108

119
from code42cli.bulk import generate_template_cmd_factory
1210
from code42cli.bulk import run_bulk_process
1311
from code42cli.cmds.shared import get_user_id
14-
from code42cli.errors import LegalHoldNotFoundOrPermissionDeniedError
15-
from code42cli.errors import UserAlreadyAddedError
1612
from code42cli.errors import UserNotInLegalHoldError
1713
from code42cli.file_readers import read_csv_arg
1814
from code42cli.options import format_option
@@ -185,16 +181,8 @@ def handle_row(matter_id, username):
185181

186182
def _add_user_to_legal_hold(sdk, matter_id, username):
187183
user_id = get_user_id(sdk, username)
188-
matter = _check_matter_is_accessible(sdk, matter_id)
189-
try:
190-
sdk.legalhold.add_to_matter(user_id, matter_id)
191-
except Py42BadRequestError as e:
192-
if "USER_ALREADY_IN_HOLD" in e.response.text:
193-
matter_id_and_name_text = "legal hold matter id={}, name={}".format(
194-
matter_id, matter["name"]
195-
)
196-
raise UserAlreadyAddedError(username, matter_id_and_name_text)
197-
raise
184+
_check_matter_is_accessible(sdk, matter_id)
185+
sdk.legalhold.add_to_matter(user_id, matter_id)
198186

199187

200188
def _remove_user_from_legal_hold(sdk, matter_id, username):
@@ -255,8 +243,4 @@ def _print_matter_members(username_list, member_type="active"):
255243

256244
@lru_cache(maxsize=None)
257245
def _check_matter_is_accessible(sdk, matter_id):
258-
try:
259-
matter = sdk.legalhold.get_matter_by_uid(matter_id)
260-
return matter
261-
except (Py42BadRequestError, Py42ForbiddenError):
262-
raise LegalHoldNotFoundOrPermissionDeniedError(matter_id)
246+
return sdk.legalhold.get_matter_by_uid(matter_id)

src/code42cli/cmds/shared.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55

66
@lru_cache(maxsize=None)
77
def get_user_id(sdk, username):
8-
"""Returns the user's UID (referred to by `user_id` in detection lists). Raises
9-
`UserDoesNotExistError` if the user doesn't exist in the Code42 server.
8+
"""Returns the user's UID (referred to by `user_id` in detection lists).
9+
Raises `UserDoesNotExistError` if the user doesn't exist in the Code42 server.
1010
1111
Args:
1212
sdk (py42.sdk.SDKClient): The py42 sdk.

src/code42cli/errors.py

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
from click._compat import get_text_stderr
66
from py42.exceptions import Py42ForbiddenError
77
from py42.exceptions import Py42HTTPError
8+
from py42.exceptions import Py42InvalidRuleOperationError
9+
from py42.exceptions import Py42LegalHoldNotFoundOrPermissionDeniedError
10+
from py42.exceptions import Py42UserAlreadyAddedError
811

912
from code42cli.logger import get_main_cli_logger
1013
from code42cli.logger import get_view_error_details_message
@@ -52,19 +55,6 @@ def format_message(self):
5255
)
5356

5457

55-
class UserAlreadyAddedError(Code42CLIError):
56-
def __init__(self, username, list_name):
57-
msg = "'{}' is already on the {}.".format(username, list_name)
58-
super().__init__(msg)
59-
60-
61-
class InvalidRuleTypeError(Code42CLIError):
62-
def __init__(self, rule_id, source):
63-
msg = "Only alert rules with a source of 'Alerting' can be targeted by this command. "
64-
msg += "Rule {0} has a source of '{1}'."
65-
super().__init__(msg.format(rule_id, source))
66-
67-
6858
class UserDoesNotExistError(Code42CLIError):
6959
"""An error to represent a username that is not in our system. The CLI shows this error when
7060
the user tries to add or remove a user that does not exist. This error is not shown during
@@ -77,20 +67,12 @@ def __init__(self, username):
7767
class UserNotInLegalHoldError(Code42CLIError):
7868
def __init__(self, username, matter_id):
7969
super().__init__(
80-
"User '{}' is not an active member of legal hold matter '{}'".format(
70+
"User '{}' is not an active member of legal hold matter '{}'.".format(
8171
username, matter_id
8272
)
8373
)
8474

8575

86-
class LegalHoldNotFoundOrPermissionDeniedError(Code42CLIError):
87-
def __init__(self, matter_id):
88-
super().__init__(
89-
"Matter with id={} either does not exist or your profile does not have permission to "
90-
"view it.".format(matter_id)
91-
)
92-
93-
9476
class ExceptionHandlingGroup(click.Group):
9577
"""Custom click.Group subclass to add custom exception handling."""
9678

@@ -124,6 +106,15 @@ def invoke(self, ctx):
124106
except click.exceptions.Exit:
125107
raise
126108

109+
except (
110+
UserDoesNotExistError,
111+
Py42UserAlreadyAddedError,
112+
Py42InvalidRuleOperationError,
113+
Py42LegalHoldNotFoundOrPermissionDeniedError,
114+
) as err:
115+
self.logger.log_error(err)
116+
raise Code42CLIError(str(err))
117+
127118
except Py42ForbiddenError as err:
128119
self.logger.log_verbose_error(self._original_args, err.response.request)
129120
raise LoggedCLIError(

tests/cmds/conftest.py

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,19 @@
22
import threading
33

44
import pytest
5-
from py42.exceptions import Py42BadRequestError
5+
from py42.exceptions import Py42UserAlreadyAddedError
66
from py42.sdk import SDKClient
77
from requests import HTTPError
8-
from requests import Request
98
from requests import Response
109
from tests.conftest import convert_str_to_date
10+
from tests.conftest import TEST_ID
1111

1212
from code42cli.logger import CliLogger
1313

1414

15+
TEST_EMPLOYEE = "risky employee"
16+
17+
1518
@pytest.fixture
1619
def sdk(mocker):
1720
return mocker.MagicMock(spec=SDKClient)
@@ -56,26 +59,12 @@ def cli_state_without_user(sdk_without_user, cli_state):
5659

5760

5861
@pytest.fixture
59-
def bad_request_for_user_already_added(mocker):
60-
resp = mocker.MagicMock(spec=Response)
61-
resp.text = "User already on list"
62-
return _create_bad_request_mock(resp)
63-
64-
65-
@pytest.fixture
66-
def generic_bad_request(mocker):
62+
def user_already_added_error(mocker):
63+
err = mocker.MagicMock(spec=HTTPError)
6764
resp = mocker.MagicMock(spec=Response)
68-
req = mocker.MagicMock(spec=Request)
69-
req.body = '{"test":"body"}'
70-
resp.request = req
71-
resp.text = "TEST"
72-
return _create_bad_request_mock(resp)
73-
74-
75-
def _create_bad_request_mock(resp):
76-
base_err = HTTPError()
77-
base_err.response = resp
78-
return Py42BadRequestError(base_err)
65+
resp.text = "TEST_ERR"
66+
err.response = resp
67+
return Py42UserAlreadyAddedError(err, TEST_ID, "detection list")
7968

8069

8170
def get_filter_value_from_json(json, filter_index):

0 commit comments

Comments
 (0)